@@ -0,0 +1,2082 @@
1+@file:Suppress("TooManyFunctions")
3+package soy.iko.opencode.ui.chat
5+import android.app.Activity
6+import android.content.Intent
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.foundation.clickable
15+import androidx.compose.foundation.layout.Arrangement
16+import androidx.compose.foundation.layout.Box
17+import androidx.compose.foundation.layout.Column
18+import androidx.compose.foundation.layout.FlowRow
19+import androidx.compose.foundation.layout.PaddingValues
20+import androidx.compose.foundation.layout.Row
21+import androidx.compose.foundation.layout.Spacer
22+import androidx.compose.foundation.layout.WindowInsets
23+import androidx.compose.foundation.layout.fillMaxSize
24+import androidx.compose.foundation.layout.fillMaxWidth
25+import androidx.compose.foundation.layout.imePadding
26+import androidx.compose.foundation.layout.navigationBars
27+import androidx.compose.foundation.layout.padding
28+import androidx.compose.foundation.layout.size
29+import androidx.compose.foundation.layout.union
30+import androidx.compose.foundation.layout.widthIn
31+import androidx.compose.foundation.layout.windowInsetsPadding
32+import androidx.compose.foundation.layout.wrapContentWidth
33+import androidx.compose.foundation.lazy.LazyColumn
34+import androidx.compose.foundation.lazy.items
35+import androidx.compose.foundation.lazy.rememberLazyListState
36+import androidx.compose.material.icons.Icons
37+import androidx.compose.material.icons.automirrored.filled.ArrowBack
38+import androidx.compose.material.icons.automirrored.filled.Send
39+import androidx.compose.material.icons.filled.Add
40+import androidx.compose.material.icons.filled.AutoAwesome
41+import androidx.compose.material.icons.filled.Delete
42+import androidx.compose.material.icons.filled.Description
43+import androidx.compose.material.icons.filled.Edit
44+import androidx.compose.material.icons.filled.Expand
45+import androidx.compose.material.icons.filled.KeyboardArrowDown
46+import androidx.compose.material.icons.filled.KeyboardArrowUp
47+import androidx.compose.material.icons.filled.Mic
48+import androidx.compose.material.icons.filled.MoreVert
49+import androidx.compose.material.icons.filled.PhotoCamera
50+import androidx.compose.material.icons.filled.PhotoLibrary
51+import androidx.compose.material.icons.filled.Refresh
52+import androidx.compose.material.icons.filled.Restore
53+import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
54+import androidx.compose.material.icons.automirrored.filled.Reply
55+import androidx.compose.material.icons.filled.Schedule
56+import androidx.compose.material.icons.filled.Stop
57+import androidx.compose.material3.AlertDialog
58+import androidx.compose.material3.Badge
59+import androidx.compose.material3.BadgedBox
60+import androidx.compose.material3.Button
61+import androidx.compose.material3.CircularProgressIndicator
62+import androidx.compose.material3.SmallFloatingActionButton
63+import androidx.compose.material3.DropdownMenu
64+import androidx.compose.material3.DropdownMenuItem
65+import androidx.compose.material3.ExperimentalMaterial3Api
66+import androidx.compose.material3.ExtendedFloatingActionButton
67+import androidx.compose.material3.FloatingActionButton
68+import androidx.compose.material3.Icon
69+import androidx.compose.material3.IconButton
70+import androidx.compose.material3.MaterialTheme
71+import androidx.compose.material3.OutlinedTextField
72+import androidx.compose.material3.Scaffold
73+import androidx.compose.material3.SnackbarDuration
74+import androidx.compose.material3.SwipeToDismissBox
75+import androidx.compose.material3.SwipeToDismissBoxValue
76+import androidx.compose.material3.rememberSwipeToDismissBoxState
77+import androidx.compose.material3.SnackbarHost
78+import androidx.compose.material3.SnackbarHostState
79+import androidx.compose.material3.SnackbarResult
80+import androidx.compose.material3.Surface
81+import androidx.compose.material3.Text
82+import androidx.compose.material3.TextButton
83+import androidx.compose.material3.TopAppBar
84+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
85+import androidx.compose.runtime.Composable
86+import androidx.compose.runtime.CompositionLocalProvider
87+import androidx.compose.runtime.DisposableEffect
88+import androidx.compose.runtime.LaunchedEffect
89+import androidx.compose.runtime.derivedStateOf
90+import androidx.compose.runtime.getValue
91+import androidx.compose.runtime.mutableIntStateOf
92+import androidx.compose.runtime.mutableStateOf
93+import androidx.compose.runtime.remember
94+import androidx.compose.runtime.rememberCoroutineScope
95+import androidx.compose.runtime.rememberUpdatedState
96+import androidx.compose.runtime.saveable.rememberSaveable
97+import androidx.compose.runtime.setValue
98+import androidx.compose.runtime.snapshotFlow
99+import androidx.compose.foundation.text.KeyboardActions
100+import androidx.compose.foundation.text.KeyboardOptions
101+import androidx.compose.ui.text.input.KeyboardCapitalization
102+import androidx.compose.ui.Alignment
103+import androidx.compose.ui.Modifier
104+import androidx.compose.ui.focus.focusRequester
105+import androidx.compose.ui.input.key.Key
106+import androidx.compose.ui.input.key.KeyEventType
107+import androidx.compose.ui.input.key.isCtrlPressed
108+import androidx.compose.ui.input.key.isShiftPressed
109+import androidx.compose.ui.input.key.key
110+import androidx.compose.ui.input.key.onPreviewKeyEvent
111+import androidx.compose.ui.input.key.type
112+import androidx.compose.ui.layout.onSizeChanged
113+import androidx.compose.ui.platform.LocalContext
114+import androidx.compose.ui.platform.LocalDensity
115+import androidx.compose.ui.platform.LocalHapticFeedback
116+import androidx.compose.ui.platform.LocalView
117+import androidx.compose.ui.platform.testTag
118+import androidx.compose.ui.res.stringResource
119+import androidx.compose.ui.semantics.Role
120+import androidx.compose.ui.semantics.contentDescription
121+import androidx.compose.ui.semantics.semantics
122+import androidx.compose.ui.text.input.ImeAction
123+import androidx.compose.ui.text.style.TextOverflow
124+import androidx.compose.ui.unit.dp
125+import androidx.lifecycle.compose.collectAsStateWithLifecycle
126+import androidx.lifecycle.viewmodel.compose.viewModel
127+import kotlinx.coroutines.Dispatchers
128+import kotlinx.coroutines.coroutineScope
129+import kotlinx.coroutines.delay
130+import kotlinx.coroutines.flow.distinctUntilChanged
131+import kotlinx.coroutines.launch
132+import kotlinx.coroutines.withContext
133+import soy.iko.opencode.data.model.Part
134+import soy.iko.opencode.data.model.MessageWithParts
135+import soy.iko.opencode.data.model.ReasoningPart
136+import soy.iko.opencode.data.model.TextPart
137+import soy.iko.opencode.data.model.ToolCompleted
138+import soy.iko.opencode.data.model.ToolError
139+import soy.iko.opencode.data.model.ToolPart
140+import soy.iko.opencode.data.model.ToolRunning
141+import soy.iko.opencode.data.network.EventStreamClient
142+import soy.iko.opencode.data.network.NetworkConfig
143+import soy.iko.opencode.di.AppContainer
144+import soy.iko.opencode.R
145+import soy.iko.opencode.ui.components.CommandPalette
146+import soy.iko.opencode.ui.components.ConnectionBanner
147+import soy.iko.opencode.ui.components.PaletteAction
148+import soy.iko.opencode.ui.components.copyToClipboard
149+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
150+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
151+import soy.iko.opencode.ui.components.showToast
152+import soy.iko.opencode.ui.components.toImageContext
153+import soy.iko.opencode.ui.vmFactory
154+import soy.iko.opencode.util.runCatchingCancellable
156+@OptIn(ExperimentalMaterial3Api::class)
159+ container: AppContainer,
162+ onOpenFile: ((String) -> Unit)? = null,
163+ onOpenSession: ((String) -> Unit)? = null,
165+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
166+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
167+ val running by vm.running.collectAsStateWithLifecycle()
168+ val aborting by vm.aborting.collectAsStateWithLifecycle()
169+ val loading by vm.loading.collectAsStateWithLifecycle()
170+ val loadError by vm.loadError.collectAsStateWithLifecycle()
171+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
172+ val models by vm.models.collectAsStateWithLifecycle()
173+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
174+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
175+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
176+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
177+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
178+ val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
179+ val agents by vm.agents.collectAsStateWithLifecycle()
180+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
181+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
182+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
183+ val commands by vm.commands.collectAsStateWithLifecycle()
184+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
185+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
186+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
187+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
188+ val draft by vm.draft.collectAsStateWithLifecycle()
189+ val attachments by vm.attachments.collectAsStateWithLifecycle()
190+ val reverted by vm.reverted.collectAsStateWithLifecycle()
191+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
192+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
193+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
194+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
195+ val haptics = LocalHapticFeedback.current
196+ val scope = rememberCoroutineScope()
197+ val shareContext = LocalContext.current
198+ val defaultShareSubject = stringResource(R.string.share_subject)
199+ val sessionLabel = stringResource(R.string.session)
200+ val defaultModelLabel = stringResource(R.string.default_model)
201+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
203+ append(selectedModel?.modelLabel ?: defaultModelLabel)
204+ selectedAgent?.let { append(" · $it") }
208+ // Connection profile (with auth) for rendering inline image attachments.
209+ // Collect as state so a server switch recomposes the image context.
210+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
211+ val imageContext = remember(activeConnection?.profile) {
212+ activeConnection?.profile?.toImageContext()
215+ // Mark this session as read while the user is viewing it; clear on leave so new
216+ // background activity can badge it again.
217+ DisposableEffect(sessionId) {
218+ container.setCurrentSession(sessionId)
219+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
222+ // Navigate away when the session is deleted via SSE so the user isn't left
223+ // on a zombie screen showing a conversation that no longer exists. Surface a
224+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
225+ // would be torn down before the user could read it, while a toast survives.
226+ // Covers both SSE-driven deletion (deleted on another device) and a user-
227+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
228+ // sets the same flag on success).
229+ val deletedContext = LocalContext.current
230+ LaunchedEffect(sessionDeleted) {
231+ if (sessionDeleted) {
232+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
237+ val snackbar = remember { SnackbarHostState() }
238+ val retryLabel = stringResource(R.string.retry)
239+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
240+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
241+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
242+ var showTitleMenu by rememberSaveable { mutableStateOf(false) }
243+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
244+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
245+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
246+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
247+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
248+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
249+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
250+ var showPalette by rememberSaveable { mutableStateOf(false) }
251+ // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
252+ // a confirmation dialog (from both the overflow menu and the command palette).
253+ var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
254+ var showInitConfirm by rememberSaveable { mutableStateOf(false) }
256+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
257+ // action list doesn't need a Composable context. Actions map to the same handlers the
258+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
259+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
260+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
261+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
262+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
263+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
264+ val paletteShellLabel = stringResource(R.string.run_shell_command)
265+ val paletteActions = remember(
266+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
267+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
270+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
271+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
272+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
273+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
274+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
275+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
279+ // Keep the screen awake while the agent is working in *this* session. The foreground
280+ // service that holds process priority during a run is managed app-wide off
281+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
282+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
283+ // SSE stream before the completion notification fires.
284+ val currentView = LocalView.current
285+ val appContext = LocalContext.current.applicationContext
286+ DisposableEffect(running) {
287+ currentView.keepScreenOn = running
288+ onDispose { currentView.keepScreenOn = false }
291+ LaunchedEffect(Unit) {
292+ vm.errorEvents.collect { event ->
293+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
294+ // message-load failure) would silently re-submit the last prompt on tap.
295+ val result = if (event.retryable) {
296+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
298+ snackbar.showSnackbar(event.message)
300+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
304+ // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
305+ // window on the container; show the snackbar over the conversation the user is viewing so
306+ // they can cancel without being navigated to the session list first. If the window expires
307+ // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
308+ val undoLabel = stringResource(R.string.undo)
309+ val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
310+ LaunchedEffect(Unit) {
311+ vm.deleteUndoEvents.collect {
313+ val dismisser = launch {
314+ delay(NetworkConfig.undoDeleteDelayMs)
315+ snackbar.currentSnackbarData?.dismiss()
317+ val result = snackbar.showSnackbar(
318+ message = sessionDeletedLabel,
319+ actionLabel = undoLabel,
320+ duration = SnackbarDuration.Indefinite,
323+ if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
328+ // --- Attachments, voice, and share-link plumbing ---
329+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
330+ val attachFailedMsg = stringResource(R.string.attachment_failed)
331+ val attachLimitMsg = stringResource(R.string.attachment_limit)
332+ val noCameraMsg = stringResource(R.string.no_camera_app)
333+ val noVoiceMsg = stringResource(R.string.no_voice_app)
334+ val voicePrompt = stringResource(R.string.voice_prompt)
335+ val linkCopiedMsg = stringResource(R.string.link_copied)
337+ // Count of picks currently being read + base64-encoded off the main thread, so the
338+ // composer can show a staging placeholder immediately (chips only materialize once done).
339+ var stagingCount by remember { mutableStateOf(0) }
341+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
342+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
343+ fun stageUris(uris: List<Uri>) {
344+ if (uris.isEmpty()) return
349+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
350+ snackbar.showSnackbar(attachLimitMsg)
353+ when (val result = uri.toAttachmentResult(appContext)) {
354+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
355+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
356+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
365+ val photoPicker = rememberLauncherForActivityResult(
366+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
367+ ) { uris -> stageUris(uris) }
369+ val filePicker = rememberLauncherForActivityResult(
370+ ActivityResultContracts.GetMultipleContents(),
371+ ) { uris -> stageUris(uris) }
373+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
374+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
375+ val cameraLauncher = rememberLauncherForActivityResult(
376+ ActivityResultContracts.TakePicture(),
378+ val uri = pendingCaptureUri
379+ pendingCaptureUri = null
380+ if (success && uri != null) stageUris(listOf(uri))
383+ val voiceLauncher = rememberLauncherForActivityResult(
384+ ActivityResultContracts.StartActivityForResult(),
386+ if (result.resultCode == Activity.RESULT_OK) {
387+ val spoken = result.data
388+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
390+ ?.takeIf { it.isNotBlank() }
391+ if (spoken != null) {
392+ // Append to the existing draft rather than replacing, so dictation adds to
393+ // whatever the user already typed.
394+ val current = vm.draft.value
395+ val combined = if (current.isBlank()) spoken else "$current $spoken"
396+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
401+ fun launchCamera() {
402+ val uri = newCameraCaptureUri(appContext)
404+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
407+ pendingCaptureUri = uri
408+ runCatching { cameraLauncher.launch(uri) }
409+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
413+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
414+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
415+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
417+ runCatching { voiceLauncher.launch(intent) }
418+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
421+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
422+ LaunchedEffect(Unit) {
423+ vm.shareLinkEvents.collect { url ->
424+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
425+ snackbar.showSnackbar(linkCopiedMsg)
429+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
430+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
431+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
432+ // a dropped branch-navigation event in the gap.
433+ val branchedMsg = stringResource(R.string.branch_created)
434+ LaunchedEffect(Unit) {
435+ vm.branchEvents.collect { newId ->
436+ showToast(shareContext, branchedMsg)
437+ onOpenSession?.invoke(newId)
441+ // Stage images shared into the app (via the system share sheet) as attachments.
442+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
443+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
444+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
445+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
446+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
447+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
448+ LaunchedEffect(pendingSharedMedia) {
449+ val shared = container.consumePendingSharedMedia()
450+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
454+ if (vm.send(draft)) {
455+ // TextHandleMove (a light tick) is semantically right for a send commit;
456+ // LongPress is reserved for long-press/swipe gestures.
457+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
461+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
464+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
465+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
466+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
467+ // typing (and the composer's own Enter-to-send handling) is untouched.
468+ modifier = Modifier.onPreviewKeyEvent { ev ->
469+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
471+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
472+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
473+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
474+ showStopConfirm = true; true
482+ val changeLabel = stringResource(R.string.change_model_agent)
483+ // The subtitle reads "model · agent", so tapping the title offers *both*
484+ // — a small menu picks which picker to open. Previously the tap went
485+ // straight to the model picker, leaving the agent changeable only via
486+ // the overflow menu despite the title implying otherwise.
489+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
490+ // node; the click label rides on `clickable` (onClickLabel) instead of
491+ // an explicit contentDescription, which would have SUPPRESSED the child
492+ // Texts and announced only "Change model and agent".
496+ onClickLabel = changeLabel,
497+ ) { showTitleMenu = true }
498+ .semantics(mergeDescendants = true) {},
499+ verticalAlignment = Alignment.CenterVertically,
501+ Column(modifier = Modifier.weight(1f, fill = false)) {
502+ // maxLines=1 + Ellipsis so a long session title can't wrap and
503+ // push the top bar to multiple lines, shifting the whole layout.
505+ sessionTitle ?: sessionLabel,
507+ overflow = TextOverflow.Ellipsis,
511+ style = MaterialTheme.typography.labelSmall,
512+ color = MaterialTheme.colorScheme.onSurfaceVariant,
514+ overflow = TextOverflow.Ellipsis,
517+ // Always show the affordance so the title reads as tappable even when
518+ // the model catalog failed to load (models empty). Without it the title
519+ // is indistinguishable from plain text and the pickers are effectively
520+ // undiscoverable — and the dropdown items already disable themselves
521+ // while a catalog is loading or unavailable.
523+ Icons.Filled.KeyboardArrowDown,
524+ contentDescription = null,
525+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
526+ modifier = Modifier.size(20.dp),
529+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
531+ text = { Text(stringResource(R.string.palette_switch_model)) },
532+ enabled = !modelsLoading || models.isNotEmpty(),
533+ onClick = { showTitleMenu = false; showModelPicker = true },
536+ text = { Text(stringResource(R.string.palette_choose_agent)) },
537+ enabled = !agentsLoading || agents.isNotEmpty(),
538+ onClick = { showTitleMenu = false; showAgentPicker = true },
544+ IconButton(onClick = {
545+ if (running) showExitConfirm = true else onBack()
547+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
551+ // At-a-glance run status in the top bar. When the user is scrolled
552+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
553+ // trailing "working…" row are off-screen, so a top-bar spinner is the
554+ // only signal the agent is still working.
556+ val workingLabel = stringResource(R.string.working)
557+ CircularProgressIndicator(
558+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
562+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
563+ // from REST. A recovery path when the stream silently drops and the
564+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
565+ // immediate tap feedback — the SSE reconnect may not visibly change
566+ // the connection state when already Connected, so without it the tap
567+ // appears to do nothing.
568+ val refreshLabel = stringResource(R.string.refresh)
570+ onClick = { vm.refreshMessages() },
571+ enabled = activeConnection != null && !refreshing,
574+ CircularProgressIndicator(
575+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
579+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
582+ // Overflow menu consolidates the less-frequent actions (share,
583+ // commands, agent, model, rename, delete) so the top bar stays
584+ // scannable on narrow phones — previously 5 icons crowded the bar
585+ // alongside the back button and tappable title. Catalog-loading
586+ // spinners stay inline (next to the overflow) so a load state is
587+ // visible without opening the menu.
588+ val moreLabel = stringResource(R.string.more)
589+ val loadingLabel = stringResource(R.string.loading)
590+ val shareLabel = stringResource(R.string.share_conversation)
591+ val commandsLabel = stringResource(R.string.commands)
592+ val renameLabel = stringResource(R.string.rename_session_chat)
593+ val deleteLabel = stringResource(R.string.delete_session_chat)
594+ val createShareLabel = stringResource(R.string.create_share_link)
595+ val copyShareLabel = stringResource(R.string.copy_share_link)
596+ val stopShareLabel = stringResource(R.string.stop_sharing)
597+ val summarizeLabel = stringResource(R.string.summarize_conversation)
598+ val initLabel = stringResource(R.string.generate_agents_md)
599+ val shellLabel = stringResource(R.string.run_shell_command)
601+ IconButton(onClick = { showOverflowMenu = true }) {
602+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
605+ expanded = showOverflowMenu,
606+ onDismissRequest = { showOverflowMenu = false },
609+ text = { Text(shareLabel) },
610+ enabled = hasMessages,
612+ showOverflowMenu = false
614+ val md = withContext(Dispatchers.Default) {
615+ buildConversationMarkdown(vm.messages.value, sessionTitle)
617+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
618+ type = "text/markdown"
619+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
620+ putExtra(android.content.Intent.EXTRA_TEXT, md)
622+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
623+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
628+ text = { Text(commandsLabel) },
629+ enabled = !commandsLoading || commands.isNotEmpty(),
630+ onClick = { showOverflowMenu = false; showCommandPicker = true },
632+ androidx.compose.material3.HorizontalDivider()
633+ // Session sharing: create a public link, copy an existing one, or revoke it.
634+ if (shareUrl == null) {
636+ text = { Text(createShareLabel) },
637+ enabled = hasMessages,
638+ onClick = { showOverflowMenu = false; vm.shareSession() },
642+ text = { Text(copyShareLabel) },
644+ showOverflowMenu = false
646+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
647+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
652+ text = { Text(stopShareLabel) },
653+ onClick = { showOverflowMenu = false; vm.unshareSession() },
657+ text = { Text(summarizeLabel) },
658+ enabled = hasMessages && !running,
659+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
662+ text = { Text(initLabel) },
664+ onClick = { showOverflowMenu = false; showInitConfirm = true },
667+ text = { Text(shellLabel) },
669+ onClick = { showOverflowMenu = false; showShellDialog = true },
671+ androidx.compose.material3.HorizontalDivider()
673+ text = { Text(renameLabel) },
674+ onClick = { showOverflowMenu = false; showRenameDialog = true },
677+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
678+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
681+ // While a catalog is initially loading (empty list + loading flag),
682+ // show a tiny inline spinner beside the overflow so the user can see
683+ // a load is in progress without opening the menu. Once loaded the
684+ // spinner disappears; the menu items are always enabled (tapping a
685+ // picker with no items shows the "no models/agents/commands" state).
686+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
687+ (agentsLoading && agents.isEmpty()) ||
688+ (modelsLoading && models.isEmpty())
689+ if (catalogLoading) {
690+ CircularProgressIndicator(
692+ .align(Alignment.TopEnd)
694+ .semantics { contentDescription = loadingLabel },
702+ snackbarHost = { SnackbarHost(snackbar) },
704+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
705+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
706+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
707+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
709+ // Pinned above the composer so the agent's plan and progress stay visible
710+ // while scrolled up mid-run; renders nothing when there's no plan.
711+ TodoPlanBar(todoPlan)
712+ AnimatedVisibility(visible = reverted) {
713+ RevertBanner(onUndo = { vm.unrevert() })
715+ AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
717+ count = queuedOffline.size,
718+ sending = outboxSending,
719+ onFlush = { vm.flushQueued() },
720+ onDiscard = { vm.discardAllQueued() },
725+ onValueChange = vm::updateDraft,
727+ aborting = aborting,
728+ enabled = activeConnection != null,
729+ sendOnEnter = sendOnEnter,
731+ onAbort = { showStopConfirm = true },
732+ queuedFollowUp = queuedFollowUp,
733+ onQueueFollowUp = vm::queueFollowUp,
734+ onCancelQueue = { vm.queueFollowUp("") },
735+ focusRequester = inputFocusRequester,
736+ attachments = attachments,
737+ staging = stagingCount > 0,
738+ onRemoveAttachment = vm::removeAttachment,
741+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
744+ onPickFile = { filePicker.launch("*/*") },
745+ onCamera = { launchCamera() },
746+ onVoice = { launchVoice() },
751+ // Collect messages inside the content lambda so streaming token updates
752+ // recompose only this subtree, not the top bar / input bar / 20+ other
753+ // state reads in the ChatScreen body.
754+ val messages by vm.messages.collectAsStateWithLifecycle()
755+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
756+ val listState = rememberLazyListState()
757+ val contentScope = rememberCoroutineScope()
758+ val timeTick = rememberRelativeTimeTick()
759+ // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
760+ // chat affordance for reading while the IME is open. Watching isScrollInProgress via
761+ // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
762+ val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
763+ androidx.compose.runtime.LaunchedEffect(listState) {
764+ androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
765+ .distinctUntilChanged()
766+ .collect { scrolling -> if (scrolling) keyboardController?.hide() }
767+ } // Group messages by day and interleave date separators so a long conversation
768+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
769+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
770+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
771+ // the same list the LazyColumn renders (separators shift the indices vs. the
772+ // raw messages list, so scroll targets must be in listItems space).
773+ val todayLabel = stringResource(R.string.today)
774+ val yesterdayLabel = stringResource(R.string.yesterday)
775+ val listItems = remember(messages, todayLabel, yesterdayLabel) {
776+ buildMessageListItems(messages, todayLabel, yesterdayLabel)
778+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
779+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
780+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
781+ // would capture the first composition's list — which is empty, since `messages`
782+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
783+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
784+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
785+ // whose value tracks the latest list.
786+ val currentListItems by rememberUpdatedState(listItems)
788+ // New-content signal for the jump-to-latest FAB: set when content grows while the user
789+ // is scrolled away from the bottom, cleared once they return (see the collector below).
790+ var hasNewContent by remember { mutableStateOf(false) }
792+ val isPinnedToBottom by remember {
794+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
795+ // When a run is active, the LazyColumn has one trailing "__typing"
796+ // item after the last list item. Account for it so "pinned to bottom"
797+ // includes the working indicator — otherwise the pin check targets
798+ // listItems.lastIndex, the typing row sits just below the viewport,
799+ // and the user never sees the progress indicator even when pinned.
800+ val items = currentListItems
801+ val effectiveLast = if (running) items.size else items.lastIndex
802+ lastVisible >= effectiveLast || items.isEmpty()
806+ // Jump to the newest message once, when the conversation first loads. Guarded by a
807+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
808+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
809+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
810+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
811+ LaunchedEffect(listItems.isNotEmpty()) {
812+ if (listItems.isNotEmpty() && !didInitialScroll) {
813+ // When a run is active the LazyColumn has a trailing "__typing" row at
814+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
815+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
816+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
817+ didInitialScroll = true
821+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
822+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
823+ // isPinnedToBottom check flips to false the instant you send — freezing
824+ // auto-scroll. If the user was pinned to the last item just before the run
825+ // began, bring the typing row into view so the pin (and streaming follow) is
826+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
827+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
828+ LaunchedEffect(running) {
829+ if (running && listItems.isNotEmpty()) {
830+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
831+ if (lastVisible >= listItems.lastIndex) {
832+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
837+ LaunchedEffect(Unit) {
841+ // Track list size + the streaming length of the last part so we auto-scroll
842+ // as content arrives, plus the pinned flag. A small data class with primitive
843+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
844+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
845+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
846+ // and tool output — not just TextPart — keeps a pinned view following a long
847+ // reasoning/tool block while it streams (previously it stalled at 0).
848+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
849+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
850+ }.collect { signal ->
851+ if (signal.pinned) {
852+ // Back at the bottom: clear the new-content badge.
853+ hasNewContent = false
854+ if (signal.size > 0) {
855+ // Scroll to the effective last index, including the trailing
856+ // "__typing" row when a run is active so the working indicator
857+ // is brought into view (not just the last message).
858+ val items = currentListItems
859+ val target = if (running) items.size else items.lastIndex
860+ listState.scrollToItem(target)
862+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
863+ // Content arrived while scrolled up — badge the jump-to-latest FAB.
864+ hasNewContent = true
866+ prevSize = signal.size
867+ prevLen = signal.lastTextLength
871+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
872+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
873+ // content padding accounts for the bottomBar's raised height, so the message
874+ // list is already above the keyboard. Adding imePadding here would double-apply
875+ // the IME inset and push messages too far up.
876+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
877+ if (activeConnection == null) {
879+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
880+ horizontalAlignment = Alignment.CenterHorizontally,
883+ stringResource(R.string.not_connected),
884+ color = MaterialTheme.colorScheme.error,
886+ Spacer(Modifier.size(12.dp))
887+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
889+ CircularProgressIndicator(
890+ Modifier.size(20.dp),
891+ color = MaterialTheme.colorScheme.onPrimary,
895+ Text(stringResource(R.string.reconnect))
900+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
901+ // Measure the banner's actual height instead of hardcoding 44dp. At large
902+ // accessibility font scales the banner's labelMedium text + spinner + Retry
903+ // button exceed 44dp, so a fixed inset lets the first message hide behind it
904+ // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
905+ // fires while the banner is composed (visible), so gate the inset on
906+ // bannerVisible and fall back to 44dp until the first measurement arrives.
907+ var bannerHeightPx by remember { mutableIntStateOf(0) }
908+ val density = LocalDensity.current
909+ val topPad = if (bannerVisible) {
910+ if (bannerHeightPx > 0) {
911+ with(density) { bannerHeightPx.toDp() } + 4.dp
919+ state = connectionState,
920+ modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
921+ isOnline = isOnline,
922+ // On a hard failure, retry by forcing an SSE reconnect (which
923+ // re-seeds from REST). refreshMessages is the right recovery path
924+ // when the connection is present but the stream died; reconnect()
925+ // is the path when the whole connection is gone (handled by the
926+ // separate "Not connected" state below).
927+ onRetry = { vm.refreshMessages() },
929+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
930+ // recovery is a swipe away everywhere — not just when the message list is
931+ // populated. Previously PTR was only around the populated list, leaving the
932+ // error/loading states reachable only via a button tap.
934+ isRefreshing = refreshing,
935+ onRefresh = { vm.refreshMessages() },
936+ // Cap width and center on large screens for readability — full-width
937+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
938+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
939+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
941+ // Reserve top space when the banner is visible so it doesn't overlap the
942+ // first message / state content. (topPad computed above.)
943+ if (loading && messages.isEmpty()) {
944+ val loadingLabel = stringResource(R.string.loading)
945+ // Attach the a11y label directly to the spinner (a detached zero-size Box
946+ // isn't reliably focused/announced by TalkBack) and show a visible label so
947+ // sighted users get "Loading…" rather than a bare spinner.
949+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
950+ horizontalAlignment = Alignment.CenterHorizontally,
952+ CircularProgressIndicator(
953+ Modifier.semantics { contentDescription = loadingLabel },
956+ Spacer(Modifier.size(8.dp))
959+ style = MaterialTheme.typography.labelMedium,
960+ color = MaterialTheme.colorScheme.onSurfaceVariant,
963+ } else if (loadError && messages.isEmpty()) {
964+ // A failed load with nothing to show. Distinct from the empty
965+ // conversation state below — the conversation isn't empty, it
966+ // failed to load, and offering "Start a conversation" here is
967+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
969+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
970+ horizontalAlignment = Alignment.CenterHorizontally,
973+ stringResource(R.string.load_messages_failed),
974+ color = MaterialTheme.colorScheme.error,
976+ Spacer(Modifier.size(12.dp))
977+ Button(onClick = { vm.refreshMessages() }) {
978+ Text(stringResource(R.string.retry))
981+ } else if (messages.isEmpty() && running) {
982+ // A run just started but no parts have arrived yet — the empty
983+ // list with only the trailing "working…" row looks broken, so
984+ // surface a clear starting state until the first part streams in.
985+ val workingText = stringResource(R.string.working)
987+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
988+ horizontalAlignment = Alignment.CenterHorizontally,
990+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
991+ Spacer(Modifier.size(12.dp))
992+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
994+ } else if (messages.isEmpty()) {
998+ // Focus the input so the user can edit the suggestion before
999+ // sending, instead of having to manually tap the field.
1000+ runCatching { inputFocusRequester.requestFocus() }
1002+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1005+ val lastMessageId = messages.lastOrNull()?.info?.id
1006+ // Text-to-speech for reading assistant replies aloud; shuts down when the
1007+ // message list leaves composition.
1008+ val tts = rememberTtsController()
1009+ val speakingMessageId by tts.speakingId
1012+ modifier = Modifier.fillMaxSize(),
1013+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
1014+ // never floats over the last message. Top padding grows when the
1015+ // connection banner is visible so it doesn't overlap the first message.
1016+ contentPadding = PaddingValues(
1020+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1022+ verticalArrangement = Arrangement.spacedBy(16.dp),
1027+ contentType = { it.contentType },
1029+ // Default placement animation so inserted/moved rows glide in. Kept to the
1030+ // default (no heavy fade spec) so a streaming message growing in place
1031+ // doesn't animate on every token.
1032+ Box(Modifier.animateItem()) {
1034+ is MessageListItem.Separator -> DateSeparator(item.label)
1035+ is MessageListItem.Message -> {
1036+ val message = item.message
1037+ // Only the last (streaming) message needs isRunning — it drives the
1038+ // reasoning-block spinner. Passing the live flag to every bubble
1039+ // makes all visible messages recompose whenever a run starts or stops.
1040+ val modelLabel = remember(message.info, models) {
1041+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1042+ ?.let { resolveModelLabel(it, models) }
1044+ // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1045+ // image/code-only messages, which then opt out of the swipe gesture.
1046+ val quoteText = remember(message.parts) {
1048+ .filterIsInstance<TextPart>()
1049+ .joinToString("\n\n") { it.text }
1051+ .takeIf { it.isNotEmpty() }
1053+ // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1054+ // snapping back (the message isn't dismissed — the quote fills the composer).
1055+ // Only enabled when there's text to quote, so non-text messages don't
1056+ // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1057+ val swipeState = rememberSwipeToDismissBoxState(
1058+ confirmValueChange = { value ->
1059+ if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1060+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1061+ vm.quoteReply(quoteText)
1062+ runCatching { inputFocusRequester.requestFocus() }
1068+ state = swipeState,
1069+ enableDismissFromEndToStart = false,
1070+ enableDismissFromStartToEnd = quoteText != null,
1071+ backgroundContent = {
1073+ Modifier.fillMaxSize().padding(horizontal = 16.dp),
1074+ contentAlignment = Alignment.CenterStart,
1077+ Icons.AutoMirrored.Filled.Reply,
1078+ contentDescription = null,
1079+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1086+ isRunning = running && message.info.id == lastMessageId,
1087+ imageContext = imageContext,
1088+ modelLabel = modelLabel,
1089+ onOpenFile = onOpenFile,
1090+ onRevert = { vm.revertTo(message.info.id) },
1092+ // editMessage reverts to before this message (hiding it and
1093+ // everything after); the revert banner surfaces the rewind
1094+ // with an Undo. Focus + scroll the composer into view like the
1095+ // Quote action so the prefilled draft isn't off-screen.
1096+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1097+ vm.editMessage(message.info.id, text)
1098+ runCatching { inputFocusRequester.requestFocus() }
1099+ contentScope.launch {
1100+ runCatchingCancellable {
1101+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1105+ onSpeak = { text -> tts.toggle(message.info.id, text) },
1106+ isSpeaking = message.info.id == speakingMessageId,
1107+ onQuote = { text ->
1108+ vm.quoteReply(text)
1109+ runCatching { inputFocusRequester.requestFocus() }
1111+ onBranch = { text -> vm.branchFrom(text) },
1112+ sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1113+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1114+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1116+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1117+ onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1119+ { vm.retryOptimisticMessage(message.info.id) }
1124+ onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1126+ { vm.dismissOptimistic(message.info.id) }
1138+ item(key = "__typing") {
1139+ val workingText = stringResource(R.string.working)
1141+ verticalAlignment = Alignment.CenterVertically,
1142+ modifier = Modifier.semantics {
1143+ contentDescription = workingText
1146+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1147+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1154+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1155+ AnimatedVisibility(
1156+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1157+ modifier = Modifier.align(Alignment.BottomEnd),
1159+ // Badge the FAB when new content arrived while the user was scrolled up, so
1160+ // they know there's something new to jump to (cleared once back at bottom).
1163+ if (hasNewContent) {
1164+ val newContentLabel = stringResource(R.string.new_messages)
1165+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1168+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1170+ ExtendedFloatingActionButton(
1172+ hasNewContent = false
1173+ if (listItems.isNotEmpty()) {
1174+ // Scroll to the effective last index, including the
1175+ // trailing "__typing" row when a run is active.
1176+ val target = if (running) listItems.size else listItems.lastIndex
1177+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1180+ // contentDescription null: the visible "Latest" text already labels
1181+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1182+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1183+ text = { Text(stringResource(R.string.latest)) },
1187+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1188+ // user has scrolled down past the first few messages. Symmetric to the
1189+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1190+ val scrolledDown by remember {
1191+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1193+ AnimatedVisibility(
1194+ visible = scrolledDown && listItems.size > 4,
1195+ modifier = Modifier.align(Alignment.BottomStart),
1197+ SmallFloatingActionButton(
1199+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1201+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1204+ Icons.Filled.KeyboardArrowUp,
1205+ contentDescription = stringResource(R.string.scroll_to_top),
1214+ if (showExitConfirm) {
1216+ onDismissRequest = { showExitConfirm = false },
1217+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1218+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1220+ TextButton(onClick = {
1221+ showExitConfirm = false
1222+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1225+ }) { Text(stringResource(R.string.stop_and_exit)) }
1228+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1233+ if (showStopConfirm) {
1235+ onDismissRequest = { showStopConfirm = false },
1236+ title = { Text(stringResource(R.string.stop_run_title)) },
1237+ text = { Text(stringResource(R.string.stop_run_text)) },
1239+ TextButton(onClick = {
1240+ showStopConfirm = false
1241+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1243+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1246+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1251+ if (showSummarizeConfirm) {
1253+ onDismissRequest = { showSummarizeConfirm = false },
1254+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
1255+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
1257+ TextButton(onClick = {
1258+ showSummarizeConfirm = false
1260+ }) { Text(stringResource(R.string.action_continue)) }
1263+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1268+ if (showInitConfirm) {
1270+ onDismissRequest = { showInitConfirm = false },
1271+ title = { Text(stringResource(R.string.init_confirm_title)) },
1272+ text = { Text(stringResource(R.string.init_confirm_text)) },
1274+ TextButton(onClick = {
1275+ showInitConfirm = false
1277+ }) { Text(stringResource(R.string.action_continue)) }
1280+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1285+ if (showRenameDialog) {
1286+ RenameSessionChatDialog(
1287+ initialTitle = sessionTitle ?: "",
1288+ onDismiss = { showRenameDialog = false },
1289+ onConfirm = { newName ->
1290+ showRenameDialog = false
1291+ vm.renameSession(newName)
1296+ if (showDeleteDialog) {
1298+ onDismissRequest = { showDeleteDialog = false },
1299+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1300+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1302+ TextButton(onClick = {
1303+ showDeleteDialog = false
1304+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1306+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1309+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1314+ if (showShellDialog) {
1315+ ShellCommandDialog(
1316+ onDismiss = { showShellDialog = false },
1318+ showShellDialog = false
1324+ if (showModelPicker) {
1327+ selected = selectedModel,
1328+ loading = modelsLoading,
1329+ error = modelsError,
1330+ onSelect = { vm.selectModel(it) },
1331+ onRetry = { vm.reloadModels() },
1332+ onDismiss = { showModelPicker = false },
1336+ if (showAgentPicker) {
1339+ selected = selectedAgent,
1340+ loading = agentsLoading,
1341+ error = agentsError,
1342+ onSelect = { vm.selectAgent(it?.name) },
1343+ onRetry = { vm.reloadAgents() },
1344+ onDismiss = { showAgentPicker = false },
1348+ if (showCommandPicker) {
1349+ CommandPickerSheet(
1350+ commands = commands,
1351+ loading = commandsLoading,
1352+ error = commandsError,
1353+ onSelect = { vm.runCommand(it) },
1354+ onRetry = { vm.reloadCommands() },
1355+ onDismiss = { showCommandPicker = false },
1359+ pendingPermission?.let { permission ->
1361+ permission = permission,
1362+ position = permissionProgress.position,
1363+ total = permissionProgress.total,
1364+ onRespond = { response -> vm.respondPermission(permission, response) },
1369+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1374+private fun ChatInputBar(
1376+ onValueChange: (String) -> Unit,
1380+ sendOnEnter: Boolean,
1381+ onSend: () -> Unit,
1382+ onAbort: () -> Unit,
1383+ queuedFollowUp: String?,
1384+ onQueueFollowUp: (String) -> Unit,
1385+ onCancelQueue: () -> Unit,
1386+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1387+ attachments: List<PendingAttachment>,
1389+ onRemoveAttachment: (String) -> Unit,
1390+ onPickPhoto: () -> Unit,
1391+ onPickFile: () -> Unit,
1392+ onCamera: () -> Unit,
1393+ onVoice: () -> Unit,
1395+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1396+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1397+ // Full-screen editor state: opened when the user wants more space for a long prompt.
1398+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1399+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1400+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1401+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1402+ // user sees their message will be sent when the run finishes, and can cancel.
1403+ if (queuedFollowUp != null) {
1405+ modifier = Modifier
1407+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1408+ verticalAlignment = Alignment.CenterVertically,
1410+ Column(modifier = Modifier.weight(1f)) {
1412+ stringResource(R.string.queued),
1413+ style = MaterialTheme.typography.labelSmall,
1414+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1418+ style = MaterialTheme.typography.bodySmall,
1419+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1421+ overflow = TextOverflow.Ellipsis,
1424+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1425+ Text(stringResource(R.string.cancel))
1429+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1430+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1432+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1433+ verticalAlignment = Alignment.Bottom,
1435+ // Attach menu: photo picker, camera, or any file.
1436+ var showAttachMenu by remember { mutableStateOf(false) }
1438+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1439+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1441+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1443+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1444+ text = { Text(stringResource(R.string.attach_photo)) },
1445+ onClick = { showAttachMenu = false; onPickPhoto() },
1448+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1449+ text = { Text(stringResource(R.string.attach_camera)) },
1450+ onClick = { showAttachMenu = false; onCamera() },
1453+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1454+ text = { Text(stringResource(R.string.attach_file)) },
1455+ onClick = { showAttachMenu = false; onPickFile() },
1459+ // Voice dictation: appends recognized speech to the draft.
1460+ IconButton(onClick = onVoice, enabled = enabled) {
1461+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1463+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1464+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1465+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1469+ onValueChange = { v ->
1470+ // Cap input length so a huge paste can't stall the UI. Shares are
1471+ // capped separately in MainActivity; this guards typed/pasted drafts.
1472+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1474+ modifier = Modifier
1476+ .focusRequester(focusRequester)
1477+ .testTag("chat_input")
1478+ .onPreviewKeyEvent { event ->
1479+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1480+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1481+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1482+ val send = enterShouldSend(
1484+ hasContent = hasContent,
1485+ sendOnEnter = sendOnEnter,
1486+ shift = event.isShiftPressed,
1487+ ctrl = event.isCtrlPressed,
1490+ if (running) onQueueFollowUp(value) else onSend()
1496+ // While a run is active a typed message only queues (sends after the run), so
1497+ // the placeholder says so instead of the plain "Message…".
1499+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1503+ // Show a "N / max" countdown once the draft crosses a high fraction of
1504+ // the cap, so the user knows a paste is about to be truncated instead
1505+ // of being silently cut off. Hidden for normal short prompts to avoid
1506+ // clutter under a typical one-line message.
1508+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1509+ if (value.length >= threshold) {
1512+ R.string.draft_chars_remaining,
1513+ NetworkConfig.maxDraftLengthChars - value.length,
1514+ NetworkConfig.maxDraftLengthChars,
1516+ style = MaterialTheme.typography.labelSmall,
1517+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1518+ else MaterialTheme.colorScheme.onSurfaceVariant,
1522+ keyboardOptions = KeyboardOptions(
1523+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
1524+ // keyboard shows a send key — matching the setting's intent and
1525+ // giving touch-only users a keyboard send affordance. When off,
1526+ // ImeAction.Default keeps the enter/newline key for multi-line input.
1527+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1528+ capitalization = KeyboardCapitalization.Sentences,
1530+ keyboardActions = KeyboardActions(
1532+ if (enabled && hasContent) onSend()
1536+ ComposerTrailingButton(
1538+ aborting = aborting,
1539+ canSend = enabled && hasContent,
1540+ canQueue = enabled && value.isNotBlank(),
1543+ onQueue = { onQueueFollowUp(value) },
1547+ if (showFullScreenEditor) {
1550+ onValueChange = onValueChange,
1551+ onDismiss = { showFullScreenEditor = false },
1552+ onSend = { showFullScreenEditor = false; onSend() },
1553+ canSend = enabled && hasContent,
1559+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1560+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1561+@OptIn(ExperimentalMaterial3Api::class)
1563+private fun FullScreenEditor(
1565+ onValueChange: (String) -> Unit,
1566+ onDismiss: () -> Unit,
1567+ onSend: () -> Unit,
1570+ androidx.compose.ui.window.Dialog(
1571+ onDismissRequest = onDismiss,
1572+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1576+ androidx.compose.material3.TopAppBar(
1577+ title = { Text(stringResource(R.string.message_placeholder)) },
1579+ androidx.compose.material3.TextButton(onClick = onDismiss) {
1580+ Text(stringResource(R.string.collapse_editor))
1586+ Surface(tonalElevation = 3.dp) {
1588+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1589+ horizontalArrangement = Arrangement.End,
1591+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1592+ Text(stringResource(R.string.send))
1600+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1601+ modifier = Modifier.fillMaxSize().padding(padding),
1602+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
1603+ maxLines = Int.MAX_VALUE,
1604+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1610+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1611+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1612+private fun enterShouldSend(
1614+ hasContent: Boolean,
1615+ sendOnEnter: Boolean,
1619+ !enabled || !hasContent -> false
1620+ sendOnEnter -> !shift
1624+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1625+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1626+ * [ChatInputBar] stays under the complexity threshold. */
1628+private fun ComposerTrailingButton(
1633+ onSend: () -> Unit,
1634+ onAbort: () -> Unit,
1635+ onQueue: () -> Unit,
1638+ Row(verticalAlignment = Alignment.CenterVertically) {
1639+ // While a run is active the trailing action is Stop, so the only send affordance is
1640+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1641+ // That leaves a touch-only user with the setting off no way to queue a follow-up
1642+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1643+ // there's typed TEXT so queuing is always reachable, without changing the user's
1644+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1645+ // canSend, which is also true for an attachment-only composer — because queuing "" just
1646+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1647+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1651+ modifier = Modifier.testTag("queue_button"),
1653+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1654+ // icon (which can be read as "snooze" or "later"), and isn't confused with
1655+ // the Send action sitting right beside the Stop button.
1657+ Icons.AutoMirrored.Filled.PlaylistAdd,
1658+ contentDescription = stringResource(R.string.queue_followup),
1662+ // Show a spinner while the abort REST call is in flight so the user sees the stop
1663+ // was sent, and disable to prevent a double-tap.
1666+ enabled = !aborting,
1667+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1670+ val stopLabel = stringResource(R.string.stop)
1671+ CircularProgressIndicator(
1672+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1673+ strokeWidth = 2.dp,
1676+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1684+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1686+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1691+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1693+private fun EmptyConversation(
1694+ onSuggestion: (String) -> Unit,
1695+ modifier: Modifier = Modifier,
1697+ // A few example prompts so a first-time user has a one-tap path to their first
1698+ // message instead of staring at a blank input. Tapping a chip fills the draft
1699+ // (without sending) so the user can edit it before sending.
1700+ val suggestions = remember {
1702+ R.string.empty_chat_suggest_1,
1703+ R.string.empty_chat_suggest_2,
1704+ R.string.empty_chat_suggest_3,
1708+ modifier = modifier.padding(32.dp),
1709+ horizontalAlignment = Alignment.CenterHorizontally,
1712+ Icons.Filled.AutoAwesome,
1713+ contentDescription = null,
1714+ modifier = Modifier.size(48.dp),
1715+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1717+ Spacer(Modifier.size(16.dp))
1719+ stringResource(R.string.empty_chat_title),
1720+ style = MaterialTheme.typography.titleMedium,
1722+ Spacer(Modifier.size(8.dp))
1724+ stringResource(R.string.empty_chat_hint),
1725+ style = MaterialTheme.typography.bodyMedium,
1726+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1728+ Spacer(Modifier.size(20.dp))
1729+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1730+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
1732+ modifier = Modifier.fillMaxWidth(),
1733+ horizontalArrangement = Arrangement.spacedBy(8.dp),
1734+ verticalArrangement = Arrangement.spacedBy(8.dp),
1736+ suggestions.forEach { resId ->
1737+ val text = stringResource(resId)
1738+ androidx.compose.material3.AssistChip(
1739+ onClick = { onSuggestion(text) },
1740+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1747+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1749+private fun RevertBanner(onUndo: () -> Unit) {
1751+ color = MaterialTheme.colorScheme.tertiaryContainer,
1752+ tonalElevation = 2.dp,
1753+ modifier = Modifier.fillMaxWidth(),
1756+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1757+ verticalAlignment = Alignment.CenterVertically,
1758+ horizontalArrangement = Arrangement.SpaceBetween,
1760+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1762+ Icons.Filled.Restore,
1763+ contentDescription = null,
1764+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
1765+ modifier = Modifier.size(18.dp),
1768+ stringResource(R.string.reverted_banner),
1769+ style = MaterialTheme.typography.bodySmall,
1770+ color = MaterialTheme.colorScheme.onTertiaryContainer,
1771+ modifier = Modifier.padding(start = 8.dp),
1774+ TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1779+/** A banner shown while messages composed offline are queued in the outbox, with a
1780+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1782+private fun OutboxBanner(
1785+ onFlush: () -> Unit,
1786+ onDiscard: () -> Unit,
1789+ color = MaterialTheme.colorScheme.secondaryContainer,
1790+ tonalElevation = 2.dp,
1791+ modifier = Modifier.fillMaxWidth(),
1794+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1795+ verticalAlignment = Alignment.CenterVertically,
1796+ horizontalArrangement = Arrangement.SpaceBetween,
1798+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1800+ CircularProgressIndicator(
1801+ Modifier.size(16.dp),
1802+ strokeWidth = 2.dp,
1803+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1805+ Spacer(Modifier.size(8.dp))
1809+ stringResource(R.string.outbox_sending)
1811+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1812+ stringResource(res, count)
1814+ style = MaterialTheme.typography.bodySmall,
1815+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1819+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1820+ TextButton(onClick = onDiscard) {
1821+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1828+/** Prompt for a one-off shell command to run in the session's worktree. */
1830+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1831+ var command by rememberSaveable { mutableStateOf("") }
1833+ onDismissRequest = onDismiss,
1834+ title = { Text(stringResource(R.string.run_shell_command)) },
1838+ onValueChange = { command = it },
1839+ modifier = Modifier.fillMaxWidth(),
1840+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1841+ label = { Text(stringResource(R.string.shell_command_label)) },
1843+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1844+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1849+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1850+ enabled = command.isNotBlank(),
1851+ ) { Text(stringResource(R.string.run)) }
1853+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1858+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1859+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1860+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
1862+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1864+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1865+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1866+ * streaming, not just plain assistant text. O(1). */
1867+private fun streamingContentLength(part: Part?): Int = when (part) {
1868+ is TextPart -> part.text.length
1869+ is ReasoningPart -> part.text.length
1870+ is ToolPart -> when (val st = part.state) {
1871+ is ToolCompleted -> st.output?.length ?: 0
1872+ is ToolError -> st.error?.length ?: 0
1873+ is ToolRunning -> st.title?.length ?: 0
1879+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1880+ * dialog but lives in the chat screen so the user can rename without backing out to
1881+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
1883+private fun RenameSessionChatDialog(
1884+ initialTitle: String,
1885+ onDismiss: () -> Unit,
1886+ onConfirm: (String) -> Unit,
1888+ // Seed the field once (no key input) so a later external title change — e.g. opencode
1889+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1890+ // doesn't re-initialize the box and discard the user's in-progress edit.
1891+ var title by rememberSaveable { mutableStateOf(initialTitle) }
1893+ onDismissRequest = onDismiss,
1894+ title = { Text(stringResource(R.string.rename_session_chat)) },
1898+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1899+ modifier = Modifier.fillMaxWidth(),
1900+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
1901+ label = { Text(stringResource(R.string.rename_session_chat)) },
1903+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1904+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1908+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1909+ Text(stringResource(R.string.save))
1913+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1919+ * A single item in the chat message list — either a [Message] bubble or a day
1920+ * [Separator] inserted before the first message of a new day. The separator shifts
1921+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1922+ * the [List] of these items (not `messages.size`/`lastIndex`).
1924+private sealed interface MessageListItem {
1926+ val contentType: Any
1928+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1929+ override val contentType: Any get() = message.info::class
1932+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1933+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1934+ // can share a label (e.g. an untimestamped message — empty label — between two
1935+ // same-day messages, or two untimestamped groups), and a label-only key would
1936+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1937+ // stable for a given message ordering so slots aren't needlessly recreated.
1938+ override val key: Any get() = "sep_${ordinal}_$label"
1939+ // Separators share a contentType so the LazyColumn can recycle their slots.
1940+ override val contentType: Any get() = "separator"
1945+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1946+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1947+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1948+ * Messages with no timestamp are grouped under an empty-label separator only if they
1949+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
1951+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1952+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1953+ * labels; older days fall back to a locale-stable medium-date format.
1955+private fun buildMessageListItems(
1956+ messages: List<MessageWithParts>,
1957+ todayLabel: String,
1958+ yesterdayLabel: String,
1959+): List<MessageListItem> {
1960+ if (messages.isEmpty()) return emptyList()
1961+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1962+ val dateFmt = mediumDateFormat()
1963+ val result = ArrayList<MessageListItem>(messages.size + 4)
1964+ val seenKeys = HashSet<String>(messages.size * 2)
1965+ var lastDayKey: String? = null
1967+ var emptyIdOrdinal = 0
1969+ for (message in messages) {
1970+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1971+ val dayKey = ts?.let { dayKey(it) } ?: ""
1972+ // Emit a separator before the very first message (so a leading un-timestamped message
1973+ // still gets the first divider, empty label and all), and thereafter only when crossing
1974+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1975+ // neither emits its own separator nor resets the day — otherwise a following same-day
1976+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1977+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1978+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1980+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
1982+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1983+ // empty id — and the reducer intentionally keeps several such messages as distinct
1984+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
1985+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1986+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1987+ if (!seenKeys.add(key)) {
1989+ while (!seenKeys.add("$key#$suffix")) suffix++
1990+ key = "$key#$suffix"
1992+ result.add(MessageListItem.Message(message, key))
1998+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2000+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2001+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
2002+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2003+ * every message on every token. Message timestamps are immutable once assigned, so we
2004+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2005+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2006+ * thread during composition, so the coarse lock is uncontended.
2008+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2009+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2012+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2013+ dayKeyCache.getOrPut(epochMillis) {
2014+ java.time.Instant.ofEpochMilli(epochMillis)
2015+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2019+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2020+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2021+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2022+private var cachedDateFmt: java.text.DateFormat? = null
2023+private var cachedDateFmtLocale: java.util.Locale? = null
2025+private fun mediumDateFormat(): java.text.DateFormat {
2026+ val locale = java.util.Locale.getDefault()
2027+ val existing = cachedDateFmt
2028+ if (existing != null && cachedDateFmtLocale == locale) return existing
2029+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2031+ cachedDateFmtLocale = locale
2036+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2037+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2038+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2041+private fun dayLabel(
2044+ today: java.time.LocalDate,
2045+ todayLabel: String,
2046+ yesterdayLabel: String,
2047+ dateFmt: java.text.DateFormat,
2049+ if (dayKey.isEmpty()) return ""
2050+ val epochDay = dayKey.toLongOrNull() ?: return ""
2051+ val date = java.time.LocalDate.ofEpochDay(epochDay)
2053+ date == today -> todayLabel
2054+ date == today.minusDays(1) -> yesterdayLabel
2055+ else -> dateFmt.format(java.util.Date(ts))
2060+ * A centered day divider in the message list. Renders nothing for an empty label
2061+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2064+private fun DateSeparator(label: String) {
2065+ if (label.isBlank()) return
2067+ modifier = Modifier.fillMaxWidth(),
2068+ horizontalArrangement = Arrangement.Center,
2071+ color = MaterialTheme.colorScheme.surfaceVariant,
2072+ shape = MaterialTheme.shapes.small,
2076+ style = MaterialTheme.typography.labelSmall,
2077+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2078+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),