@@ -1,3468 +0,0 @@
1−@file:Suppress("TooManyFunctions")
2−
3−package soy.iko.opencode.ui.chat
4−
5−import android.app.Activity
6−import android.content.Intent
7−import android.net.Uri
8−import android.speech.RecognizerIntent
9−import androidx.activity.compose.BackHandler
10−import androidx.activity.compose.rememberLauncherForActivityResult
11−import androidx.activity.result.PickVisualMediaRequest
12−import androidx.activity.result.contract.ActivityResultContracts
13−import androidx.compose.animation.AnimatedVisibility
14−import androidx.compose.animation.core.RepeatMode
15−import androidx.compose.animation.core.animateFloat
16−import androidx.compose.animation.core.infiniteRepeatable
17−import androidx.compose.animation.core.rememberInfiniteTransition
18−import androidx.compose.animation.core.tween
19−import androidx.compose.foundation.background
20−import androidx.compose.foundation.clickable
21−import androidx.compose.foundation.content.contentReceiver
22−import androidx.compose.foundation.layout.Arrangement
23−import androidx.compose.foundation.layout.Box
24−import androidx.compose.foundation.layout.Column
25−import androidx.compose.foundation.layout.FlowRow
26−import androidx.compose.foundation.layout.PaddingValues
27−import androidx.compose.foundation.layout.Row
28−import androidx.compose.foundation.layout.Spacer
29−import androidx.compose.foundation.layout.WindowInsets
30−import androidx.compose.foundation.layout.fillMaxSize
31−import androidx.compose.foundation.layout.fillMaxWidth
32−import androidx.compose.foundation.layout.heightIn
33−import androidx.compose.foundation.layout.height
34−import androidx.compose.foundation.layout.imePadding
35−import androidx.compose.foundation.layout.ime
36−import androidx.compose.foundation.layout.navigationBars
37−import androidx.compose.foundation.layout.padding
38−import androidx.compose.foundation.layout.size
39−import androidx.compose.foundation.layout.union
40−import androidx.compose.foundation.layout.widthIn
41−import androidx.compose.foundation.layout.windowInsetsPadding
42−import androidx.compose.foundation.layout.wrapContentWidth
43−import androidx.compose.foundation.lazy.LazyColumn
44−import androidx.compose.foundation.lazy.items
45−import androidx.compose.foundation.lazy.rememberLazyListState
46−import androidx.compose.foundation.shape.RoundedCornerShape
47−import androidx.compose.material.icons.Icons
48−import androidx.compose.material.icons.automirrored.filled.ArrowBack
49−import androidx.compose.material.icons.automirrored.filled.Send
50−import androidx.compose.material.icons.filled.ErrorOutline
51−import androidx.compose.material.icons.filled.Add
52−import androidx.compose.material.icons.filled.AutoAwesome
53−import androidx.compose.material.icons.filled.Delete
54−import androidx.compose.material.icons.filled.Description
55−import androidx.compose.material.icons.filled.Close
56−import androidx.compose.material.icons.filled.Edit
57−import androidx.compose.material.icons.filled.Expand
58−import androidx.compose.material.icons.filled.FormatQuote
59−import androidx.compose.material.icons.filled.ExpandLess
60−import androidx.compose.material.icons.filled.ExpandMore
61−import androidx.compose.material.icons.filled.Search
62−import androidx.compose.material.icons.filled.KeyboardArrowDown
63−import androidx.compose.material.icons.filled.KeyboardArrowUp
64−import androidx.compose.material.icons.filled.Mic
65−import androidx.compose.material.icons.filled.MoreVert
66−import androidx.compose.material.icons.filled.PhotoCamera
67−import androidx.compose.material.icons.filled.PhotoLibrary
68−import androidx.compose.material.icons.filled.Refresh
69−import androidx.compose.material.icons.filled.Restore
70−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
71−import androidx.compose.material.icons.automirrored.filled.Reply
72−import androidx.compose.material.icons.filled.Schedule
73−import androidx.compose.material.icons.filled.Stop
74−import androidx.compose.material3.AlertDialog
75−import androidx.compose.material3.Badge
76−import androidx.compose.material3.BadgedBox
77−import androidx.compose.material3.Button
78−import androidx.compose.material3.CircularProgressIndicator
79−import androidx.compose.material3.SmallFloatingActionButton
80−import androidx.compose.material3.DropdownMenu
81−import androidx.compose.material3.DropdownMenuItem
82−import androidx.compose.material3.ExperimentalMaterial3Api
83−import androidx.compose.material3.ExtendedFloatingActionButton
84−import androidx.compose.material3.FloatingActionButton
85−import androidx.compose.material3.Icon
86−import androidx.compose.material3.IconButton
87−import androidx.compose.material3.MaterialTheme
88−import androidx.compose.material3.OutlinedTextField
89−import androidx.compose.material3.Scaffold
90−import androidx.compose.material3.SnackbarDuration
91−import androidx.compose.material3.SwipeToDismissBox
92−import androidx.compose.material3.SwipeToDismissBoxValue
93−import androidx.compose.material3.rememberSwipeToDismissBoxState
94−import androidx.compose.material3.SnackbarHost
95−import androidx.compose.material3.SnackbarHostState
96−import androidx.compose.material3.SnackbarResult
97−import androidx.compose.material3.Surface
98−import androidx.compose.material3.Text
99−import androidx.compose.material3.TextButton
100−import androidx.compose.material3.TopAppBar
101−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
102−import androidx.compose.runtime.Composable
103−import androidx.compose.runtime.CompositionLocalProvider
104−import androidx.compose.runtime.DisposableEffect
105−import androidx.compose.runtime.LaunchedEffect
106−import androidx.compose.runtime.derivedStateOf
107−import androidx.compose.runtime.getValue
108−import androidx.compose.runtime.mutableIntStateOf
109−import androidx.compose.runtime.mutableLongStateOf
110−import androidx.compose.runtime.mutableStateOf
111−import androidx.compose.runtime.produceState
112−import androidx.compose.runtime.remember
113−import androidx.compose.runtime.rememberCoroutineScope
114−import androidx.compose.runtime.rememberUpdatedState
115−import androidx.compose.runtime.saveable.rememberSaveable
116−import androidx.compose.runtime.setValue
117−import androidx.compose.runtime.snapshotFlow
118−import androidx.compose.foundation.text.KeyboardActions
119−import androidx.compose.foundation.text.KeyboardOptions
120−import androidx.compose.ui.text.input.KeyboardCapitalization
121−import androidx.compose.ui.Alignment
122−import androidx.compose.ui.Modifier
123−import androidx.compose.ui.draw.alpha
124−import androidx.compose.ui.draw.clip
125−import androidx.compose.ui.focus.focusRequester
126−import androidx.compose.ui.input.key.Key
127−import androidx.compose.ui.input.key.KeyEventType
128−import androidx.compose.ui.input.key.isCtrlPressed
129−import androidx.compose.ui.input.key.isShiftPressed
130−import androidx.compose.ui.input.key.key
131−import androidx.compose.ui.input.key.onPreviewKeyEvent
132−import androidx.compose.ui.input.key.type
133−import androidx.compose.ui.layout.onSizeChanged
134−import androidx.compose.ui.platform.LocalContext
135−import androidx.compose.ui.platform.LocalDensity
136−import androidx.compose.ui.platform.LocalHapticFeedback
137−import androidx.compose.ui.platform.LocalLayoutDirection
138−import androidx.compose.ui.platform.LocalView
139−import androidx.compose.ui.platform.testTag
140−import androidx.compose.ui.unit.LayoutDirection
141−import androidx.compose.ui.res.pluralStringResource
142−import androidx.compose.ui.res.stringResource
143−import androidx.compose.ui.semantics.Role
144−import androidx.compose.ui.semantics.contentDescription
145−import androidx.compose.ui.semantics.heading
146−import androidx.compose.ui.semantics.liveRegion
147−import androidx.compose.ui.semantics.LiveRegionMode
148−import androidx.compose.ui.semantics.invisibleToUser
149−import androidx.compose.ui.semantics.semantics
150−import androidx.compose.ui.text.input.ImeAction
151−import androidx.compose.ui.text.style.TextOverflow
152−import androidx.compose.ui.unit.dp
153−import androidx.lifecycle.compose.collectAsStateWithLifecycle
154−import androidx.lifecycle.viewmodel.compose.viewModel
155−import kotlinx.coroutines.Dispatchers
156−import kotlinx.coroutines.coroutineScope
157−import kotlinx.coroutines.delay
158−import kotlinx.coroutines.flow.collectLatest
159−import kotlinx.coroutines.flow.distinctUntilChanged
160−import kotlinx.coroutines.flow.first
161−import kotlinx.coroutines.launch
162−import kotlinx.coroutines.withContext
163−import soy.iko.opencode.data.model.Part
164−import soy.iko.opencode.data.model.MessageWithParts
165−import soy.iko.opencode.data.model.AssistantMessage
166−import soy.iko.opencode.data.model.Command
167−import soy.iko.opencode.data.model.ReasoningPart
168−import soy.iko.opencode.data.model.TextPart
169−import soy.iko.opencode.data.model.ToolCompleted
170−import soy.iko.opencode.data.model.ToolError
171−import soy.iko.opencode.data.model.ToolPart
172−import soy.iko.opencode.data.model.ToolRunning
173−import soy.iko.opencode.data.model.FilePart
174−import soy.iko.opencode.data.model.sourcePath
175−import soy.iko.opencode.data.model.inputElement
176−import soy.iko.opencode.data.network.EventStreamClient
177−import soy.iko.opencode.data.network.NetworkConfig
178−import soy.iko.opencode.di.AppContainer
179−import soy.iko.opencode.R
180−import soy.iko.opencode.ui.components.CommandPalette
181−import soy.iko.opencode.ui.components.ConnectionBanner
182−import soy.iko.opencode.ui.components.DiffView
183−import soy.iko.opencode.ui.components.PaletteAction
184−import soy.iko.opencode.ui.components.LocalReducedMotion
185−import soy.iko.opencode.ui.components.LocalSearchHighlight
186−
187−import soy.iko.opencode.ui.components.copyToClipboard
188−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
189−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
190−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
191−import soy.iko.opencode.ui.components.showToast
192−import soy.iko.opencode.ui.components.toImageContext
193−import soy.iko.opencode.ui.vmFactory
194−import soy.iko.opencode.util.runCatchingCancellable
195−
196−// Optional message id to scroll to and briefly highlight on first load (from global search).
197−// Consumed once: after the message is scrolled into view and highlighted, the focus is
198−// cleared so subsequent recompositions don't re-trigger the scroll.
199−@OptIn(ExperimentalMaterial3Api::class)
200−@Composable
201−fun ChatScreen(
202− container: AppContainer,
203− sessionId: String,
204− onBack: () -> Unit,
205− onOpenFile: ((String) -> Unit)? = null,
206− onOpenSession: ((String) -> Unit)? = null,
207− focusMessageId: String? = null,
208− onEditProfile: ((String) -> Unit)? = null,
209−) {
210− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
211− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
212− val running by vm.running.collectAsStateWithLifecycle()
213− val streamInterrupted by vm.streamInterrupted.collectAsStateWithLifecycle()
214− val aborting by vm.aborting.collectAsStateWithLifecycle()
215− val loading by vm.loading.collectAsStateWithLifecycle()
216− val loadError by vm.loadError.collectAsStateWithLifecycle()
217− val loadErrorInline by vm.loadErrorInline.collectAsStateWithLifecycle()
218− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
219− val models by vm.models.collectAsStateWithLifecycle()
220− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
221− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
222− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
223− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
224− val reconnectAttempts by vm.reconnectAttempts.collectAsStateWithLifecycle()
225− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
226− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
227− val agents by vm.agents.collectAsStateWithLifecycle()
228− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
229− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
230− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
231− val commands by vm.commands.collectAsStateWithLifecycle()
232− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
233− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
234− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
235− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
236− val draft by vm.draft.collectAsStateWithLifecycle()
237− val pendingQuote by vm.pendingQuote.collectAsStateWithLifecycle()
238− val attachments by vm.attachments.collectAsStateWithLifecycle()
239− val reverted by vm.reverted.collectAsStateWithLifecycle()
240− val editing by vm.editing.collectAsStateWithLifecycle()
241− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
242− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
243− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
244− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
245− val preferredModelId by container.settingsStore.preferredModelId.collectAsStateWithLifecycle(initialValue = "")
246− val recentModelEntries by container.recentModelsStore.entries.collectAsStateWithLifecycle()
247− val compactSpacing by container.settingsStore.compactMessageSpacing.collectAsStateWithLifecycle(initialValue = false)
248− val notifPermission by container.settingsStore.notifPermission.collectAsStateWithLifecycle(initialValue = true)
249− val isOnline by container.isOnline.collectAsStateWithLifecycle()
250− val haptics = LocalHapticFeedback.current
251− val layoutDirection = LocalLayoutDirection.current
252− val scope = rememberCoroutineScope()
253− val shareContext = LocalContext.current
254− val defaultShareSubject = stringResource(R.string.share_subject)
255− val sessionLabel = stringResource(R.string.session)
256− val defaultModelLabel = stringResource(R.string.default_model)
257− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
258− buildString {
259− append(selectedModel?.modelLabel ?: defaultModelLabel)
260− selectedAgent?.let { append(" · $it") }
261− }
262− }
263−
264− // Connection profile (with auth) for rendering inline image attachments.
265− // Collect as state so a server switch recomposes the image context.
266− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
267− val imageContext = remember(activeConnection?.profile) {
268− activeConnection?.profile?.toImageContext()
269− }
270−
271− // Mark this session as read while the user is viewing it; clear on leave so new
272− // background activity can badge it again.
273− DisposableEffect(sessionId) {
274− container.setCurrentSession(sessionId)
275− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
276− }
277−
278− // Navigate away when the session is deleted via SSE so the user isn't left
279− // on a zombie screen showing a conversation that no longer exists. Surface a
280− // toast (not a snackbar) because the screen is about to be popped — a snackbar
281− // would be torn down before the user could read it, while a toast survives.
282− // Covers both SSE-driven deletion (deleted on another device) and a user-
283− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
284− // sets the same flag on success).
285− val deletedContext = LocalContext.current
286− LaunchedEffect(sessionDeleted) {
287− if (sessionDeleted) {
288− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
289− onBack()
290− }
291− }
292−
293− val snackbar = remember { SnackbarHostState() }
294− val retryLabel = stringResource(R.string.retry)
295− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
296− // Dedicated focus requester for the in-conversation search field. The overflow menu's
297− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
298− // (the composer), so typing went to the composer instead of the search field.
299− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
300− var showModelPicker by rememberSaveable { mutableStateOf(false) }
301− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
302− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
303− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
304− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
305− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
306− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
307− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
308− var showShellDialog by rememberSaveable { mutableStateOf(false) }
309− var showPalette by rememberSaveable { mutableStateOf(false) }
310− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
311− var searchActive by rememberSaveable { mutableStateOf(false) }
312− var chatSearch by rememberSaveable { mutableStateOf("") }
313− // Index of the currently-focused in-conversation search match (into the filtered list).
314− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
315− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
316− // required reading each message to find the term).
317− var searchPos by rememberSaveable { mutableIntStateOf(0) }
318− var searchFiltering by remember { mutableStateOf(false) }
319− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
320− // a confirmation dialog (from both the overflow menu and the command palette).
321− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
322− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
323−
324− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
325− // action list doesn't need a Composable context. Actions map to the same handlers the
326− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
327− val paletteModelLabel = stringResource(R.string.palette_switch_model)
328− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
329− val paletteCommandLabel = stringResource(R.string.palette_run_command)
330− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
331− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
332− val paletteShellLabel = stringResource(R.string.run_shell_command)
333− val paletteActions = remember(
334− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
335− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
336− ) {
337− buildList {
338− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
339− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
340− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
341− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
342− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
343− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
344− }
345− }
346−
347− // Keep the screen awake while the agent is working in *this* session. The foreground
348− // service that holds process priority during a run is managed app-wide off
349− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
350− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
351− // SSE stream before the completion notification fires.
352− val currentView = LocalView.current
353− val appContext = LocalContext.current.applicationContext
354− DisposableEffect(running) {
355− currentView.keepScreenOn = running
356− onDispose { currentView.keepScreenOn = false }
357− }
358−
359− LaunchedEffect(Unit) {
360− vm.errorEvents.collect { event ->
361− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
362− // message-load failure) would silently re-submit the last prompt on tap.
363− val result = if (event.retryable) {
364− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
365− } else {
366− snackbar.showSnackbar(event.message)
367− }
368− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
369− }
370− }
371−
372− // Stop-undo: abort() emits the last-sent prompt here so this collector can show a
373− // "Stopped — Undo" snackbar. Tapping Undo re-sends the prompt, recovering an accidental
374− // Stop without a confirmation dialog (Stop now happens on first tap).
375− val undoStopLabel = stringResource(R.string.undo)
376− val stoppedLabel = stringResource(R.string.run_stopped_undo)
377− LaunchedEffect(Unit) {
378− vm.stopUndoEvents.collect { prompt ->
379− if (prompt != null) {
380− val result = snackbar.showSnackbar(message = stoppedLabel, actionLabel = undoStopLabel)
381− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.resendLastPrompt()
382− }
383− }
384− }
385−
386− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
387− // window on the container; show the snackbar over the conversation the user is viewing so
388− // they can cancel without being navigated to the session list first. If the window expires
389− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
390− //
391− // collectLatest (not collect): a serialized collect queues each snackbar behind the
392− // previous one's full window, so under a rapid re-delete (delete A, then delete the same
393− // session again, or a delete timed just after the first) the VM delete timer (started at
394− // emit time) fires before the second snackbar is ever shown — a dead Undo button.
395− // collectLatest cancels the current snackbar and shows the newest immediately, keeping its
396− // Undo window aligned with its timer. Tracking `pending` mirrors SessionListScreen: when a
397− // newer delete supersedes the prior snackbar mid-window, the prior session's deferred REST
398− // delete (still scheduled on the container's scope) would fire with no reachable Undo.
399− // Withdrawing it via cancelSessionDelete cancels the timer (no-op if it already fired), so
400− // no session is silently deleted without a chance to undo.
401− val undoLabel = stringResource(R.string.undo)
402− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
403− LaunchedEffect(Unit) {
404− var pending: String? = null
405− vm.deleteUndoEvents.collectLatest { id ->
406− pending?.let { vm.cancelSessionDelete(it) }
407− pending = id
408− coroutineScope {
409− val dismisser = launch {
410− delay(NetworkConfig.undoDeleteDelayMs)
411− snackbar.currentSnackbarData?.dismiss()
412− }
413− val result = snackbar.showSnackbar(
414− message = sessionDeletedLabel,
415− actionLabel = undoLabel,
416− duration = SnackbarDuration.Indefinite,
417− )
418− dismisser.cancel()
419− if (result == SnackbarResult.ActionPerformed) {
420− vm.cancelSessionDelete(id)
421− pending = null
422− }
423− }
424− }
425− }
426−
427− // --- Attachments, voice, and share-link plumbing ---
428− val attachFailedMsg = stringResource(R.string.attachment_failed)
429− val noCameraMsg = stringResource(R.string.no_camera_app)
430− val noVoiceMsg = stringResource(R.string.no_voice_app)
431− val voicePrompt = stringResource(R.string.voice_prompt)
432− val linkCopiedMsg = stringResource(R.string.link_copied)
433− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
434−
435− // Count of picks currently being read + base64-encoded off the main thread, so the
436− // composer can show a staging placeholder immediately (chips only materialize once done).
437− // Backed by the ViewModel (vm.stagingCount / vm.stagingFileTotal) so the staging state
438− // survives a configuration change: the encode work runs on viewModelScope (which
439− // survives rotation), so the counters must live on the VM too — remember { mutableStateOf
440− // } in the composable would reset to 0 on rotation and lose the staging chip mid-encode.
441− val stagingCount by vm.stagingCount.collectAsStateWithLifecycle()
442− val stagingFileTotal by vm.stagingFileTotal.collectAsStateWithLifecycle()
443−
444− // Convert each picked Uri to a base64 attachment on the VM's scope (survives rotation),
445− // honoring the per-prompt count cap and surfacing per-file errors via the VM's errorEvents.
446− fun stageUris(uris: List<Uri>) {
447− vm.stageUris(uris, appContext)
448− }
449−
450− val photoPicker = rememberLauncherForActivityResult(
451− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
452− ) { uris -> stageUris(uris) }
453−
454− val filePicker = rememberLauncherForActivityResult(
455− ActivityResultContracts.GetMultipleContents(),
456− ) { uris -> stageUris(uris) }
457−
458− // Uri survives a config change mid-capture so the TakePicture result still resolves.
459− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
460− val cameraLauncher = rememberLauncherForActivityResult(
461− ActivityResultContracts.TakePicture(),
462− ) { success ->
463− val uri = pendingCaptureUri
464− pendingCaptureUri = null
465− if (success && uri != null) stageUris(listOf(uri))
466− }
467−
468− val voiceLauncher = rememberLauncherForActivityResult(
469− ActivityResultContracts.StartActivityForResult(),
470− ) { result ->
471− if (result.resultCode == Activity.RESULT_OK) {
472− val spoken = result.data
473− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
474− ?.firstOrNull()
475− ?.takeIf { it.isNotBlank() }
476− if (spoken != null) {
477− // Append to the existing draft rather than replacing, so dictation adds to
478− // whatever the user already typed.
479− val current = vm.draft.value
480− val combined = if (current.isBlank()) spoken else "$current $spoken"
481− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
482− }
483− }
484− }
485−
486− fun launchCamera() {
487− val uri = newCameraCaptureUri(appContext)
488− if (uri == null) {
489− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
490− return
491− }
492− pendingCaptureUri = uri
493− runCatching { cameraLauncher.launch(uri) }
494− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
495− }
496−
497− fun launchVoice() {
498− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
499− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
500− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
501− }
502− runCatching { voiceLauncher.launch(intent) }
503− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
504− }
505−
506− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
507− LaunchedEffect(Unit) {
508− vm.shareLinkEvents.collect { url ->
509− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
510− snackbar.showSnackbar(linkCopiedMsg)
511− }
512− }
513−
514− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
515− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
516− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
517− // a dropped branch-navigation event in the gap. The lambda is wrapped in rememberUpdatedState
518− // so the Unit-keyed collector invokes the LATEST lambda instead of the one captured at first
519− // composition — a latent footgun if a future change makes onOpenSession depend on current
520− // Compose state (e.g. pane-aware routing). The collector itself is never cancelled, so no
521− // event is dropped.
522− val branchedMsg = stringResource(R.string.branch_created)
523− val currentOnOpenSession by rememberUpdatedState(onOpenSession)
524− LaunchedEffect(Unit) {
525− vm.branchEvents.collect { newId ->
526− showToast(shareContext, branchedMsg)
527− currentOnOpenSession?.invoke(newId)
528− }
529− }
530−
531− // Stage images shared into the app (via the system share sheet) as attachments.
532− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
533− // while this ChatScreen is already composed — which happens in two-pane mode, where the
534− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
535− // only fire on first composition. consumePendingSharedMedia() atomically drains the
536− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
537− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
538− LaunchedEffect(pendingSharedMedia) {
539− val shared = container.consumePendingSharedMedia()
540− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
541− }
542−
543− fun doSend() {
544− if (vm.send(draft)) {
545− // TextHandleMove (a light tick) is semantically right for a send commit;
546− // LongPress is reserved for long-press/swipe gestures.
547− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
548− }
549− }
550−
551− // The in-conversation search bar is an AnimatedVisibility overlay (not a Dialog/Dropdown),
552− // so it has no built-in back handling. Close it first on back press, before the exit
553− // confirmation or navigation-away can fire — standard Android "back closes the topmost
554− // overlay" behavior. Declared before the exit-confirm BackHandler so it takes precedence
555− // when both could be active (search open + a run in progress).
556− BackHandler(enabled = searchActive) {
557− searchActive = false
558− chatSearch = ""
559− }
560−
561− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker && !searchActive) { showExitConfirm = true }
562−
563− Scaffold(
564− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
565− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
566− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
567− // typing (and the composer's own Enter-to-send handling) is untouched.
568− modifier = Modifier.onPreviewKeyEvent { ev ->
569− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
570− when {
571− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
572− // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
573− // the field so the user can type immediately.
574− ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
575− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
576− ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
577− ev.key == Key.Escape && running && !showExitConfirm -> {
578− vm.abort(); true
579− }
580− else -> false
581− }
582− },
583− topBar = {
584− TopAppBar(
585− title = {
586− val changeLabel = stringResource(R.string.change_model_agent)
587− // The subtitle reads "model · agent", so tapping the title offers *both*
588− // — a small menu picks which picker to open. Previously the tap went
589− // straight to the model picker, leaving the agent changeable only via
590− // the overflow menu despite the title implying otherwise.
591− Box {
592− Row(
593− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
594− // node; the click label rides on `clickable` (onClickLabel) instead of
595− // an explicit contentDescription, which would have SUPPRESSED the child
596− // Texts and announced only "Change model and agent".
597− modifier = Modifier
598− .clickable(
599− role = Role.Button,
600− onClickLabel = changeLabel,
601− ) { showTitleMenu = true }
602− .semantics(mergeDescendants = true) {},
603− verticalAlignment = Alignment.CenterVertically,
604− ) {
605− Column(modifier = Modifier.weight(1f, fill = false)) {
606− // maxLines=1 + Ellipsis so a long session title can't wrap and
607− // push the top bar to multiple lines, shifting the whole layout.
608− Text(
609− sessionTitle ?: sessionLabel,
610− maxLines = 1,
611− overflow = TextOverflow.Ellipsis,
612− )
613− Text(
614− subtitle,
615− style = MaterialTheme.typography.labelSmall,
616− color = MaterialTheme.colorScheme.onSurfaceVariant,
617− maxLines = 1,
618− overflow = TextOverflow.Ellipsis,
619− )
620− }
621− // Always show the affordance so the title reads as tappable even when
622− // the model catalog failed to load (models empty). Without it the title
623− // is indistinguishable from plain text and the pickers are effectively
624− // undiscoverable — and the dropdown items already disable themselves
625− // while a catalog is loading or unavailable.
626− Icon(
627− Icons.Filled.KeyboardArrowDown,
628− contentDescription = null,
629− tint = MaterialTheme.colorScheme.onSurfaceVariant,
630− modifier = Modifier.size(20.dp),
631− )
632− }
633− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
634− DropdownMenuItem(
635− text = { Text(stringResource(R.string.palette_switch_model)) },
636− enabled = !modelsLoading || models.isNotEmpty(),
637− onClick = { showTitleMenu = false; showModelPicker = true },
638− )
639− DropdownMenuItem(
640− text = { Text(stringResource(R.string.palette_choose_agent)) },
641− enabled = !agentsLoading || agents.isNotEmpty(),
642− onClick = { showTitleMenu = false; showAgentPicker = true },
643− )
644− }
645− }
646− },
647− navigationIcon = {
648− IconButton(onClick = {
649− if (running) showExitConfirm = true else onBack()
650− }) {
651− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
652− }
653− },
654− actions = {
655− // At-a-glance run status in the top bar. When the user is scrolled
656− // up (jump-to-latest FAB visible), the input-bar Stop button and the
657− // trailing "working…" row are off-screen, so a top-bar spinner is the
658− // only signal the agent is still working.
659− if (running) {
660− val workingLabel = stringResource(R.string.working)
661− CircularProgressIndicator(
662− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
663− strokeWidth = 2.dp,
664− )
665− }
666− // Manual refresh: forces an SSE reconnect, which re-seeds messages
667− // from REST. A recovery path when the stream silently drops and the
668− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
669− // immediate tap feedback — the SSE reconnect may not visibly change
670− // the connection state when already Connected, so without it the tap
671− // appears to do nothing. Disabled while a run is active: a mid-run
672− // refresh forces a reconnect that can interrupt the streaming reply,
673− // and the working spinner already signals "wait" — the recovery path
674− // is only needed when nothing is actively streaming.
675− val refreshLabel = stringResource(R.string.refresh)
676− IconButton(
677− onClick = { vm.refreshMessages() },
678− enabled = activeConnection != null && !refreshing && !running,
679− ) {
680− if (refreshing) {
681− CircularProgressIndicator(
682− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
683− strokeWidth = 2.dp,
684− )
685− } else {
686− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
687− }
688− }
689− // Overflow menu consolidates the less-frequent actions (share,
690− // commands, agent, model, rename, delete) so the top bar stays
691− // scannable on narrow phones — previously 5 icons crowded the bar
692− // alongside the back button and tappable title. Catalog-loading
693− // spinners stay inline (next to the overflow) so a load state is
694− // visible without opening the menu.
695− val moreLabel = stringResource(R.string.more)
696− val loadingLabel = stringResource(R.string.loading)
697− val shareLabel = stringResource(R.string.share_conversation)
698− val copyAsMarkdownLabel = stringResource(R.string.copy_as_markdown)
699− val shareAsJsonLabel = stringResource(R.string.share_as_json)
700− val copyAsJsonLabel = stringResource(R.string.copy_as_json)
701− val commandsLabel = stringResource(R.string.commands)
702− val renameLabel = stringResource(R.string.rename_session_chat)
703− val deleteLabel = stringResource(R.string.delete_session_chat)
704− val createShareLabel = stringResource(R.string.create_share_link)
705− val copyShareLabel = stringResource(R.string.copy_share_link)
706− val stopShareLabel = stringResource(R.string.stop_sharing)
707− val summarizeLabel = stringResource(R.string.summarize_conversation)
708− val initLabel = stringResource(R.string.generate_agents_md)
709− val shellLabel = stringResource(R.string.run_shell_command)
710− Box {
711− IconButton(onClick = { showOverflowMenu = true }) {
712− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
713− }
714− DropdownMenu(
715− expanded = showOverflowMenu,
716− onDismissRequest = { showOverflowMenu = false },
717− ) {
718− DropdownMenuItem(
719− text = { Text(shareLabel) },
720− enabled = hasMessages,
721− onClick = {
722− showOverflowMenu = false
723− scope.launch {
724− val md = withContext(Dispatchers.Default) {
725− buildConversationMarkdown(vm.messages.value, sessionTitle)
726− }
727− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
728− type = "text/markdown"
729− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
730− putExtra(android.content.Intent.EXTRA_TEXT, md)
731− }
732− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
733− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
734− }
735− },
736− )
737− // Copy the whole conversation as Markdown to the clipboard, so a
738− // user can paste into another app without the share-sheet round-trip.
739− DropdownMenuItem(
740− text = { Text(copyAsMarkdownLabel) },
741− enabled = hasMessages,
742− onClick = {
743− showOverflowMenu = false
744− scope.launch {
745− val md = withContext(Dispatchers.Default) {
746− buildConversationMarkdown(vm.messages.value, sessionTitle)
747− }
748− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
749− }
750− },
751− )
752− // Lossless JSON share: the full List<MessageWithParts> serialized with
753− // the shared OpencodeJson, so tool outputs, file sources, and reasoning
754− // survive verbatim (the Markdown export truncates/summarizes them).
755− DropdownMenuItem(
756− text = { Text(shareAsJsonLabel) },
757− enabled = hasMessages,
758− onClick = {
759− showOverflowMenu = false
760− scope.launch {
761− val json = withContext(Dispatchers.Default) {
762− buildConversationJson(vm.messages.value)
763− }
764− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
765− type = "application/json"
766− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
767− putExtra(android.content.Intent.EXTRA_TEXT, json)
768− }
769− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
770− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
771− }
772− },
773− )
774− DropdownMenuItem(
775− text = { Text(copyAsJsonLabel) },
776− enabled = hasMessages,
777− onClick = {
778− showOverflowMenu = false
779− scope.launch {
780− val json = withContext(Dispatchers.Default) {
781− buildConversationJson(vm.messages.value)
782− }
783− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
784− }
785− },
786− )
787− DropdownMenuItem(
788− text = { Text(commandsLabel) },
789− enabled = !commandsLoading || commands.isNotEmpty(),
790− onClick = { showOverflowMenu = false; showCommandPicker = true },
791− )
792− DropdownMenuItem(
793− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
794− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
795− )
796− DropdownMenuItem(
797− text = { Text(stringResource(R.string.find_in_conversation)) },
798− onClick = {
799− showOverflowMenu = false
800− searchActive = true
801− // Focus is requested by the LaunchedEffect(searchActive)
802− // below, which waits for the search field to be composed
803− // before requesting focus (calling requestFocus here would
804− // target a field that isn't in the composition yet).
805− },
806− )
807− androidx.compose.material3.HorizontalDivider()
808− // Session sharing: create a public link, copy an existing one, or revoke it.
809− if (shareUrl == null) {
810− DropdownMenuItem(
811− text = { Text(createShareLabel) },
812− enabled = hasMessages,
813− onClick = { showOverflowMenu = false; vm.shareSession() },
814− )
815− } else {
816− DropdownMenuItem(
817− text = { Text(copyShareLabel) },
818− onClick = {
819− showOverflowMenu = false
820− shareUrl?.let {
821− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
822− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
823− }
824− },
825− )
826− DropdownMenuItem(
827− text = { Text(stopShareLabel) },
828− onClick = { showOverflowMenu = false; vm.unshareSession() },
829− )
830− }
831− DropdownMenuItem(
832− text = { Text(summarizeLabel) },
833− enabled = hasMessages && !running,
834− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
835− )
836− DropdownMenuItem(
837− text = { Text(initLabel) },
838− enabled = !running,
839− onClick = { showOverflowMenu = false; showInitConfirm = true },
840− )
841− DropdownMenuItem(
842− text = { Text(shellLabel) },
843− enabled = !running,
844− onClick = { showOverflowMenu = false; showShellDialog = true },
845− )
846− androidx.compose.material3.HorizontalDivider()
847− DropdownMenuItem(
848− text = { Text(renameLabel) },
849− onClick = { showOverflowMenu = false; showRenameDialog = true },
850− )
851− DropdownMenuItem(
852− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
853− onClick = { showOverflowMenu = false; showDeleteDialog = true },
854− )
855− }
856− // While a catalog is initially loading (empty list + loading flag),
857− // show a tiny inline spinner beside the overflow so the user can see
858− // a load is in progress without opening the menu. Once loaded the
859− // spinner disappears; the menu items are always enabled (tapping a
860− // picker with no items shows the "no models/agents/commands" state).
861− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
862− (agentsLoading && agents.isEmpty()) ||
863− (modelsLoading && models.isEmpty())
864− if (catalogLoading) {
865− CircularProgressIndicator(
866− Modifier
867− .align(Alignment.TopEnd)
868− .size(10.dp)
869− .semantics { contentDescription = loadingLabel },
870− strokeWidth = 1.dp,
871− )
872− }
873− }
874− },
875− )
876− },
877− snackbarHost = { SnackbarHost(snackbar) },
878− bottomBar = {
879− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
880− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
881− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
882− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
883− Column {
884− // Pinned above the composer so the agent's plan and progress stay visible
885− // while scrolled up mid-run; renders nothing when there's no plan.
886− TodoPlanBar(todoPlan)
887− val bannerMotion = rememberVisibilityTransitions()
888− AnimatedVisibility(
889− visible = reverted,
890− enter = bannerMotion.enter,
891− exit = bannerMotion.exit,
892− ) {
893− RevertBanner(
894− diff = revertDiff,
895− isEditing = editing,
896− onUndo = { vm.unrevert() },
897− )
898− }
899− AnimatedVisibility(
900− visible = queuedOffline.isNotEmpty(),
901− enter = bannerMotion.enter,
902− exit = bannerMotion.exit,
903− ) {
904− OutboxBanner(
905− count = queuedOffline.size,
906− sending = outboxSending,
907− onFlush = { vm.flushQueued() },
908− onDiscard = { vm.discardAllQueued() },
909− )
910− }
911− AnimatedVisibility(
912− visible = pendingQuote != null,
913− enter = bannerMotion.enter,
914− exit = bannerMotion.exit,
915− ) {
916− pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
917− }
918− ChatInputBar(
919− value = draft,
920− onValueChange = vm::updateDraft,
921− running = running,
922− aborting = aborting,
923− enabled = activeConnection != null,
924− sendOnEnter = sendOnEnter,
925− onSend = ::doSend,
926− onAbort = { vm.abort() },
927− queuedFollowUp = queuedFollowUp,
928− onQueueFollowUp = vm::queueFollowUp,
929− onCancelQueue = { vm.queueFollowUp("") },
930− focusRequester = inputFocusRequester,
931− attachments = attachments,
932− staging = stagingCount > 0,
933− stagingFileCount = stagingFileTotal,
934− onRemoveAttachment = vm::removeAttachment,
935− onPickPhoto = {
936− photoPicker.launch(
937− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
938− )
939− },
940− onPickFile = { filePicker.launch("*/*") },
941− onCamera = { launchCamera() },
942− onVoice = { launchVoice() },
943− onPasteImage = { stageUris(it) },
944− commands = commands,
945− onRunCommand = { cmd ->
946− vm.runCommand(cmd)
947− // Clear the draft so the typed /prefix doesn't linger after the
948− // command fires (the command picker confirmation, if any, is
949− // handled inside runCommand).
950− vm.updateDraft("")
951− },
952− )
953− }
954− },
955− ) { padding ->
956− // Collect messages inside the content lambda so streaming token updates
957− // recompose only this subtree, not the top bar / input bar / 20+ other
958− // state reads in the ChatScreen body.
959− val messages by vm.messages.collectAsStateWithLifecycle()
960− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
961− val listState = rememberLazyListState()
962− val contentScope = rememberCoroutineScope()
963− val timeTick = rememberRelativeTimeTick()
964− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
965− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
966− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
967− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
968− androidx.compose.runtime.LaunchedEffect(listState) {
969− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
970− .distinctUntilChanged()
971− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
972− } // Group messages by day and interleave date separators so a long conversation
973− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
974− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
975− // outside the PullToRefreshBox so the auto-scroll effects below can reference
976− // the same list the LazyColumn renders (separators shift the indices vs. the
977− // raw messages list, so scroll targets must be in listItems space).
978− val todayLabel = stringResource(R.string.today)
979− val yesterdayLabel = stringResource(R.string.yesterday)
980− // In-conversation search: when active, narrow to messages whose text contains the query.
981− // Computed on the filtered set so day separators still align with the visible messages.
982− // Debounced + off-main-thread so a keystroke-by-keystroke filter walk over a long
983− // conversation (with many tool parts whose state stringification is non-trivial)
984− // doesn't jank the UI. produceState yields the empty list immediately and publishes
985− // the filtered result once the debounce settles.
986− val searchQuery = chatSearch.trim()
987− // When no search is active, skip the produceState indirection entirely and use the
988− // messages list directly. produceState keyed on (messages, searchQuery) re-launches
989− // its coroutine on every messages emission (every streamed token) even when the
990− // query is empty — the body just re-assigns `value = messages`, but the coroutine
991− // churn (launch + cancel + state write) ~20x/sec is pure overhead. Using `messages`
992− // directly when there's no search avoids that, and `buildMessageListItems` keys its
993− // own remember on the resulting list identity either way.
994− val searchMessages: List<MessageWithParts> = if (searchQuery.isEmpty()) {
995− messages
996− } else {
997− // Capture the messages list via rememberUpdatedState so the latest list is read
998− // when the debounce completes, WITHOUT re-launching the produceState coroutine on
999− // every messages emission. Keying produceState on `messages` restarts the debounce
1000− // delay from zero on every streamed token (~20×/sec); if tokens arrive faster than
1001− // the debounce interval the filter never runs and search shows "no matches" for the
1002− // entire run. Keying only on `searchQuery` lets the debounce settle once per query
1003− // while still filtering against the most recent list.
1004− val currentMessages by rememberUpdatedState(messages)
1005− val filtered by produceState(
1006− initialValue = emptyList(),
1007− searchQuery,
1008− ) {
1009− // Debounce: wait for the user to stop typing before running the filter,
1010− // so each keystroke doesn't kick off a fresh scan.
1011− kotlinx.coroutines.delay(NetworkConfig.chatSearchDebounceMs)
1012− // Run the filter off the main thread — the walk stringifies tool state
1013− // and scans every part of every message, which is non-trivial work for a
1014− // long conversation.
1015− value = withContext(Dispatchers.Default) {
1016− currentMessages.filter { m ->
1017− m.parts.any { p ->
1018− when (p) {
1019− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
1020− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
1021− is ToolPart -> {
1022− // Match the tool name plus its running/completed/error text and the
1023− // stringified input, so searching for an error string or a file the
1024− // tool touched actually finds the message it appeared in.
1025− p.tool.contains(searchQuery, ignoreCase = true) ||
1026− (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
1027− (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
1028− p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
1029− (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
1030− p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
1031− }
1032− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
1033− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
1034− else -> false
1035− }
1036− }
1037− }
1038− }
1039− searchFiltering = false
1040− }
1041− filtered
1042− }
1043− // Keep the focused-match index in range as the query (and thus the match set) changes.
1044− // A new query resets to the first match (keyed on searchQuery alone so any change —
1045− // even one that still yields enough matches — jumps to index 0 rather than carrying
1046− // the old index over to a semantically unrelated message). A shrunk set clamps to
1047− // the last valid index (keyed on size so a content refresh that shrinks the matches
1048− // without a query change doesn't leave searchPos out of range).
1049− LaunchedEffect(searchQuery) {
1050− if (searchQuery.isNotEmpty()) searchFiltering = true
1051− searchPos = 0
1052− }
1053− LaunchedEffect(searchMessages.size) {
1054− if (searchPos >= searchMessages.size) searchPos = (searchMessages.size - 1).coerceAtLeast(0)
1055− }
1056− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1057− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1058− }
1059− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1060− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1061− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1062− // would capture the first composition's list — which is empty, since `messages`
1063− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1064− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1065− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1066− // whose value tracks the latest list.
1067− val currentListItems by rememberUpdatedState(listItems)
1068−
1069− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1070− // while the user was scrolled away from the bottom, cleared once they return. A count
1071− // (vs. a bare dot) tells the user how much they missed at a glance.
1072− // rememberSaveable (not plain remember) so the badge count survives rotation: plain
1073− // remember resets to 0 on recreation, hiding the "new content" signal even though new
1074− // messages are still arriving. Int is Bundle-savable.
1075− var newContentCount by rememberSaveable { mutableIntStateOf(0) }
1076−
1077− val isPinnedToBottom by remember {
1078− derivedStateOf {
1079− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1080− // When a run is active, the LazyColumn has one trailing "__typing"
1081− // item after the last list item. Account for it so "pinned to bottom"
1082− // includes the working indicator — otherwise the pin check targets
1083− // listItems.lastIndex, the typing row sits just below the viewport,
1084− // and the user never sees the progress indicator even when pinned.
1085− val items = currentListItems
1086− val effectiveLast = if (running) items.size else items.lastIndex
1087− lastVisible >= effectiveLast || items.isEmpty()
1088− }
1089− }
1090−
1091− // Jump to the newest message once, when the conversation first loads. Guarded by a
1092− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1093− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1094− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1095− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1096− LaunchedEffect(listItems.isNotEmpty()) {
1097− if (listItems.isNotEmpty() && !didInitialScroll) {
1098− // When a run is active the LazyColumn has a trailing "__typing" row at
1099− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1100− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1101− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1102− didInitialScroll = true
1103− }
1104− }
1105−
1106− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1107− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1108− // isPinnedToBottom check flips to false the instant you send — freezing
1109− // auto-scroll. If the user was pinned to the last item just before the run
1110− // began, bring the typing row into view so the pin (and streaming follow) is
1111− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1112− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1113− LaunchedEffect(running) {
1114− if (running && listItems.isNotEmpty()) {
1115− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1116− if (lastVisible >= listItems.lastIndex) {
1117− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1118− }
1119− }
1120− }
1121−
1122− // Scroll the focused search match into view whenever the user steps through results with
1123− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1124− // includes date separators) and animates there.
1125− //
1126− // Keyed ONLY on searchPos and searchQuery (not listItems): a bare listItems key re-keys
1127− // on every streamed token (the list is rebuilt per snapshot), which re-fires this effect
1128− // ~20×/sec during an active stream — re-scrolling to the focused match on every token
1129− // and making it impossible to browse other matches with the up/down arrows while content
1130− // is streaming. snapshotFlow (reading currentListItems, a rememberUpdatedState) waits for
1131− // the target to appear without re-keying the effect on every list change, mirroring the
1132− // focusedMessageId pattern below.
1133− LaunchedEffect(searchPos, searchQuery) {
1134− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1135− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1136− val targetId = target.info.id
1137− val index = snapshotFlow {
1138− currentListItems.indexOfFirst {
1139− it is MessageListItem.Message && it.message.info.id == targetId
1140− }
1141− }.first { it >= 0 }
1142− runCatchingCancellable { listState.animateScrollToItem(index) }
1143− }
1144−
1145− // Global-search deep link: scroll to and briefly highlight the matched message. The
1146− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1147− // clears itself after a short delay so the user can re-read the surrounding context
1148− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1149− //
1150− // Keyed ONLY on focusedMessageId (not listItems): a bare listItems key re-keys on every
1151− // streamed token (the list is rebuilt per snapshot), which cancels the 2.5s delay before
1152− // it can clear the highlight — re-scrolling to the focus on every token and making an
1153− // actively-streaming chat unreadable. snapshotFlow waits for the message to appear in the
1154− // list (it may not be present on the first composition while messages load) without
1155− // re-keying the effect on every list change.
1156− // rememberSaveable (not plain remember) so the cleared null survives rotation:
1157− // plain remember keyed on focusMessageId re-seeds the non-null nav arg on every
1158− // recreation, re-firing this effect and yanking scroll back to the focus after the
1159− // user already dismissed the highlight. String? is Bundle-savable.
1160− var focusedMessageId by rememberSaveable(focusMessageId) { mutableStateOf(focusMessageId) }
1161− val currentListItemsForFocus by rememberUpdatedState(listItems)
1162− LaunchedEffect(focusedMessageId) {
1163− val focus = focusedMessageId ?: return@LaunchedEffect
1164− // Wait for the focused message to appear in the list, then resolve its index. A
1165− // first-composition empty list (messages still loading) will populate as the seed
1166− // arrives; snapshotFlow re-evaluates on each list change until the match is found.
1167− val index = snapshotFlow {
1168− currentListItemsForFocus.indexOfFirst {
1169− it is MessageListItem.Message && it.message.info.id == focus
1170− }
1171− }.first { it >= 0 }
1172− runCatchingCancellable { listState.animateScrollToItem(index) }
1173− kotlinx.coroutines.delay(2500)
1174− focusedMessageId = null
1175− }
1176−
1177− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1178− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1179− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1180− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1181− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1182− val density = androidx.compose.ui.platform.LocalDensity.current
1183− var wasImeOpen by rememberSaveable { mutableStateOf(false) }
1184− val imeBottomPx = WindowInsets.ime.getBottom(density)
1185− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1186− if (listItems.isEmpty()) return@LaunchedEffect
1187− val imeOpen = imeBottomPx > 0
1188− // Scroll to bottom only on the open transition (not close) and only when the user
1189− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1190− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1191− if (shouldScroll) {
1192− runCatchingCancellable {
1193− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1194− }
1195− }
1196− wasImeOpen = imeOpen
1197− }
1198−
1199− LaunchedEffect(Unit) {
1200− var prevSize = 0
1201− var prevLen = 0
1202− var initialized = false
1203− snapshotFlow {
1204− // Track list size + the streaming length of the last part so we auto-scroll
1205− // as content arrives, plus the pinned flag. A small data class with primitive
1206− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1207− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1208− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1209− // and tool output — not just TextPart — keeps a pinned view following a long
1210− // reasoning/tool block while it streams (previously it stalled at 0).
1211− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1212− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1213− }.collect { signal ->
1214− if (!initialized) {
1215− prevSize = signal.size
1216− prevLen = signal.lastTextLength
1217− initialized = true
1218− return@collect
1219− }
1220− if (signal.pinned) {
1221− // Back at the bottom: clear the new-content badge.
1222− newContentCount = 0
1223− if (signal.size > 0) {
1224− // Scroll to the effective last index, including the trailing
1225− // "__typing" row when a run is active so the working indicator
1226− // is brought into view (not just the last message).
1227− val items = currentListItems
1228− val target = if (running) items.size else items.lastIndex
1229− listState.scrollToItem(target)
1230− }
1231− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1232− // Content arrived while scrolled up — increment the jump-to-latest badge.
1233− // Only count whole new items (not per-token growth) so the number reflects
1234− // new messages, not a token count.
1235− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1236− else if (newContentCount == 0) newContentCount = 1
1237− }
1238− prevSize = signal.size
1239− prevLen = signal.lastTextLength
1240− }
1241− }
1242−
1243− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1244− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1245− // content padding accounts for the bottomBar's raised height, so the message
1246− // list is already above the keyboard. Adding imePadding here would double-apply
1247− // the IME inset and push messages too far up.
1248− //
1249− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1250− // message list on wide screens instead of floating at the screen edges — on a
1251− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1252− // The horizontal margin below is applied to the FAB/search containers so they
1253− // track the list's left/right edges.
1254− androidx.compose.foundation.layout.BoxWithConstraints(
1255− modifier = Modifier.fillMaxSize().padding(padding),
1256− ) {
1257− val screenMaxWidth = maxWidth
1258− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1259− // Horizontal margin between the capped list's edge and the screen edge (0 on
1260− // screens narrower than the cap). Applied as start/end padding so the FABs and
1261− // search bar sit at the list's edges, not the screen's.
1262− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1263− if (activeConnection == null) {
1264− Column(
1265− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1266− horizontalAlignment = Alignment.CenterHorizontally,
1267− ) {
1268− Text(
1269− stringResource(R.string.not_connected),
1270− color = MaterialTheme.colorScheme.error,
1271− )
1272− Spacer(Modifier.size(12.dp))
1273− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1274− if (reconnecting) {
1275− CircularProgressIndicator(
1276− Modifier.size(20.dp),
1277− color = MaterialTheme.colorScheme.onPrimary,
1278− strokeWidth = 2.dp,
1279− )
1280− } else {
1281− Text(stringResource(R.string.reconnect))
1282− }
1283− }
1284− }
1285− } else {
1286− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1287− // Measure the banner's actual height instead of hardcoding 44dp. At large
1288− // accessibility font scales the banner's labelMedium text + spinner + Retry
1289− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1290− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1291− // fires while the banner is composed (visible), so gate the inset on
1292− // bannerVisible and fall back to 44dp until the first measurement arrives.
1293− var bannerHeightPx by remember { mutableIntStateOf(0) }
1294− // Track the search bar height so the list's top padding can grow when search
1295− // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1296− // the floating search bar (the "scroll-under-the-search-bar" bug).
1297− var searchbarHeightPx by remember { mutableIntStateOf(0) }
1298− val density = LocalDensity.current
1299− val topPad = if (bannerVisible) {
1300− if (bannerHeightPx > 0) {
1301− with(density) { bannerHeightPx.toDp() } + 4.dp
1302− } else {
1303− 44.dp
1304− }
1305− } else {
1306− 16.dp
1307− } + if (searchActive && searchbarHeightPx > 0) {
1308− with(density) { searchbarHeightPx.toDp() } + 4.dp
1309− } else {
1310− 0.dp
1311− }
1312− ConnectionBanner(
1313− state = connectionState,
1314− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1315− isOnline = isOnline,
1316− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1317− // re-seeds from REST). refreshMessages is the right recovery path
1318− // when the connection is present but the stream died; reconnect()
1319− // is the path when the whole connection is gone (handled by the
1320− // separate "Not connected" state below).
1321− onRetry = { vm.refreshMessages() },
1322− // On an auth failure (401/403), retrying with the same bad credentials
1323− // is futile — offer a one-tap path to edit the active profile's
1324− // credentials instead of making the user hunt for the server list.
1325− onEditCredentials = {
1326− val profileId = activeConnection?.profile?.id
1327− if (profileId != null) onEditProfile?.invoke(profileId)
1328− },
1329− reconnectAttempts = reconnectAttempts,
1330− )
1331− // Persistent inline error banner for a mid-conversation load failure.
1332− // Unlike the one-shot snackbar (which fires once per streak then goes
1333− // silent), this stays visible until the stream recovers, so a persistent
1334− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1335− // Anchored at the top, below the connection banner, so it doesn't overlap
1336− // the message list.
1337− if (loadErrorInline && hasMessages) {
1338− Surface(
1339− color = MaterialTheme.colorScheme.errorContainer,
1340− shape = MaterialTheme.shapes.small,
1341− modifier = Modifier
1342− .align(Alignment.TopCenter)
1343− .padding(top = if (bannerVisible) topPad else 8.dp)
1344− .padding(horizontal = 16.dp)
1345− .semantics { liveRegion = LiveRegionMode.Polite },
1346− ) {
1347− Row(
1348− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1349− verticalAlignment = Alignment.CenterVertically,
1350− horizontalArrangement = Arrangement.spacedBy(8.dp),
1351− ) {
1352− Icon(
1353− Icons.Filled.ErrorOutline,
1354− contentDescription = null,
1355− modifier = Modifier.size(16.dp),
1356− tint = MaterialTheme.colorScheme.onErrorContainer,
1357− )
1358− Text(
1359− stringResource(R.string.load_error_persistent),
1360− style = MaterialTheme.typography.labelMedium,
1361− color = MaterialTheme.colorScheme.onErrorContainer,
1362− modifier = Modifier.weight(1f),
1363− )
1364− TextButton(
1365− onClick = { vm.refreshMessages() },
1366− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1367− ) {
1368− Text(stringResource(R.string.retry))
1369− }
1370− }
1371− }
1372− }
1373− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1374− // recovery is a swipe away everywhere — not just when the message list is
1375− // populated. Previously PTR was only around the populated list, leaving the
1376− // error/loading states reachable only via a button tap.
1377− PullToRefreshBox(
1378− isRefreshing = refreshing,
1379− // Suppress the refresh action while a run is active: a mid-stream
1380− // refresh forces an SSE reconnect that can interrupt the actively
1381− // streaming reply (matching the top-bar refresh button, which is
1382− // also disabled while running). The pull gesture still responds, but
1383− // the release no-ops instead of triggering a disruptive re-seed.
1384− onRefresh = { if (!running) vm.refreshMessages() },
1385− // Cap width and center on large screens for readability — full-width
1386− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1387− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1388− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1389− ) {
1390− // Reserve top space when the banner is visible so it doesn't overlap the
1391− // first message / state content. (topPad computed above.)
1392− if (loading && messages.isEmpty()) {
1393− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1394− // than a bare centered spinner and the first real messages pop into an
1395− // already-shaped list instead of a blank-then-pop.
1396− ChatSkeleton(topPad = topPad)
1397− } else if (loadError && messages.isEmpty()) {
1398− // A failed load with nothing to show. Distinct from the empty
1399− // conversation state below — the conversation isn't empty, it
1400− // failed to load, and offering "Start a conversation" here is
1401− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1402− Column(
1403− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1404− horizontalAlignment = Alignment.CenterHorizontally,
1405− ) {
1406− Text(
1407− stringResource(R.string.load_messages_failed),
1408− color = MaterialTheme.colorScheme.error,
1409− )
1410− Spacer(Modifier.size(12.dp))
1411− Button(onClick = { vm.refreshMessages() }) {
1412− Text(stringResource(R.string.retry))
1413− }
1414− // When the VM's retryWhen loop is actively retrying (loading is true
1415− // on top of the error state), surface a small "retrying…" indicator so
1416− // the user knows the system is working — without it, the static error
1417− // + Retry button reads as "broken, tap to fix", and the user may not
1418− // realize an automatic retry is already in progress.
1419− if (loading) {
1420− Spacer(Modifier.size(12.dp))
1421− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1422− Row(verticalAlignment = Alignment.CenterVertically) {
1423− CircularProgressIndicator(
1424− Modifier.size(14.dp),
1425− strokeWidth = 2.dp,
1426− )
1427− Text(
1428− retryingLabel,
1429− style = MaterialTheme.typography.labelSmall,
1430− color = MaterialTheme.colorScheme.onSurfaceVariant,
1431− modifier = Modifier.padding(start = 6.dp),
1432− )
1433− }
1434− }
1435− }
1436− } else if (messages.isEmpty() && running) {
1437− // A run just started but no parts have arrived yet — the empty list with
1438− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1439− // from the initial-load branch so the perceived start latency is lower and
1440− // the first real assistant part pops into an already-shaped list.
1441− ChatSkeleton(topPad = topPad)
1442− } else if (messages.isEmpty()) {
1443− EmptyConversation(
1444− onSuggestion = {
1445− vm.updateDraft(it)
1446− // Focus the input so the user can edit the suggestion before
1447− // sending, instead of having to manually tap the field.
1448− runCatching { inputFocusRequester.requestFocus() }
1449− },
1450− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1451− )
1452− } else {
1453− val lastMessageId = messages.lastOrNull()?.info?.id
1454− // Text-to-speech for reading assistant replies aloud; shuts down when the
1455− // message list leaves composition.
1456− val tts = rememberTtsController()
1457− val speakingMessageId by tts.speakingId
1458− val ttsState by tts.state
1459− // Provide the in-conversation search query to the markdown renderer so matching
1460− // text spans are highlighted in-place (in addition to the focused-row highlight
1461− // above). Scoped to the list so cleared search stops highlighting immediately.
1462− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1463− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1464− LazyColumn(
1465− state = listState,
1466− modifier = Modifier.fillMaxSize(),
1467− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1468− // never floats over the last message. Top padding grows when the
1469− // connection banner is visible so it doesn't overlap the first message.
1470− contentPadding = PaddingValues(
1471− start = 16.dp,
1472− top = topPad,
1473− end = 16.dp,
1474− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1475− ),
1476− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1477− // more conversation on screen without scrolling as much.
1478− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1479− ) {
1480− items(
1481− items = listItems,
1482− key = { it.key },
1483− contentType = { it.contentType },
1484− ) { item ->
1485− // When in-conversation search is stepping through matches, highlight the
1486− // focused one's row so the user can spot it at a glance among the filtered
1487− // results (full in-text term highlighting would require threading the query
1488− // through the markdown renderer; the row highlight + scroll-to-match covers
1489− // the navigation use case desktop chat apps solve with next/prev).
1490− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1491− searchMessages.getOrNull(searchPos)?.info?.id
1492− } else null
1493− val isFocusedMatch = focusedMatchId != null &&
1494− item is MessageListItem.Message &&
1495− item.message.info.id == focusedMatchId
1496− // No animateItem() here. It is backed by SizeAnimationModifierNode, which
1497− // forces a draw-phase remeasure (the display-list rebuild triggered by
1498− // AndroidComposeView.dispatchDraw) when its target's size changes. That
1499− // remeasure runs inside the draw pass and reads Placeable.getWidth()/
1500− // getHeight() of a child whose measured size hasn't been committed yet —
1501− // an NPE in PaddingValuesModifier.measure / FillNode.measure (the R8 map
1502− // marks both sites with a throws(NullPointerException) rewriteFrame).
1503− //
1504− // This is the same crash class previously fixed for the markdown library's
1505− // animateContentSize and MessageBubble's send-status AnimatedContent. An
1506− // earlier fix kept animateItem() but skipped it for the actively-streaming
1507− // row; that was insufficient because the crash also fires when OPENING a
1508− // chat (running = false, so every row kept animateItem()): historical rows
1509− // with async-loading content (DiffView's produceState starts empty and
1510− // fills a frame later; RemoteImage loading; large markdown) change size
1511− // after mount and trigger the same draw-phase remeasure. animateItem() is
1512− // fundamentally unsafe on any chat row whose size can change post-mount,
1513− // so it is removed entirely. The glide-in animation it provided is
1514− // decorative (the list already auto-scrolls to new messages) and is not
1515− // worth a 4th round of this crash.
1516− Box(
1517− Modifier
1518− .then(
1519− if (isFocusedMatch) {
1520− Modifier.background(
1521− MaterialTheme.colorScheme.secondaryContainer,
1522− MaterialTheme.shapes.medium,
1523− )
1524− } else {
1525− Modifier
1526− },
1527− ),
1528− ) {
1529− when (item) {
1530− is MessageListItem.Separator -> DateSeparator(item.label)
1531− is MessageListItem.Message -> {
1532− val message = item.message
1533− val messageId = message.info.id
1534− // Only the last (streaming) message needs isRunning — it drives the
1535− // reasoning-block spinner. Passing the live flag to every bubble
1536− // makes all visible messages recompose whenever a run starts or stops.
1537− val modelLabel = remember(message.info, models) {
1538− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1539− ?.let { resolveModelLabel(it, models) }
1540− }
1541− // Key agentLabel/quoteText on the message id + the id of the
1542− // last TextPart/AgentPart, so the streaming message's label
1543− // updates when a NEW text/agent part is appended (its id
1544− // changes) without re-running filterIsInstance per token (a
1545− // streaming TextPart's id is stable across token updates, so
1546− // the key only changes on append, not on every token). The
1547− // prior `remember(messageId)` pinned these at first
1548− // composition: for a message that started with reasoning/tool
1549− // parts before any TextPart, quoteText stayed "" for the life
1550− // of the list item, so swipe-to-reply yielded "cannot quote
1551− // this" even after text arrived.
1552− val lastTextPartId = remember(message.parts) {
1553− message.parts.lastOrNull { it is TextPart }?.id
1554− }
1555− val lastAgentPartId = remember(message.parts) {
1556− message.parts.filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1557− .lastOrNull { it.name.isNotBlank() }?.id
1558− }
1559− val agentLabel = remember(messageId, lastAgentPartId) {
1560− message.parts
1561− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1562− .firstOrNull { it.name.isNotBlank() }?.name
1563− }
1564− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1565− // image/code-only messages, which then opt out of the swipe gesture.
1566− val quoteText = remember(messageId, lastTextPartId) {
1567− message.parts
1568− .filterIsInstance<TextPart>()
1569− .joinToString("\n\n") { it.text }
1570− .trim()
1571− .takeIf { it.isNotEmpty() }
1572− }
1573− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1574− // snapping back (the message isn't dismissed — the quote fills the composer).
1575− // Enabled for non-text messages too (image/tool-only), but the confirm
1576− // callback gives a haptic without triggering reply — so the user gets a
1577− // perceptible "can't quote this" signal instead of a silently dead gesture.
1578− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1579− val undoLabel = stringResource(R.string.undo)
1580− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1581− // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1582− // so it's stable across recompositions (a fresh lambda would force the
1583− // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1584− // derived value that's stable for non-streaming messages.
1585− val swipeState = rememberSwipeToDismissBoxState(
1586− confirmValueChange = remember(messageId, quoteText) {
1587− { value ->
1588− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1589− SwipeToDismissBoxValue.EndToStart
1590− } else {
1591− SwipeToDismissBoxValue.StartToEnd
1592− }
1593− if (value == replyValue) {
1594− if (quoteText != null) {
1595− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1596− vm.quoteReply(quoteText)
1597− runCatching { inputFocusRequester.requestFocus() }
1598− scope.launch {
1599− val res = snackbar.showSnackbar(
1600− message = quoteReplyLabel,
1601− actionLabel = undoLabel,
1602− )
1603− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1604− vm.cancelQuoteReply()
1605− }
1606− }
1607− } else {
1608− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1609− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1610− }
1611− }
1612− false
1613− }
1614− },
1615− )
1616− // In RTL locales, mirror the swipe direction so the reply
1617− // gesture reads naturally (swipe from the trailing edge
1618− // toward the leading edge), matching how LTR users swipe
1619− // left-to-right. Without this, RTL users had no reply swipe.
1620− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1621− // Memoize every MessageBubble lambda on the message id so a recomposition
1622− // triggered by a sibling (e.g. the streaming message's parts changing,
1623− // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1624− // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1625− // many `(() -> Unit)?` params, which Compose treats as unstable), so
1626− // without memoization every visible bubble recomposes on every token,
1627− // defeating the @Immutable MessageWithParts reference-stability the
1628− // reducer's Holder cache provides. This mirrors the SessionListScreen
1629− // per-card lambda memoization pattern.
1630− val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1631− val onEdit = remember(messageId) {
1632− { text: String ->
1633− // editMessage reverts to before this message (hiding it and
1634− // everything after); the revert banner surfaces the rewind
1635− // with an Undo. Focus + scroll the composer into view like the
1636− // Quote action so the prefilled draft isn't off-screen.
1637− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1638− vm.editMessage(messageId, text)
1639− runCatching { inputFocusRequester.requestFocus() }
1640− contentScope.launch {
1641− runCatchingCancellable {
1642− listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1643− }
1644− }
1645− Unit
1646− }
1647− }
1648− val onSpeak = remember(messageId) {
1649− { text: String ->
1650− if (!tts.toggle(messageId, text)) {
1651− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1652− }
1653− Unit
1654− }
1655− }
1656− val onPause = remember { { tts.pause() } }
1657− val onResume = remember { { tts.resume() } }
1658− val onStop = remember { { tts.stop() } }
1659− val onQuote = remember(messageId) {
1660− { text: String ->
1661− vm.quoteReply(text)
1662− runCatching { inputFocusRequester.requestFocus() }
1663− Unit
1664− }
1665− }
1666− val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1667− // Regenerate is only meaningful for a finished assistant reply
1668− // (not the actively-streaming one), so gate it on !running.
1669− val onRegenerate = if (!running) {
1670− remember(messageId) { { vm.regenerate(messageId) } }
1671− } else {
1672− null
1673− }
1674− // Continue: resume a partial reply. Shown only for
1675− // incomplete assistant messages (a partial reply that
1676− // was aborted) and not while a run is active.
1677− val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1678− val onContinue = if (canContinue) {
1679− remember(messageId) { { vm.continueRun(messageId) } }
1680− } else {
1681− null
1682− }
1683− val messageFailed = optimisticStatuses[messageId] == true
1684− val onRetry = if (messageFailed) {
1685− remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1686− } else {
1687− null
1688− }
1689− val onDismiss = if (messageFailed) {
1690− remember(messageId) { { vm.dismissOptimistic(messageId) } }
1691− } else {
1692− null
1693− }
1694− val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1695− {
1696− // Per-message share: build a single-message Markdown
1697− // transcript off-thread and fire ACTION_SEND, mirroring the
1698− // whole-conversation share but scoped to just this message.
1699− scope.launch {
1700− val md = withContext(Dispatchers.Default) {
1701− buildMessageMarkdown(message)
1702− } ?: return@launch
1703− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1704− type = "text/markdown"
1705− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1706− putExtra(android.content.Intent.EXTRA_TEXT, md)
1707− }
1708− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1709− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1710− }
1711− Unit
1712− }
1713− }
1714− SwipeToDismissBox(
1715− state = swipeState,
1716− enableDismissFromEndToStart = !replyFromStartToEnd,
1717− enableDismissFromStartToEnd = replyFromStartToEnd,
1718− backgroundContent = {
1719− Box(
1720− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1721− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1722− ) {
1723− Icon(
1724− Icons.AutoMirrored.Filled.Reply,
1725− contentDescription = null,
1726− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1727− )
1728− }
1729− },
1730− ) {
1731− MessageBubble(
1732− message,
1733− isRunning = running && messageId == lastMessageId,
1734− imageContext = imageContext,
1735− modelLabel = modelLabel,
1736− agentLabel = agentLabel,
1737− onOpenFile = onOpenFile,
1738− onRevert = onRevert,
1739− onEdit = onEdit,
1740− onSpeak = onSpeak,
1741− isSpeaking = messageId == speakingMessageId,
1742− ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1743− onPause = onPause,
1744− onResume = onResume,
1745− onStop = onStop,
1746− onQuote = onQuote,
1747− onBranch = onBranch,
1748− onRegenerate = onRegenerate,
1749− onContinue = onContinue,
1750− sendStatus = optimisticStatuses[messageId]?.let { failed ->
1751− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1752− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1753− },
1754− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1755− onRetry = onRetry,
1756− onDismiss = onDismiss,
1757− onShare = onShare,
1758− isFirstOfSpeaker = item.isFirstOfSpeaker,
1759− highlighted = focusedMessageId != null && messageId == focusedMessageId,
1760− )
1761− }
1762− }
1763− }
1764− }
1765− }
1766− if (running) {
1767− item(key = "__typing") {
1768− val workingText = stringResource(R.string.working)
1769− // When the SSE stream dropped mid-run, show a "reconnecting" label
1770− // instead of the plain "working" text so the user understands the
1771− // run is still active but the stream is reconnecting (not finished).
1772− val reconnectingText = stringResource(R.string.reconnecting)
1773− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1774− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1775− // survives LazyColumn recycling — a local remember reset to 0:00 when
1776− // the row was disposed and scrolled back into view. The VM stamps the
1777− // start on the real false→true transition (send/run/init), not on
1778− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1779− // once per second; the value is decorative (the a11y label is the row's).
1780− // The clock freezes when an abort is confirmed (aborting = true) so the
1781− // user can see how long the run lasted before they stopped it, rather
1782− // than the clock continuing to tick until SessionIdle clears _running.
1783− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1784− // Seed the initial value synchronously from startMs so the timer
1785− // doesn't flash 0:00 when the __typing row is recycled by LazyColumn
1786− // (scrolled out then back in): produceState's coroutine is cancelled on
1787− // disposal and re-launched on re-entry, and a 0L initialValue would
1788− // briefly show "0:00" before the producer's first iteration runs.
1789− val elapsedMs by produceState(
1790− initialValue = if (startMs > 0L) (System.currentTimeMillis() - startMs).coerceAtLeast(0L) else 0L,
1791− startMs, aborting,
1792− ) {
1793− if (startMs == 0L) return@produceState
1794− if (aborting) {
1795− // Freeze at the last-computed value: one final snapshot then stop.
1796− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1797− return@produceState
1798− }
1799− while (true) {
1800− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1801− delay(1000)
1802− }
1803− }
1804− val elapsedText = remember(elapsedMs) {
1805− val total = elapsedMs / 1000
1806− // Locale.US for stable digit formatting: on locales with
1807− // non-ASCII digits (ar-/fa-) the default locale would render
1808− // localized digits inside the Monospace block, breaking the
1809− // fixed-width alignment the monospace family was chosen for.
1810− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1811− }
1812− Row(
1813− verticalAlignment = Alignment.CenterVertically,
1814− // No animateItem() here for the same reason as the message rows
1815− // above: the __typing row's size changes (the elapsed-time Text
1816− // grows from "0:00" to "M:SS" and the spinner mounts on first
1817− // frame), and animateItem()'s SizeAnimationModifierNode forces a
1818− // draw-phase remeasure that NPEs on Placeable.getWidth(). The
1819− // working row is mounted/unmounted as a whole item (key="__typing")
1820− // by LazyColumn, which already crossfades the appearance; the
1821− // placement animation is not needed.
1822− modifier = Modifier
1823− .padding(vertical = 4.dp),
1824− ) {
1825− // Merge the indicator + label + clock into one TalkBack node so
1826− // it's announced once (the working label, then the elapsed time)
1827− // instead of "working… / working… / 0:14" with the label read
1828− // twice. The Stop IconButton below stays separately focusable.
1829− Row(
1830− verticalAlignment = Alignment.CenterVertically,
1831− modifier = Modifier.semantics(mergeDescendants = true) {
1832− contentDescription = "$interruptedLabel $elapsedText"
1833− },
1834− ) {
1835− // Dim the spinner when interrupted so the row reads as
1836− // "paused/reconnecting" rather than actively progressing.
1837− CircularProgressIndicator(
1838− Modifier.size(16.dp),
1839− strokeWidth = 2.dp,
1840− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1841− else MaterialTheme.colorScheme.primary,
1842− )
1843− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1844− Spacer(Modifier.size(8.dp))
1845− Icon(
1846− Icons.Filled.Schedule,
1847− contentDescription = null,
1848− modifier = Modifier.size(14.dp),
1849− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1850− )
1851− Text(
1852− elapsedText,
1853− style = MaterialTheme.typography.labelMedium,
1854− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1855− color = MaterialTheme.colorScheme.onSurfaceVariant,
1856− modifier = Modifier.padding(start = 4.dp),
1857− )
1858− }
1859− // A trailing Stop on the working row so the run can be aborted
1860− // without scrolling back to the composer (which may be off-screen
1861− // while the user reads the streaming output up-thread).
1862− Spacer(Modifier.weight(1f))
1863− val stopLabel = stringResource(R.string.stop)
1864− IconButton(
1865− onClick = { vm.abort() },
1866− modifier = Modifier.semantics { contentDescription = stopLabel },
1867− ) {
1868− Icon(Icons.Filled.Stop, contentDescription = null)
1869− }
1870− }
1871− }
1872− }
1873− }
1874− }
1875− }
1876− }
1877− // Jump-to-latest affordance when the user has scrolled away during a stream.
1878− val fabMotion = rememberVisibilityTransitions()
1879− AnimatedVisibility(
1880− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1881− enter = fabMotion.enter,
1882− exit = fabMotion.exit,
1883− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1884− // edge instead of floating at the screen edge (visually detached on tablets).
1885− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1886− ) {
1887− // Badge the FAB when new content arrived while the user was scrolled up, so
1888− // they know there's something new to jump to (cleared once back at bottom).
1889− BadgedBox(
1890− badge = {
1891− if (newContentCount > 0) {
1892− // Merge the count into the badge announcement so TalkBack reads
1893− // "5 new messages" instead of the bare label and a separate number.
1894− val newContentLabel = pluralStringResource(
1895− R.plurals.plurals_new_messages,
1896− newContentCount,
1897− newContentCount,
1898− )
1899− Badge(
1900− modifier = Modifier.semantics {
1901− contentDescription = newContentLabel
1902− // Announce new-content counts as they change so a
1903− // TalkBack user hears "5 new messages" without having
1904− // to focus the FAB. Polite so it doesn't interrupt an
1905− // in-progress utterance (e.g. streaming token reads).
1906− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1907− },
1908− ) {
1909− Text(
1910− if (newContentCount > 99) "99+" else newContentCount.toString(),
1911− modifier = Modifier.semantics { invisibleToUser() },
1912− )
1913− }
1914− }
1915− },
1916− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1917− ) {
1918− ExtendedFloatingActionButton(
1919− onClick = {
1920− newContentCount = 0
1921− if (listItems.isNotEmpty()) {
1922− // Scroll to the effective last index, including the
1923− // trailing "__typing" row when a run is active.
1924− val target = if (running) listItems.size else listItems.lastIndex
1925− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1926− }
1927− },
1928− // contentDescription null: the visible "Latest" text already labels
1929− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1930− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1931− text = { Text(stringResource(R.string.latest)) },
1932− )
1933− }
1934− }
1935− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1936− // user has scrolled down past the first few messages. Symmetric to the
1937− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1938− val scrolledDown by remember {
1939− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1940− }
1941− AnimatedVisibility(
1942− visible = scrolledDown && listItems.size > 4,
1943− enter = fabMotion.enter,
1944− exit = fabMotion.exit,
1945− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1946− ) {
1947− SmallFloatingActionButton(
1948− onClick = {
1949− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1950− },
1951− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1952− ) {
1953− Icon(
1954− Icons.Filled.KeyboardArrowUp,
1955− contentDescription = stringResource(R.string.scroll_to_top),
1956− )
1957− }
1958− }
1959− // In-conversation search bar. Overlays the list so typing filters messages in
1960− // place; the match count + a no-matches note give immediate feedback.
1961− val searchMotion = rememberVisibilityTransitions()
1962− AnimatedVisibility(
1963− visible = searchActive,
1964− enter = searchMotion.enter,
1965− exit = searchMotion.exit,
1966− // Inset by sideMargin on wide screens so the search bar spans the capped
1967− // list's width, not the full screen width.
1968− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1969− ) {
1970− Surface(
1971− tonalElevation = 3.dp,
1972− modifier = Modifier
1973− .padding(horizontal = 12.dp, vertical = 4.dp)
1974− .fillMaxWidth()
1975− .onSizeChanged { searchbarHeightPx = it.height },
1976− ) {
1977− // Focus the search field when the bar appears (from the overflow menu's
1978− // "Find in conversation" or Ctrl+F), so the user can start typing
1979− // immediately. Runs after the search field enters the composition.
1980− LaunchedEffect(searchActive) {
1981− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1982− }
1983− Row(
1984− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1985− verticalAlignment = Alignment.CenterVertically,
1986− ) {
1987− OutlinedTextField(
1988− value = chatSearch,
1989− onValueChange = { chatSearch = it },
1990− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1991− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1992− singleLine = true,
1993− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1994− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1995− )
1996− // Match counter: "N of M" where N is the focused match (1-based) and
1997− // M is the total matching messages. Only shown when there's a query.
1998− val matchCount = searchMessages.size
1999− Text(
2000− if (searchQuery.isNotEmpty() && matchCount > 0) {
2001− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
2002− } else if (searchQuery.isNotEmpty()) {
2003− stringResource(R.string.search_no_matches)
2004− } else "",
2005− style = MaterialTheme.typography.labelSmall,
2006− color = MaterialTheme.colorScheme.onSurfaceVariant,
2007− modifier = Modifier
2008− .padding(horizontal = 4.dp)
2009− // Live region so a TalkBack user hears "3 of 12" / "No
2010− // matches" announce as they step through results, not just
2011− // the sighted user seeing the counter update.
2012− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
2013− )
2014− // Step through matches (Previous / Next), disabled when there are
2015− // fewer than two to navigate. Wrap around at the ends so repeated
2016− // taps cycle through every hit.
2017− val prevLabel = stringResource(R.string.find_previous)
2018− val nextLabel = stringResource(R.string.find_next)
2019− IconButton(
2020− onClick = {
2021− if (matchCount > 0) {
2022− searchPos = (searchPos - 1 + matchCount) % matchCount
2023− }
2024− },
2025− enabled = matchCount > 1,
2026− ) {
2027− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
2028− }
2029− IconButton(
2030− onClick = {
2031− if (matchCount > 0) {
2032− searchPos = (searchPos + 1) % matchCount
2033− }
2034− },
2035− enabled = matchCount > 1,
2036− ) {
2037− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
2038− }
2039− IconButton(onClick = {
2040− searchActive = false
2041− chatSearch = ""
2042− }) {
2043− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
2044− }
2045− }
2046− }
2047− }
2048− // When a search yields no matches (but the conversation isn't empty), say so
2049− // instead of showing a blank list.
2050− val noMatches = searchActive && searchQuery.isNotEmpty() &&
2051− !searchFiltering && searchMessages.isEmpty() && messages.isNotEmpty()
2052− if (noMatches) {
2053− Text(
2054− stringResource(R.string.search_no_matches),
2055− style = MaterialTheme.typography.bodyMedium,
2056− color = MaterialTheme.colorScheme.onSurfaceVariant,
2057− modifier = Modifier.align(Alignment.Center),
2058− )
2059− }
2060− }
2061− }
2062− }
2063− }
2064−
2065− if (showExitConfirm) {
2066− AlertDialog(
2067− onDismissRequest = { showExitConfirm = false },
2068− title = { Text(stringResource(R.string.stop_and_exit_title)) },
2069− text = { Text(stringResource(R.string.stop_and_exit_text)) },
2070− confirmButton = {
2071− TextButton(onClick = {
2072− showExitConfirm = false
2073− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2074− vm.abort()
2075− onBack()
2076− }) { Text(stringResource(R.string.stop_and_exit)) }
2077− },
2078− dismissButton = {
2079− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
2080− },
2081− )
2082− }
2083−
2084− if (showSummarizeConfirm) {
2085− AlertDialog(
2086− onDismissRequest = { showSummarizeConfirm = false },
2087− title = { Text(stringResource(R.string.summarize_confirm_title)) },
2088− text = { Text(stringResource(R.string.summarize_confirm_text)) },
2089− confirmButton = {
2090− TextButton(onClick = {
2091− showSummarizeConfirm = false
2092− vm.summarize()
2093− }) { Text(stringResource(R.string.action_continue)) }
2094− },
2095− dismissButton = {
2096− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
2097− },
2098− )
2099− }
2100−
2101− if (showInitConfirm) {
2102− AlertDialog(
2103− onDismissRequest = { showInitConfirm = false },
2104− title = { Text(stringResource(R.string.init_confirm_title)) },
2105− text = { Text(stringResource(R.string.init_confirm_text)) },
2106− confirmButton = {
2107− TextButton(onClick = {
2108− showInitConfirm = false
2109− vm.initProject()
2110− }) { Text(stringResource(R.string.action_continue)) }
2111− },
2112− dismissButton = {
2113− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2114− },
2115− )
2116− }
2117−
2118− if (showRenameDialog) {
2119− RenameSessionChatDialog(
2120− initialTitle = sessionTitle ?: "",
2121− onDismiss = { showRenameDialog = false },
2122− onConfirm = { newName ->
2123− showRenameDialog = false
2124− vm.renameSession(newName)
2125− },
2126− )
2127− }
2128−
2129− if (showDeleteDialog) {
2130− AlertDialog(
2131− onDismissRequest = { showDeleteDialog = false },
2132− title = { Text(stringResource(R.string.delete_session_chat_title)) },
2133− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2134− confirmButton = {
2135− TextButton(onClick = {
2136− showDeleteDialog = false
2137− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2138− vm.deleteSession()
2139− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2140− },
2141− dismissButton = {
2142− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2143− },
2144− )
2145− }
2146−
2147− if (showShellDialog) {
2148− ShellCommandDialog(
2149− onDismiss = { showShellDialog = false },
2150− onRun = { cmd ->
2151− showShellDialog = false
2152− vm.runShell(cmd)
2153− },
2154− )
2155− }
2156−
2157− if (showModelPicker) {
2158− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2159− // to, dropping any whose model is no longer offered by the server. Ordered by
2160− // recency (head of the store first).
2161− val recentOptions = remember(models, recentModelEntries) {
2162− val byKey = models.associateBy { it.providerID to it.modelID }
2163− recentModelEntries.mapNotNull { entry ->
2164− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2165− }
2166− }
2167− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2168− // below isn't @Composable, so stringResource can't be called inside it.
2169− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2170− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2171− ModelPickerSheet(
2172− options = models,
2173− selected = selectedModel,
2174− loading = modelsLoading,
2175− error = modelsError,
2176− onSelect = {
2177− vm.selectModel(it)
2178− container.recentModelsStore.add(it.providerID, it.modelID)
2179− },
2180− onRetry = { vm.reloadModels() },
2181− onDismiss = { showModelPicker = false },
2182− preferredModelId = preferredModelId,
2183− onSetPreferredModel = { id ->
2184− scope.launch {
2185− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2186− // Confirm the change with a snackbar so the user sees it took effect —
2187− // the toggle's label flip can be missed, especially when clearing.
2188− val msg = if (id.isEmpty()) {
2189− defaultModelClearedMsg
2190− } else {
2191− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2192− defaultModelSetFmt.format(label)
2193− }
2194− snackbar.showSnackbar(msg)
2195− }
2196− },
2197− recent = recentOptions,
2198− )
2199− }
2200−
2201− if (showAgentPicker) {
2202− AgentPickerSheet(
2203− agents = agents,
2204− selected = selectedAgent,
2205− loading = agentsLoading,
2206− error = agentsError,
2207− onSelect = { vm.selectAgent(it?.name) },
2208− onRetry = { vm.reloadAgents() },
2209− onDismiss = { showAgentPicker = false },
2210− )
2211− }
2212−
2213− if (showCommandPicker) {
2214− CommandPickerSheet(
2215− commands = commands,
2216− loading = commandsLoading,
2217− error = commandsError,
2218− onSelect = { vm.runCommand(it) },
2219− onRetry = { vm.reloadCommands() },
2220− onDismiss = { showCommandPicker = false },
2221− )
2222− }
2223−
2224− pendingPermission?.let { permission ->
2225− PermissionDialog(
2226− permission = permission,
2227− position = permissionProgress.position,
2228− total = permissionProgress.total,
2229− onRespond = { response -> vm.respondPermission(permission, response) },
2230− // On auto-reject timeout, post a notification so a returning user finds a
2231− // persistent record of why the run stopped (the dialog itself is gone).
2232− // Gated by the user's notification setting (notifPermission).
2233− onAutoReject = {
2234− val conn = activeConnection
2235− val ctx = appContext
2236− val title = sessionTitle ?: sessionId
2237− if (notifPermission) {
2238− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2239− ctx, sessionId, title, conn?.profile?.id,
2240− )
2241− }
2242− },
2243− )
2244− }
2245−
2246− if (showPalette) {
2247− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2248− }
2249−
2250− if (showShortcutsDialog) {
2251− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2252− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2253− // depends on the "Send on Enter" setting, noted inline.
2254− AlertDialog(
2255− onDismissRequest = { showShortcutsDialog = false },
2256− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2257− text = {
2258− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2259− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2260− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2261− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2262− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2263− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2264− }
2265− },
2266− confirmButton = {
2267− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2268− },
2269− )
2270− }
2271−}
2272−
2273−@Composable
2274−private fun ShortcutRow(keys: String, desc: String) {
2275− Row(verticalAlignment = Alignment.CenterVertically) {
2276− Text(
2277− keys,
2278− style = MaterialTheme.typography.labelLarge,
2279− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2280− modifier = Modifier.widthIn(min = 160.dp),
2281− )
2282− Text(
2283− desc,
2284− style = MaterialTheme.typography.bodyMedium,
2285− color = MaterialTheme.colorScheme.onSurfaceVariant,
2286− )
2287− }
2288−}
2289−
2290−/**
2291− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2292− * of matching commands above the composer. Tapping a command fires it immediately.
2293− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2294− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2295− */
2296−@Composable
2297−private fun SlashCommandAutocomplete(
2298− value: String,
2299− commands: List<Command>,
2300− running: Boolean,
2301− onRunCommand: (Command) -> Unit,
2302−) {
2303− if (running || commands.isEmpty()) return
2304− val slashQuery = remember(value) {
2305− if (value.startsWith("/")) value.removePrefix("/") else null
2306− } ?: return
2307− val matchingCommands = remember(slashQuery, commands) {
2308− commands.filter { cmd ->
2309− slashQuery.isEmpty() ||
2310− cmd.name.contains(slashQuery, ignoreCase = true) ||
2311− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2312− }.take(8)
2313− }
2314− if (matchingCommands.isNotEmpty()) {
2315− CommandAutocompleteDropdown(
2316− commands = matchingCommands,
2317− onPick = onRunCommand,
2318− )
2319− }
2320−}
2321−
2322−/**
2323− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2324− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2325− * user can discover and invoke commands by typing the conventional "/" prefix instead
2326− * of opening the overflow menu / command palette. Tapping a row fires the command.
2327− */
2328−@Composable
2329−private fun CommandAutocompleteDropdown(
2330− commands: List<Command>,
2331− onPick: (Command) -> Unit,
2332−) {
2333− val haptics = LocalHapticFeedback.current
2334− Surface(
2335− color = MaterialTheme.colorScheme.surface,
2336− tonalElevation = 3.dp,
2337− shape = MaterialTheme.shapes.medium,
2338− modifier = Modifier
2339− .fillMaxWidth()
2340− .padding(horizontal = 8.dp, vertical = 4.dp)
2341− .heightIn(max = 240.dp),
2342− ) {
2343− LazyColumn {
2344− items(
2345− count = commands.size,
2346− key = { commands[it].name },
2347− ) { i ->
2348− val cmd = commands[i]
2349− Row(
2350− modifier = Modifier
2351− .fillMaxWidth()
2352− .clickable(role = Role.Button) {
2353− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2354− onPick(cmd)
2355− }
2356− .padding(horizontal = 16.dp, vertical = 10.dp),
2357− verticalAlignment = Alignment.CenterVertically,
2358− horizontalArrangement = Arrangement.spacedBy(12.dp),
2359− ) {
2360− Text(
2361− "/${cmd.name}",
2362− style = MaterialTheme.typography.labelLarge,
2363− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2364− color = MaterialTheme.colorScheme.primary,
2365− )
2366− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2367− Text(
2368− desc,
2369− style = MaterialTheme.typography.bodySmall,
2370− color = MaterialTheme.colorScheme.onSurfaceVariant,
2371− maxLines = 1,
2372− overflow = TextOverflow.Ellipsis,
2373− )
2374− }
2375− }
2376− }
2377− }
2378− }
2379−}
2380−
2381−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2382−@Suppress("CyclomaticComplexMethod")
2383−@Composable
2384−private fun ChatInputBar(
2385− value: String,
2386− onValueChange: (String) -> Unit,
2387− running: Boolean,
2388− aborting: Boolean,
2389− enabled: Boolean,
2390− sendOnEnter: Boolean,
2391− onSend: () -> Unit,
2392− onAbort: () -> Unit,
2393− queuedFollowUp: String?,
2394− onQueueFollowUp: (String) -> Unit,
2395− onCancelQueue: () -> Unit,
2396− focusRequester: androidx.compose.ui.focus.FocusRequester,
2397− attachments: List<PendingAttachment>,
2398− staging: Boolean,
2399− stagingFileCount: Int,
2400− onRemoveAttachment: (String) -> Unit,
2401− onPickPhoto: () -> Unit,
2402− onPickFile: () -> Unit,
2403− onCamera: () -> Unit,
2404− onVoice: () -> Unit,
2405− onPasteImage: (List<Uri>) -> Unit,
2406− commands: List<Command> = emptyList(),
2407− onRunCommand: (Command) -> Unit = {},
2408−) {
2409− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2410− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2411− val context = LocalContext.current
2412− // Full-screen editor state: opened when the user wants more space for a long prompt.
2413− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2414− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2415− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2416− // A queued follow-up replaces the Stop button with a "queued" chip so the
2417− // user sees their message will be sent when the run finishes, and can cancel.
2418− if (queuedFollowUp != null) {
2419− val editLabel = stringResource(R.string.edit)
2420− Row(
2421− modifier = Modifier
2422− .fillMaxWidth()
2423− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2424− verticalAlignment = Alignment.CenterVertically,
2425− ) {
2426− // Tapping the chip reloads the queued text into the draft (and clears the
2427− // queue) so a typo spotted while queuing can be fixed without retyping.
2428− Column(
2429− modifier = Modifier
2430− .weight(1f)
2431− .clip(MaterialTheme.shapes.small)
2432− .clickable(role = Role.Button, onClickLabel = editLabel) {
2433− onValueChange(queuedFollowUp)
2434− onCancelQueue()
2435− }
2436− .padding(vertical = 4.dp),
2437− ) {
2438− Text(
2439− stringResource(R.string.queued),
2440− style = MaterialTheme.typography.labelSmall,
2441− color = MaterialTheme.colorScheme.onSurfaceVariant,
2442− )
2443− Text(
2444− queuedFollowUp,
2445− style = MaterialTheme.typography.bodySmall,
2446− color = MaterialTheme.colorScheme.onSurfaceVariant,
2447− maxLines = 1,
2448− overflow = TextOverflow.Ellipsis,
2449− )
2450− }
2451− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2452− Text(stringResource(R.string.cancel))
2453− }
2454− }
2455− }
2456− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2457− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2458− // Slash-command autocomplete: extracted to a helper to keep this function's
2459− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2460− // start with "/" or the command catalog is empty.
2461− SlashCommandAutocomplete(
2462− value = value,
2463− commands = commands,
2464− running = running,
2465− onRunCommand = onRunCommand,
2466− )
2467− Row(
2468− modifier = Modifier.fillMaxWidth().padding(8.dp),
2469− verticalAlignment = Alignment.Bottom,
2470− ) {
2471− // Attach menu: photo picker, camera, or any file.
2472− var showAttachMenu by remember { mutableStateOf(false) }
2473− Box {
2474− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2475− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2476− }
2477− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2478− DropdownMenuItem(
2479− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2480− text = { Text(stringResource(R.string.attach_photo)) },
2481− onClick = { showAttachMenu = false; onPickPhoto() },
2482− )
2483− DropdownMenuItem(
2484− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2485− text = { Text(stringResource(R.string.attach_camera)) },
2486− onClick = { showAttachMenu = false; onCamera() },
2487− )
2488− DropdownMenuItem(
2489− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2490− text = { Text(stringResource(R.string.attach_file)) },
2491− onClick = { showAttachMenu = false; onPickFile() },
2492− )
2493− }
2494− }
2495− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2496− // disabled) when the device has no speech-recognition activity, so a user
2497− // without a voice app doesn't get a button that only fails noisily on tap.
2498− val voiceAvailable = remember {
2499− val pm = context.packageManager
2500− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2501− pm.queryIntentActivities(intent, 0).isNotEmpty()
2502− }
2503− if (voiceAvailable) {
2504− IconButton(onClick = onVoice, enabled = enabled) {
2505− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2506− }
2507− }
2508− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2509− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2510− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2511− }
2512− OutlinedTextField(
2513− value = value,
2514− onValueChange = { v ->
2515− // Cap input length so a huge paste can't stall the UI. Shares are
2516− // capped separately in MainActivity; this guards typed/pasted drafts.
2517− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2518− },
2519− modifier = Modifier
2520− .weight(1f)
2521− .focusRequester(focusRequester)
2522− .testTag("chat_input")
2523− // Intercept image content pasted/dropped into the field (keyboard paste
2524− // of a copied screenshot, drag from Files, etc.) and route it through the
2525− // same staging path as the attach menu. Non-image content (text) falls
2526− // through unchanged so normal typing/paste works.
2527− .contentReceiver(
2528− remember {
2529− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2530− val clipData = transferable.clipEntry?.clipData
2531− if (clipData != null) {
2532− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2533− val item = clipData.getItemAt(i)
2534− item.uri?.takeIf { uri ->
2535− item.text == null && uri.toString().let { s ->
2536− s.startsWith("content:") || s.startsWith("file:")
2537− }
2538− }
2539− }
2540− if (imageUris.isNotEmpty()) {
2541− onPasteImage(imageUris)
2542− }
2543− }
2544− transferable
2545− }
2546− },
2547− )
2548− .onPreviewKeyEvent { event ->
2549− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2550− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2551− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2552− val send = enterShouldSend(
2553− enabled = enabled,
2554− hasContent = hasContent,
2555− sendOnEnter = sendOnEnter,
2556− shift = event.isShiftPressed,
2557− ctrl = event.isCtrlPressed,
2558− )
2559− if (send) {
2560− if (running) onQueueFollowUp(value) else onSend()
2561− true
2562− } else {
2563− false
2564− }
2565− },
2566− // While a run is active a typed message only queues (sends after the run), so
2567− // the placeholder says so instead of the plain "Message…".
2568− placeholder = {
2569− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2570− },
2571− enabled = enabled,
2572− maxLines = 6,
2573− // Show a "N / max" countdown once the draft crosses a high fraction of
2574− // the cap, so the user knows a paste is about to be truncated instead
2575− // of being silently cut off. Hidden for normal short prompts to avoid
2576− // clutter under a typical one-line message.
2577− supportingText = {
2578− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2579− if (value.length >= threshold) {
2580− Text(
2581− stringResource(
2582− R.string.draft_chars_remaining,
2583− NetworkConfig.maxDraftLengthChars - value.length,
2584− NetworkConfig.maxDraftLengthChars,
2585− ),
2586− style = MaterialTheme.typography.labelSmall,
2587− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2588− else MaterialTheme.colorScheme.onSurfaceVariant,
2589− )
2590− } else if (value.lines().size > 6) {
2591− // The inline field caps at 6 lines; once the draft crosses that,
2592− // hint that a bigger full-screen editor exists (the Expand icon
2593− // above is easy to miss among the icon row). A tappable label
2594− // would be ideal, but a plain hint is enough to draw attention.
2595− Text(
2596− stringResource(R.string.open_full_editor_hint),
2597− style = MaterialTheme.typography.labelSmall,
2598− color = MaterialTheme.colorScheme.onSurfaceVariant,
2599− )
2600− }
2601− },
2602− keyboardOptions = KeyboardOptions(
2603− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2604− // keyboard shows a send key — matching the setting's intent and
2605− // giving touch-only users a keyboard send affordance. When off,
2606− // ImeAction.Default keeps the enter/newline key for multi-line input.
2607− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2608− capitalization = KeyboardCapitalization.Sentences,
2609− ),
2610− keyboardActions = KeyboardActions(
2611− onSend = {
2612− // Mirror the hardware-Enter handler: during a run the soft-keyboard
2613− // send key must queue the follow-up, not silently drop it. vm.send()
2614− // returns false while a run is active (beginRun() rejects), so calling
2615− // onSend() directly here would lose the typed message with no feedback
2616− // for touch-only users (no hardware Enter path available).
2617− if (enabled && hasContent) {
2618− if (running) onQueueFollowUp(value) else onSend()
2619− }
2620− },
2621− ),
2622− )
2623− ComposerTrailingButton(
2624− running = running,
2625− aborting = aborting,
2626− canSend = enabled && hasContent,
2627− canQueue = enabled && value.isNotBlank(),
2628− onSend = onSend,
2629− onAbort = onAbort,
2630− onQueue = { onQueueFollowUp(value) },
2631− )
2632− }
2633− }
2634− if (showFullScreenEditor) {
2635− FullScreenEditor(
2636− value = value,
2637− onValueChange = onValueChange,
2638− onDismiss = { showFullScreenEditor = false },
2639− onSend = {
2640− showFullScreenEditor = false
2641− // Mirror the inline composer's behavior: while a run is active a send
2642− // can't go immediately, so queue the follow-up instead of silently
2643− // dropping it (vm.send() returns false during a run, which previously
2644− // lost the typed message with no feedback).
2645− if (running) onQueueFollowUp(value) else onSend()
2646− },
2647− canSend = enabled && hasContent,
2648− running = running,
2649− sendOnEnter = sendOnEnter,
2650− attachments = attachments,
2651− onRemoveAttachment = onRemoveAttachment,
2652− staging = staging,
2653− stagingFileCount = stagingFileCount,
2654− )
2655− }
2656− }
2657−}
2658−
2659−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2660− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2661−@OptIn(ExperimentalMaterial3Api::class)
2662−@Composable
2663−private fun FullScreenEditor(
2664− value: String,
2665− onValueChange: (String) -> Unit,
2666− onDismiss: () -> Unit,
2667− onSend: () -> Unit,
2668− canSend: Boolean,
2669− running: Boolean = false,
2670− sendOnEnter: Boolean = false,
2671− attachments: List<PendingAttachment> = emptyList(),
2672− onRemoveAttachment: (String) -> Unit = {},
2673− staging: Boolean = false,
2674− stagingFileCount: Int = 0,
2675−) {
2676− androidx.compose.ui.window.Dialog(
2677− onDismissRequest = onDismiss,
2678− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2679− ) {
2680− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2681− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2682− // gives the available width so we can center a capped-width column.
2683− androidx.compose.foundation.layout.BoxWithConstraints(
2684− modifier = Modifier.fillMaxSize(),
2685− contentAlignment = Alignment.Center,
2686− ) {
2687− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2688− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2689− else 0.dp
2690− Scaffold(
2691− modifier = Modifier.padding(horizontal = hPad),
2692− topBar = {
2693− androidx.compose.material3.TopAppBar(
2694− title = { Text(stringResource(R.string.compose_editor_title)) },
2695− navigationIcon = {
2696− androidx.compose.material3.TextButton(onClick = onDismiss) {
2697− Text(stringResource(R.string.collapse_editor))
2698− }
2699− },
2700− )
2701− },
2702− bottomBar = {
2703− Surface(tonalElevation = 3.dp) {
2704− Row(
2705− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2706− horizontalArrangement = Arrangement.End,
2707− ) {
2708− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2709− Text(stringResource(if (running) R.string.queue else R.string.send))
2710− }
2711− }
2712− }
2713− },
2714− ) { padding ->
2715− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2716− // Show staged attachments in the full-screen editor too, so a user who staged
2717− // images then expanded for a long prompt can still see and remove them without
2718− // collapsing first (mirrors the inline composer's AttachmentStrip).
2719− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2720− OutlinedTextField(
2721− value = value,
2722− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2723− modifier = Modifier
2724− .fillMaxSize()
2725− .weight(1f)
2726− // Honor the "Send on Enter" setting here too, so the full-screen
2727− // editor matches the inline composer: Enter sends (Shift+Enter
2728− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2729− // when off. Previously this hard-coded ImeAction.Default and had no
2730− // key handler, so a hardware-keyboard user got a different behaviour
2731− // from the inline composer depending on which they happened to open.
2732− .onPreviewKeyEvent { event ->
2733− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2734− val send = enterShouldSend(
2735− enabled = canSend,
2736− hasContent = canSend,
2737− sendOnEnter = sendOnEnter,
2738− shift = event.isShiftPressed,
2739− ctrl = event.isCtrlPressed,
2740− )
2741− if (send) { onSend(); true } else false
2742− },
2743− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2744− maxLines = Int.MAX_VALUE,
2745− keyboardOptions = KeyboardOptions(
2746− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2747− capitalization = KeyboardCapitalization.Sentences,
2748− ),
2749− keyboardActions = KeyboardActions(
2750− onSend = { if (canSend) onSend() },
2751− ),
2752− )
2753− }
2754− }
2755− }
2756− }
2757−}
2758−
2759−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2760− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2761−private fun enterShouldSend(
2762− enabled: Boolean,
2763− hasContent: Boolean,
2764− sendOnEnter: Boolean,
2765− shift: Boolean,
2766− ctrl: Boolean,
2767−): Boolean = when {
2768− !enabled || !hasContent -> false
2769− sendOnEnter -> !shift
2770− else -> ctrl
2771−}
2772−
2773−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2774− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2775− * [ChatInputBar] stays under the complexity threshold. */
2776−@Composable
2777−private fun ComposerTrailingButton(
2778− running: Boolean,
2779− aborting: Boolean,
2780− canSend: Boolean,
2781− canQueue: Boolean,
2782− onSend: () -> Unit,
2783− onAbort: () -> Unit,
2784− onQueue: () -> Unit,
2785−) {
2786− if (running) {
2787− Row(verticalAlignment = Alignment.CenterVertically) {
2788− // While a run is active the trailing action is Stop, so the only send affordance is
2789− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2790− // That leaves a touch-only user with the setting off no way to queue a follow-up
2791− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2792− // there's typed TEXT so queuing is always reachable, without changing the user's
2793− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2794− // canSend, which is also true for an attachment-only composer — because queuing "" just
2795− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2796− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2797− if (canQueue) {
2798− IconButton(
2799− onClick = onQueue,
2800− modifier = Modifier.testTag("queue_button"),
2801− ) {
2802− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2803− // icon (which can be read as "snooze" or "later"), and isn't confused with
2804− // the Send action sitting right beside the Stop button.
2805− Icon(
2806− Icons.AutoMirrored.Filled.PlaylistAdd,
2807− contentDescription = stringResource(R.string.queue_followup),
2808− )
2809− }
2810− }
2811− // Show a spinner while the abort REST call is in flight so the user sees the stop
2812− // was sent, and disable to prevent a double-tap.
2813− IconButton(
2814− onClick = onAbort,
2815− enabled = !aborting,
2816− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2817− ) {
2818− if (aborting) {
2819− val stopLabel = stringResource(R.string.stop)
2820− CircularProgressIndicator(
2821− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2822− strokeWidth = 2.dp,
2823− )
2824− } else {
2825− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2826− }
2827− }
2828− }
2829− } else {
2830− IconButton(
2831− onClick = onSend,
2832− enabled = canSend,
2833− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2834− ) {
2835− // Tint the send icon with primary when there's content to send so the commit action
2836− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2837− Icon(
2838− Icons.AutoMirrored.Filled.Send,
2839− contentDescription = stringResource(R.string.send),
2840− tint = if (canSend) MaterialTheme.colorScheme.primary
2841− else MaterialTheme.colorScheme.onSurfaceVariant,
2842− )
2843− }
2844− }
2845−}
2846−
2847−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2848−@Composable
2849−private fun EmptyConversation(
2850− onSuggestion: (String) -> Unit,
2851− modifier: Modifier = Modifier,
2852−) {
2853− // A few example prompts so a first-time user has a one-tap path to their first
2854− // message instead of staring at a blank input. Tapping a chip fills the draft
2855− // (without sending) so the user can edit it before sending.
2856− val suggestions = remember {
2857− listOf(
2858− R.string.empty_chat_suggest_1,
2859− R.string.empty_chat_suggest_2,
2860− R.string.empty_chat_suggest_3,
2861− )
2862− }
2863− Column(
2864− modifier = modifier.padding(32.dp),
2865− horizontalAlignment = Alignment.CenterHorizontally,
2866− ) {
2867− Icon(
2868− Icons.Filled.AutoAwesome,
2869− contentDescription = null,
2870− modifier = Modifier.size(48.dp),
2871− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2872− )
2873− Spacer(Modifier.size(16.dp))
2874− Text(
2875− stringResource(R.string.empty_chat_title),
2876− style = MaterialTheme.typography.titleMedium,
2877− )
2878− Spacer(Modifier.size(8.dp))
2879− Text(
2880− stringResource(R.string.empty_chat_hint),
2881− style = MaterialTheme.typography.bodyMedium,
2882− color = MaterialTheme.colorScheme.onSurfaceVariant,
2883− )
2884− Spacer(Modifier.size(20.dp))
2885− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2886− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2887− FlowRow(
2888− modifier = Modifier.fillMaxWidth(),
2889− horizontalArrangement = Arrangement.spacedBy(8.dp),
2890− verticalArrangement = Arrangement.spacedBy(8.dp),
2891− ) {
2892− suggestions.forEach { resId ->
2893− val text = stringResource(resId)
2894− androidx.compose.material3.AssistChip(
2895− onClick = { onSuggestion(text) },
2896− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2897− )
2898− }
2899− }
2900− }
2901−}
2902−
2903−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2904− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2905− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2906−@Composable
2907−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2908− val haptics = LocalHapticFeedback.current
2909− var showDiff by rememberSaveable { mutableStateOf(false) }
2910− val expandMotion = rememberVisibilityTransitions()
2911− Surface(
2912− color = MaterialTheme.colorScheme.tertiaryContainer,
2913− tonalElevation = 2.dp,
2914− modifier = Modifier.fillMaxWidth(),
2915− ) {
2916− Column {
2917− Row(
2918− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2919− verticalAlignment = Alignment.CenterVertically,
2920− horizontalArrangement = Arrangement.SpaceBetween,
2921− ) {
2922− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2923− Icon(
2924− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2925− contentDescription = null,
2926− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2927− modifier = Modifier.size(18.dp),
2928− )
2929− Text(
2930− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2931− style = MaterialTheme.typography.bodySmall,
2932− color = MaterialTheme.colorScheme.onTertiaryContainer,
2933− modifier = Modifier.padding(start = 8.dp),
2934− )
2935− // "Show what changed" toggle, shown only when the server provided a diff.
2936− // Collapsible so the banner stays compact by default; a user curious about
2937− // what the revert rolled back can expand it inline without leaving the chat.
2938− if (!diff.isNullOrBlank()) {
2939− TextButton(
2940− onClick = {
2941− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2942− showDiff = !showDiff
2943− },
2944− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2945− ) {
2946− Icon(
2947− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2948− contentDescription = null,
2949− modifier = Modifier.size(16.dp),
2950− )
2951− Text(
2952− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2953− style = MaterialTheme.typography.labelSmall,
2954− modifier = Modifier.padding(start = 4.dp),
2955− )
2956− }
2957− }
2958− }
2959− TextButton(onClick = {
2960− // Haptic on undo to match the other destructive/important confirmations: a
2961− // revert restores potentially hundreds of hidden messages.
2962− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2963− onUndo()
2964− }) { Text(stringResource(R.string.undo)) }
2965− }
2966− // The diff render lives inside the banner's Surface so it inherits the tertiary
2967− // tonal container and reads as part of the banner, not a floating panel.
2968− if (!diff.isNullOrBlank()) {
2969− AnimatedVisibility(
2970− visible = showDiff,
2971− enter = expandMotion.enter,
2972− exit = expandMotion.exit,
2973− ) {
2974− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2975− Text(
2976− stringResource(R.string.revert_diff_header),
2977− style = MaterialTheme.typography.labelSmall,
2978− color = MaterialTheme.colorScheme.onTertiaryContainer,
2979− modifier = Modifier.padding(bottom = 4.dp),
2980− )
2981− DiffView(diff, saveKey = "revertDiff")
2982− }
2983− }
2984− }
2985− }
2986− }
2987−}
2988−
2989−/** A dismissible preview card shown above the composer when the user quote-replied to a
2990− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2991− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2992− * the Discord/Slack quote-preview pattern. */
2993−@Composable
2994−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2995− val haptics = LocalHapticFeedback.current
2996− Surface(
2997− color = MaterialTheme.colorScheme.secondaryContainer,
2998− tonalElevation = 2.dp,
2999− modifier = Modifier.fillMaxWidth(),
3000− ) {
3001− Row(
3002− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
3003− verticalAlignment = Alignment.Top,
3004− ) {
3005− Icon(
3006− Icons.Filled.FormatQuote,
3007− contentDescription = null,
3008− tint = MaterialTheme.colorScheme.onSecondaryContainer,
3009− modifier = Modifier.size(18.dp).padding(top = 2.dp),
3010− )
3011− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
3012− Text(
3013− stringResource(R.string.quote_reply_banner),
3014− style = MaterialTheme.typography.labelSmall,
3015− color = MaterialTheme.colorScheme.onSecondaryContainer,
3016− )
3017− Text(
3018− quotedText,
3019− style = MaterialTheme.typography.bodySmall,
3020− color = MaterialTheme.colorScheme.onSecondaryContainer,
3021− maxLines = 2,
3022− overflow = TextOverflow.Ellipsis,
3023− )
3024− }
3025− IconButton(onClick = {
3026− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
3027− onCancel()
3028− }) {
3029− Icon(
3030− Icons.Filled.Close,
3031− contentDescription = stringResource(R.string.cancel_quote_reply),
3032− tint = MaterialTheme.colorScheme.onSecondaryContainer,
3033− modifier = Modifier.size(18.dp),
3034− )
3035− }
3036− }
3037− }
3038−}
3039−
3040−/** A banner shown while messages composed offline are queued in the outbox, with a
3041− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
3042−@Composable
3043−private fun OutboxBanner(
3044− count: Int,
3045− sending: Boolean,
3046− onFlush: () -> Unit,
3047− onDiscard: () -> Unit,
3048−) {
3049− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
3050− Surface(
3051− color = MaterialTheme.colorScheme.secondaryContainer,
3052− tonalElevation = 2.dp,
3053− modifier = Modifier.fillMaxWidth(),
3054− ) {
3055− Row(
3056− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
3057− verticalAlignment = Alignment.CenterVertically,
3058− horizontalArrangement = Arrangement.SpaceBetween,
3059− ) {
3060− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
3061− if (sending) {
3062− CircularProgressIndicator(
3063− Modifier.size(16.dp),
3064− strokeWidth = 2.dp,
3065− color = MaterialTheme.colorScheme.onSecondaryContainer,
3066− )
3067− Spacer(Modifier.size(8.dp))
3068− }
3069− Text(
3070− if (sending) {
3071− stringResource(R.string.outbox_sending)
3072− } else {
3073− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
3074− stringResource(res, count)
3075− },
3076− style = MaterialTheme.typography.bodySmall,
3077− color = MaterialTheme.colorScheme.onSecondaryContainer,
3078− )
3079− }
3080− if (!sending) {
3081− val haptics = LocalHapticFeedback.current
3082− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
3083− TextButton(onClick = {
3084− // Confirm before discarding all queued messages (irreversible), matching
3085− // the confirmation pattern used by deleteSession and other destructive
3086− // actions. Previously a single tap dropped every queued message.
3087− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
3088− showDiscardConfirm = true
3089− }) {
3090− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
3091− }
3092− }
3093− }
3094− }
3095− if (showDiscardConfirm) {
3096− androidx.compose.material3.AlertDialog(
3097− onDismissRequest = { showDiscardConfirm = false },
3098− title = { Text(stringResource(R.string.discard_queued_title)) },
3099− text = { Text(stringResource(R.string.discard_queued_text, count)) },
3100− confirmButton = {
3101− androidx.compose.material3.TextButton(onClick = {
3102− showDiscardConfirm = false
3103− onDiscard()
3104− }) { Text(stringResource(R.string.discard)) }
3105− },
3106− dismissButton = {
3107− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3108− Text(stringResource(R.string.cancel))
3109− }
3110− },
3111− )
3112− }
3113−}
3114−
3115−/** Prompt for a one-off shell command to run in the session's worktree. */
3116−@Composable
3117−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3118− var command by rememberSaveable { mutableStateOf("") }
3119− AlertDialog(
3120− onDismissRequest = onDismiss,
3121− title = { Text(stringResource(R.string.run_shell_command)) },
3122− text = {
3123− OutlinedTextField(
3124− value = command,
3125− onValueChange = { command = it },
3126− modifier = Modifier.fillMaxWidth(),
3127− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3128− label = { Text(stringResource(R.string.shell_command_label)) },
3129− singleLine = true,
3130− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3131− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3132− )
3133− },
3134− confirmButton = {
3135− TextButton(
3136− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3137− enabled = command.isNotBlank(),
3138− ) { Text(stringResource(R.string.run)) }
3139− },
3140− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3141− )
3142−}
3143−
3144−/**
3145− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3146− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3147− * equality is structural so `snapshotFlow` emits only when something relevant changes.
3148− */
3149−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3150−
3151−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3152− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3153− * streaming, not just plain assistant text. O(1). */
3154−private fun streamingContentLength(part: Part?): Int = when (part) {
3155− is TextPart -> part.text.length
3156− is ReasoningPart -> part.text.length
3157− is ToolPart -> when (val st = part.state) {
3158− is ToolCompleted -> st.output?.length ?: 0
3159− is ToolError -> st.error?.length ?: 0
3160− is ToolRunning -> st.title?.length ?: 0
3161− else -> 0
3162− }
3163− else -> 0
3164−}
3165−
3166−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3167− * dialog but lives in the chat screen so the user can rename without backing out to
3168− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3169−@Composable
3170−private fun RenameSessionChatDialog(
3171− initialTitle: String,
3172− onDismiss: () -> Unit,
3173− onConfirm: (String) -> Unit,
3174−) {
3175− // Seed the field once (no key input) so a later external title change — e.g. opencode
3176− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3177− // doesn't re-initialize the box and discard the user's in-progress edit.
3178− var title by rememberSaveable { mutableStateOf(initialTitle) }
3179− AlertDialog(
3180− onDismissRequest = onDismiss,
3181− title = { Text(stringResource(R.string.rename_session_chat)) },
3182− text = {
3183− OutlinedTextField(
3184− value = title,
3185− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3186− modifier = Modifier.fillMaxWidth(),
3187− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3188− label = { Text(stringResource(R.string.rename_session_chat)) },
3189− singleLine = true,
3190− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3191− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3192− )
3193− },
3194− confirmButton = {
3195− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3196− Text(stringResource(R.string.save))
3197− }
3198− },
3199− dismissButton = {
3200− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3201− },
3202− )
3203−}
3204−
3205−/**
3206− * A single item in the chat message list — either a [Message] bubble or a day
3207− * [Separator] inserted before the first message of a new day. The separator shifts
3208− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3209− * the [List] of these items (not `messages.size`/`lastIndex`).
3210− */
3211−private sealed interface MessageListItem {
3212− val key: Any
3213− val contentType: Any
3214−
3215− data class Message(
3216− val message: MessageWithParts,
3217− override val key: Any,
3218− // Whether this is the first message in a consecutive run of the same speaker (role).
3219− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3220− // reducing visual noise in tool-heavy conversations where many assistant messages
3221− // appear back-to-back. A separator or a role change resets the flag.
3222− val isFirstOfSpeaker: Boolean,
3223− ) : MessageListItem {
3224− override val contentType: Any get() = message.info::class
3225− }
3226−
3227− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3228− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3229− // can share a label (e.g. an untimestamped message — empty label — between two
3230− // same-day messages, or two untimestamped groups), and a label-only key would
3231− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3232− // stable for a given message ordering so slots aren't needlessly recreated.
3233− override val key: Any get() = "sep_${ordinal}_$label"
3234− // Separators share a contentType so the LazyColumn can recycle their slots.
3235− override val contentType: Any get() = "separator"
3236− }
3237−}
3238−
3239−/**
3240− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3241− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3242− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3243− * Messages with no timestamp are grouped under an empty-label separator only if they
3244− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3245− *
3246− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3247− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3248− * labels; older days fall back to a locale-stable medium-date format.
3249− */
3250−private fun buildMessageListItems(
3251− messages: List<MessageWithParts>,
3252− todayLabel: String,
3253− yesterdayLabel: String,
3254−): List<MessageListItem> {
3255− if (messages.isEmpty()) return emptyList()
3256− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3257− val dateFmt = mediumDateFormat()
3258− val result = ArrayList<MessageListItem>(messages.size + 4)
3259− val seenKeys = HashSet<String>(messages.size * 2)
3260− var lastDayKey: String? = null
3261− var sepOrdinal = 0
3262− var emptyIdOrdinal = 0
3263− var first = true
3264− // Track the previous message's role to detect consecutive same-speaker runs, so the
3265− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3266− // "no previous message or a separator just interrupted the run", both of which make the
3267− // next message the first of its group.
3268− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3269− for (message in messages) {
3270− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3271− val dayKey = ts?.let { dayKey(it) } ?: ""
3272− // Emit a separator before the very first message (so a leading un-timestamped message
3273− // still gets the first divider, empty label and all), and thereafter only when crossing
3274− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3275− // neither emits its own separator nor resets the day — otherwise a following same-day
3276− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3277− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3278− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3279− // A date separator visually breaks a speaker run, so the next message is treated
3280− // as the first of its group (even if the same role continues across the day break).
3281− prevRoleClass = null
3282− }
3283− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3284− first = false
3285− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3286− // empty id — and the reducer intentionally keeps several such messages as distinct
3287− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3288− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3289− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3290− if (!seenKeys.add(key)) {
3291− var suffix = 1
3292− while (!seenKeys.add("$key#$suffix")) suffix++
3293− key = "$key#$suffix"
3294− }
3295− val roleClass = message.info::class
3296− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3297− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3298− prevRoleClass = roleClass
3299− }
3300− return result
3301−}
3302−
3303−/**
3304− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3305− *
3306− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3307− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3308− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3309− * every message on every token. Message timestamps are immutable once assigned, so we
3310− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3311− * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3312− *
3313− * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3314− * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3315− * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3316− * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3317− * reads, so the common case (a hit) is a single volatile read + hash probe.
3318− * [removeEldestEntry] is not available on ConcurrentHashMap, so the bound is enforced via
3319− * a size check in [dayKey]: once the cap ([DAY_KEY_CACHE_MAX]) is reached the cache is
3320− * cleared; in practice the cache size is bounded by the number of distinct message
3321− * timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]) and the cap is a
3322− * safety valve for the process-lifetime cache across many sessions.
3323− */
3324−private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3325−
3326−/** Upper bound on [dayKeyCache] entries. Message timestamps are immutable once assigned, so
3327− * the natural bound is the number of distinct timestamps in a session (≤
3328− * [NetworkConfig.maxInMemoryMessages]); this cap is a safety valve for the process-lifetime
3329− * cache across many sessions, keeping a runaway leak from accumulating unbounded memory. */
3330−private const val DAY_KEY_CACHE_MAX = 1024
3331−
3332−private fun dayKey(epochMillis: Long): String {
3333− val cached = dayKeyCache[epochMillis]
3334− if (cached != null) return cached
3335− val value = java.time.Instant.ofEpochMilli(epochMillis)
3336− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3337− // Guard the size under the cache's concurrency: only the first thread to see the cap
3338− // exceeded evicts (draining is O(N) but rare and idempotent), so concurrent inserts
3339− // past the cap don't each pay the scan. computeIfAbsent would hold the segment lock
3340− // during the (cheap) date computation but can't express the size guard, so use put
3341− // after the fact; a duplicate put of the same key/value is harmless.
3342− if (dayKeyCache.size >= DAY_KEY_CACHE_MAX) dayKeyCache.clear()
3343− dayKeyCache[epochMillis] = value
3344− return value
3345−}
3346−
3347−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3348−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3349−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3350−private var cachedDateFmt: java.text.DateFormat? = null
3351−private var cachedDateFmtLocale: java.util.Locale? = null
3352−
3353−private fun mediumDateFormat(): java.text.DateFormat {
3354− val locale = java.util.Locale.getDefault()
3355− val existing = cachedDateFmt
3356− if (existing != null && cachedDateFmtLocale == locale) return existing
3357− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3358− cachedDateFmt = it
3359− cachedDateFmtLocale = locale
3360− }
3361−}
3362−
3363−/**
3364− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3365− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3366− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3367− * messages.
3368− */
3369−private fun dayLabel(
3370− dayKey: String,
3371− ts: Long,
3372− today: java.time.LocalDate,
3373− todayLabel: String,
3374− yesterdayLabel: String,
3375− dateFmt: java.text.DateFormat,
3376−): String {
3377− if (dayKey.isEmpty()) return ""
3378− val epochDay = dayKey.toLongOrNull() ?: return ""
3379− val date = java.time.LocalDate.ofEpochDay(epochDay)
3380− return when {
3381− date == today -> todayLabel
3382− date == today.minusDays(1) -> yesterdayLabel
3383− else -> dateFmt.format(java.util.Date(ts))
3384− }
3385−}
3386−
3387−/**
3388− * A centered day divider in the message list. Renders nothing for an empty label
3389− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3390− */
3391−@Composable
3392−private fun DateSeparator(label: String) {
3393− if (label.isBlank()) return
3394− Row(
3395− modifier = Modifier.fillMaxWidth(),
3396− horizontalArrangement = Arrangement.Center,
3397− ) {
3398− Surface(
3399− color = MaterialTheme.colorScheme.surfaceVariant,
3400− shape = MaterialTheme.shapes.small,
3401− // Marked as a heading so TalkBack users can navigate day-by-day with the
3402− // heading-skip gesture — the canonical affordance for date dividers in a list.
3403− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3404− ) {
3405− Text(
3406− label,
3407− style = MaterialTheme.typography.labelSmall,
3408− color = MaterialTheme.colorScheme.onSurfaceVariant,
3409− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3410− )
3411− }
3412− }
3413−}
3414−
3415−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3416− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3417− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3418− * [BoxScope] extension so it can align itself to the top center of its host box. */
3419−@Composable
3420−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3421− val loadingLabel = stringResource(R.string.loading)
3422− val reducedMotion = LocalReducedMotion.current
3423− val transition = rememberInfiniteTransition(label = "skeleton")
3424− val pulse by transition.animateFloat(
3425− initialValue = 0.35f,
3426− targetValue = 0.7f,
3427− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3428− label = "skeletonAlpha",
3429− )
3430− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3431− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3432− @Composable
3433− fun bar(widthFraction: Float) {
3434− Box(
3435− Modifier
3436− .fillMaxWidth(widthFraction)
3437− .height(14.dp)
3438− .clip(RoundedCornerShape(4.dp))
3439− .background(skeletonColor)
3440− .alpha(skeletonAlpha),
3441− )
3442− }
3443− Column(
3444− modifier = Modifier
3445− .align(Alignment.TopCenter)
3446− .padding(top = topPad)
3447− .padding(16.dp)
3448− .fillMaxWidth()
3449− .semantics { contentDescription = loadingLabel },
3450− verticalArrangement = Arrangement.spacedBy(14.dp),
3451− ) {
3452− repeat(4) { i ->
3453− val left = i % 2 == 0
3454− Row(
3455− modifier = Modifier.fillMaxWidth(),
3456− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3457− ) {
3458− Column(
3459− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3460− verticalArrangement = Arrangement.spacedBy(6.dp),
3461− ) {
3462− bar(1f)
3463− bar(0.8f)
3464− }
3465− }
3466− }
3467− }
3468−}