@@ -0,0 +1,2100 @@
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.LocalReducedMotion
149+import soy.iko.opencode.ui.components.copyToClipboard
150+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
151+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
152+import soy.iko.opencode.ui.components.rememberVisibilityTransitions
153+import soy.iko.opencode.ui.components.showToast
154+import soy.iko.opencode.ui.components.toImageContext
155+import soy.iko.opencode.ui.vmFactory
156+import soy.iko.opencode.util.runCatchingCancellable
158+@OptIn(ExperimentalMaterial3Api::class)
161+ container: AppContainer,
164+ onOpenFile: ((String) -> Unit)? = null,
165+ onOpenSession: ((String) -> Unit)? = null,
167+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
168+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
169+ val running by vm.running.collectAsStateWithLifecycle()
170+ val aborting by vm.aborting.collectAsStateWithLifecycle()
171+ val loading by vm.loading.collectAsStateWithLifecycle()
172+ val loadError by vm.loadError.collectAsStateWithLifecycle()
173+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
174+ val models by vm.models.collectAsStateWithLifecycle()
175+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
176+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
177+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
178+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
179+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
180+ val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
181+ val agents by vm.agents.collectAsStateWithLifecycle()
182+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
183+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
184+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
185+ val commands by vm.commands.collectAsStateWithLifecycle()
186+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
187+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
188+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
189+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
190+ val draft by vm.draft.collectAsStateWithLifecycle()
191+ val attachments by vm.attachments.collectAsStateWithLifecycle()
192+ val reverted by vm.reverted.collectAsStateWithLifecycle()
193+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
194+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
195+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
196+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
197+ val haptics = LocalHapticFeedback.current
198+ val scope = rememberCoroutineScope()
199+ val shareContext = LocalContext.current
200+ val defaultShareSubject = stringResource(R.string.share_subject)
201+ val sessionLabel = stringResource(R.string.session)
202+ val defaultModelLabel = stringResource(R.string.default_model)
203+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
205+ append(selectedModel?.modelLabel ?: defaultModelLabel)
206+ selectedAgent?.let { append(" · $it") }
210+ // Connection profile (with auth) for rendering inline image attachments.
211+ // Collect as state so a server switch recomposes the image context.
212+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
213+ val imageContext = remember(activeConnection?.profile) {
214+ activeConnection?.profile?.toImageContext()
217+ // Mark this session as read while the user is viewing it; clear on leave so new
218+ // background activity can badge it again.
219+ DisposableEffect(sessionId) {
220+ container.setCurrentSession(sessionId)
221+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
224+ // Navigate away when the session is deleted via SSE so the user isn't left
225+ // on a zombie screen showing a conversation that no longer exists. Surface a
226+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
227+ // would be torn down before the user could read it, while a toast survives.
228+ // Covers both SSE-driven deletion (deleted on another device) and a user-
229+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
230+ // sets the same flag on success).
231+ val deletedContext = LocalContext.current
232+ LaunchedEffect(sessionDeleted) {
233+ if (sessionDeleted) {
234+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
239+ val snackbar = remember { SnackbarHostState() }
240+ val retryLabel = stringResource(R.string.retry)
241+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
242+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
243+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
244+ var showTitleMenu by rememberSaveable { mutableStateOf(false) }
245+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
246+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
247+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
248+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
249+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
250+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
251+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
252+ var showPalette by rememberSaveable { mutableStateOf(false) }
253+ // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
254+ // a confirmation dialog (from both the overflow menu and the command palette).
255+ var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
256+ var showInitConfirm by rememberSaveable { mutableStateOf(false) }
258+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
259+ // action list doesn't need a Composable context. Actions map to the same handlers the
260+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
261+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
262+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
263+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
264+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
265+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
266+ val paletteShellLabel = stringResource(R.string.run_shell_command)
267+ val paletteActions = remember(
268+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
269+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
272+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
273+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
274+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
275+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
276+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
277+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
281+ // Keep the screen awake while the agent is working in *this* session. The foreground
282+ // service that holds process priority during a run is managed app-wide off
283+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
284+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
285+ // SSE stream before the completion notification fires.
286+ val currentView = LocalView.current
287+ val appContext = LocalContext.current.applicationContext
288+ DisposableEffect(running) {
289+ currentView.keepScreenOn = running
290+ onDispose { currentView.keepScreenOn = false }
293+ LaunchedEffect(Unit) {
294+ vm.errorEvents.collect { event ->
295+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
296+ // message-load failure) would silently re-submit the last prompt on tap.
297+ val result = if (event.retryable) {
298+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
300+ snackbar.showSnackbar(event.message)
302+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
306+ // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
307+ // window on the container; show the snackbar over the conversation the user is viewing so
308+ // they can cancel without being navigated to the session list first. If the window expires
309+ // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
310+ val undoLabel = stringResource(R.string.undo)
311+ val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
312+ LaunchedEffect(Unit) {
313+ vm.deleteUndoEvents.collect {
315+ val dismisser = launch {
316+ delay(NetworkConfig.undoDeleteDelayMs)
317+ snackbar.currentSnackbarData?.dismiss()
319+ val result = snackbar.showSnackbar(
320+ message = sessionDeletedLabel,
321+ actionLabel = undoLabel,
322+ duration = SnackbarDuration.Indefinite,
325+ if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
330+ // --- Attachments, voice, and share-link plumbing ---
331+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
332+ val attachFailedMsg = stringResource(R.string.attachment_failed)
333+ val attachLimitMsg = stringResource(R.string.attachment_limit)
334+ val noCameraMsg = stringResource(R.string.no_camera_app)
335+ val noVoiceMsg = stringResource(R.string.no_voice_app)
336+ val voicePrompt = stringResource(R.string.voice_prompt)
337+ val linkCopiedMsg = stringResource(R.string.link_copied)
339+ // Count of picks currently being read + base64-encoded off the main thread, so the
340+ // composer can show a staging placeholder immediately (chips only materialize once done).
341+ var stagingCount by remember { mutableStateOf(0) }
343+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
344+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
345+ fun stageUris(uris: List<Uri>) {
346+ if (uris.isEmpty()) return
351+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
352+ snackbar.showSnackbar(attachLimitMsg)
355+ when (val result = uri.toAttachmentResult(appContext)) {
356+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
357+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
358+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
367+ val photoPicker = rememberLauncherForActivityResult(
368+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
369+ ) { uris -> stageUris(uris) }
371+ val filePicker = rememberLauncherForActivityResult(
372+ ActivityResultContracts.GetMultipleContents(),
373+ ) { uris -> stageUris(uris) }
375+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
376+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
377+ val cameraLauncher = rememberLauncherForActivityResult(
378+ ActivityResultContracts.TakePicture(),
380+ val uri = pendingCaptureUri
381+ pendingCaptureUri = null
382+ if (success && uri != null) stageUris(listOf(uri))
385+ val voiceLauncher = rememberLauncherForActivityResult(
386+ ActivityResultContracts.StartActivityForResult(),
388+ if (result.resultCode == Activity.RESULT_OK) {
389+ val spoken = result.data
390+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
392+ ?.takeIf { it.isNotBlank() }
393+ if (spoken != null) {
394+ // Append to the existing draft rather than replacing, so dictation adds to
395+ // whatever the user already typed.
396+ val current = vm.draft.value
397+ val combined = if (current.isBlank()) spoken else "$current $spoken"
398+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
403+ fun launchCamera() {
404+ val uri = newCameraCaptureUri(appContext)
406+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
409+ pendingCaptureUri = uri
410+ runCatching { cameraLauncher.launch(uri) }
411+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
415+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
416+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
417+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
419+ runCatching { voiceLauncher.launch(intent) }
420+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
423+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
424+ LaunchedEffect(Unit) {
425+ vm.shareLinkEvents.collect { url ->
426+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
427+ snackbar.showSnackbar(linkCopiedMsg)
431+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
432+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
433+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
434+ // a dropped branch-navigation event in the gap.
435+ val branchedMsg = stringResource(R.string.branch_created)
436+ LaunchedEffect(Unit) {
437+ vm.branchEvents.collect { newId ->
438+ showToast(shareContext, branchedMsg)
439+ onOpenSession?.invoke(newId)
443+ // Stage images shared into the app (via the system share sheet) as attachments.
444+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
445+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
446+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
447+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
448+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
449+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
450+ LaunchedEffect(pendingSharedMedia) {
451+ val shared = container.consumePendingSharedMedia()
452+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
456+ if (vm.send(draft)) {
457+ // TextHandleMove (a light tick) is semantically right for a send commit;
458+ // LongPress is reserved for long-press/swipe gestures.
459+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
463+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
466+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
467+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
468+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
469+ // typing (and the composer's own Enter-to-send handling) is untouched.
470+ modifier = Modifier.onPreviewKeyEvent { ev ->
471+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
473+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
474+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
475+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
476+ showStopConfirm = true; true
484+ val changeLabel = stringResource(R.string.change_model_agent)
485+ // The subtitle reads "model · agent", so tapping the title offers *both*
486+ // — a small menu picks which picker to open. Previously the tap went
487+ // straight to the model picker, leaving the agent changeable only via
488+ // the overflow menu despite the title implying otherwise.
491+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
492+ // node; the click label rides on `clickable` (onClickLabel) instead of
493+ // an explicit contentDescription, which would have SUPPRESSED the child
494+ // Texts and announced only "Change model and agent".
498+ onClickLabel = changeLabel,
499+ ) { showTitleMenu = true }
500+ .semantics(mergeDescendants = true) {},
501+ verticalAlignment = Alignment.CenterVertically,
503+ Column(modifier = Modifier.weight(1f, fill = false)) {
504+ // maxLines=1 + Ellipsis so a long session title can't wrap and
505+ // push the top bar to multiple lines, shifting the whole layout.
507+ sessionTitle ?: sessionLabel,
509+ overflow = TextOverflow.Ellipsis,
513+ style = MaterialTheme.typography.labelSmall,
514+ color = MaterialTheme.colorScheme.onSurfaceVariant,
516+ overflow = TextOverflow.Ellipsis,
519+ // Always show the affordance so the title reads as tappable even when
520+ // the model catalog failed to load (models empty). Without it the title
521+ // is indistinguishable from plain text and the pickers are effectively
522+ // undiscoverable — and the dropdown items already disable themselves
523+ // while a catalog is loading or unavailable.
525+ Icons.Filled.KeyboardArrowDown,
526+ contentDescription = null,
527+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
528+ modifier = Modifier.size(20.dp),
531+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
533+ text = { Text(stringResource(R.string.palette_switch_model)) },
534+ enabled = !modelsLoading || models.isNotEmpty(),
535+ onClick = { showTitleMenu = false; showModelPicker = true },
538+ text = { Text(stringResource(R.string.palette_choose_agent)) },
539+ enabled = !agentsLoading || agents.isNotEmpty(),
540+ onClick = { showTitleMenu = false; showAgentPicker = true },
546+ IconButton(onClick = {
547+ if (running) showExitConfirm = true else onBack()
549+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
553+ // At-a-glance run status in the top bar. When the user is scrolled
554+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
555+ // trailing "working…" row are off-screen, so a top-bar spinner is the
556+ // only signal the agent is still working.
558+ val workingLabel = stringResource(R.string.working)
559+ CircularProgressIndicator(
560+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
564+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
565+ // from REST. A recovery path when the stream silently drops and the
566+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
567+ // immediate tap feedback — the SSE reconnect may not visibly change
568+ // the connection state when already Connected, so without it the tap
569+ // appears to do nothing.
570+ val refreshLabel = stringResource(R.string.refresh)
572+ onClick = { vm.refreshMessages() },
573+ enabled = activeConnection != null && !refreshing,
576+ CircularProgressIndicator(
577+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
581+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
584+ // Overflow menu consolidates the less-frequent actions (share,
585+ // commands, agent, model, rename, delete) so the top bar stays
586+ // scannable on narrow phones — previously 5 icons crowded the bar
587+ // alongside the back button and tappable title. Catalog-loading
588+ // spinners stay inline (next to the overflow) so a load state is
589+ // visible without opening the menu.
590+ val moreLabel = stringResource(R.string.more)
591+ val loadingLabel = stringResource(R.string.loading)
592+ val shareLabel = stringResource(R.string.share_conversation)
593+ val commandsLabel = stringResource(R.string.commands)
594+ val renameLabel = stringResource(R.string.rename_session_chat)
595+ val deleteLabel = stringResource(R.string.delete_session_chat)
596+ val createShareLabel = stringResource(R.string.create_share_link)
597+ val copyShareLabel = stringResource(R.string.copy_share_link)
598+ val stopShareLabel = stringResource(R.string.stop_sharing)
599+ val summarizeLabel = stringResource(R.string.summarize_conversation)
600+ val initLabel = stringResource(R.string.generate_agents_md)
601+ val shellLabel = stringResource(R.string.run_shell_command)
603+ IconButton(onClick = { showOverflowMenu = true }) {
604+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
607+ expanded = showOverflowMenu,
608+ onDismissRequest = { showOverflowMenu = false },
611+ text = { Text(shareLabel) },
612+ enabled = hasMessages,
614+ showOverflowMenu = false
616+ val md = withContext(Dispatchers.Default) {
617+ buildConversationMarkdown(vm.messages.value, sessionTitle)
619+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
620+ type = "text/markdown"
621+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
622+ putExtra(android.content.Intent.EXTRA_TEXT, md)
624+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
625+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
630+ text = { Text(commandsLabel) },
631+ enabled = !commandsLoading || commands.isNotEmpty(),
632+ onClick = { showOverflowMenu = false; showCommandPicker = true },
634+ androidx.compose.material3.HorizontalDivider()
635+ // Session sharing: create a public link, copy an existing one, or revoke it.
636+ if (shareUrl == null) {
638+ text = { Text(createShareLabel) },
639+ enabled = hasMessages,
640+ onClick = { showOverflowMenu = false; vm.shareSession() },
644+ text = { Text(copyShareLabel) },
646+ showOverflowMenu = false
648+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
649+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
654+ text = { Text(stopShareLabel) },
655+ onClick = { showOverflowMenu = false; vm.unshareSession() },
659+ text = { Text(summarizeLabel) },
660+ enabled = hasMessages && !running,
661+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
664+ text = { Text(initLabel) },
666+ onClick = { showOverflowMenu = false; showInitConfirm = true },
669+ text = { Text(shellLabel) },
671+ onClick = { showOverflowMenu = false; showShellDialog = true },
673+ androidx.compose.material3.HorizontalDivider()
675+ text = { Text(renameLabel) },
676+ onClick = { showOverflowMenu = false; showRenameDialog = true },
679+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
680+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
683+ // While a catalog is initially loading (empty list + loading flag),
684+ // show a tiny inline spinner beside the overflow so the user can see
685+ // a load is in progress without opening the menu. Once loaded the
686+ // spinner disappears; the menu items are always enabled (tapping a
687+ // picker with no items shows the "no models/agents/commands" state).
688+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
689+ (agentsLoading && agents.isEmpty()) ||
690+ (modelsLoading && models.isEmpty())
691+ if (catalogLoading) {
692+ CircularProgressIndicator(
694+ .align(Alignment.TopEnd)
696+ .semantics { contentDescription = loadingLabel },
704+ snackbarHost = { SnackbarHost(snackbar) },
706+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
707+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
708+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
709+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
711+ // Pinned above the composer so the agent's plan and progress stay visible
712+ // while scrolled up mid-run; renders nothing when there's no plan.
713+ TodoPlanBar(todoPlan)
714+ val bannerMotion = rememberVisibilityTransitions()
717+ enter = bannerMotion.enter,
718+ exit = bannerMotion.exit,
720+ RevertBanner(onUndo = { vm.unrevert() })
723+ visible = queuedOffline.isNotEmpty(),
724+ enter = bannerMotion.enter,
725+ exit = bannerMotion.exit,
728+ count = queuedOffline.size,
729+ sending = outboxSending,
730+ onFlush = { vm.flushQueued() },
731+ onDiscard = { vm.discardAllQueued() },
736+ onValueChange = vm::updateDraft,
738+ aborting = aborting,
739+ enabled = activeConnection != null,
740+ sendOnEnter = sendOnEnter,
742+ onAbort = { showStopConfirm = true },
743+ queuedFollowUp = queuedFollowUp,
744+ onQueueFollowUp = vm::queueFollowUp,
745+ onCancelQueue = { vm.queueFollowUp("") },
746+ focusRequester = inputFocusRequester,
747+ attachments = attachments,
748+ staging = stagingCount > 0,
749+ onRemoveAttachment = vm::removeAttachment,
752+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
755+ onPickFile = { filePicker.launch("*/*") },
756+ onCamera = { launchCamera() },
757+ onVoice = { launchVoice() },
762+ // Collect messages inside the content lambda so streaming token updates
763+ // recompose only this subtree, not the top bar / input bar / 20+ other
764+ // state reads in the ChatScreen body.
765+ val messages by vm.messages.collectAsStateWithLifecycle()
766+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
767+ val listState = rememberLazyListState()
768+ val contentScope = rememberCoroutineScope()
769+ val timeTick = rememberRelativeTimeTick()
770+ // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
771+ // chat affordance for reading while the IME is open. Watching isScrollInProgress via
772+ // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
773+ val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
774+ androidx.compose.runtime.LaunchedEffect(listState) {
775+ androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
776+ .distinctUntilChanged()
777+ .collect { scrolling -> if (scrolling) keyboardController?.hide() }
778+ } // Group messages by day and interleave date separators so a long conversation
779+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
780+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
781+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
782+ // the same list the LazyColumn renders (separators shift the indices vs. the
783+ // raw messages list, so scroll targets must be in listItems space).
784+ val todayLabel = stringResource(R.string.today)
785+ val yesterdayLabel = stringResource(R.string.yesterday)
786+ val listItems = remember(messages, todayLabel, yesterdayLabel) {
787+ buildMessageListItems(messages, todayLabel, yesterdayLabel)
789+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
790+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
791+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
792+ // would capture the first composition's list — which is empty, since `messages`
793+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
794+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
795+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
796+ // whose value tracks the latest list.
797+ val currentListItems by rememberUpdatedState(listItems)
799+ // New-content signal for the jump-to-latest FAB: set when content grows while the user
800+ // is scrolled away from the bottom, cleared once they return (see the collector below).
801+ var hasNewContent by remember { mutableStateOf(false) }
803+ val isPinnedToBottom by remember {
805+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
806+ // When a run is active, the LazyColumn has one trailing "__typing"
807+ // item after the last list item. Account for it so "pinned to bottom"
808+ // includes the working indicator — otherwise the pin check targets
809+ // listItems.lastIndex, the typing row sits just below the viewport,
810+ // and the user never sees the progress indicator even when pinned.
811+ val items = currentListItems
812+ val effectiveLast = if (running) items.size else items.lastIndex
813+ lastVisible >= effectiveLast || items.isEmpty()
817+ // Jump to the newest message once, when the conversation first loads. Guarded by a
818+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
819+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
820+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
821+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
822+ LaunchedEffect(listItems.isNotEmpty()) {
823+ if (listItems.isNotEmpty() && !didInitialScroll) {
824+ // When a run is active the LazyColumn has a trailing "__typing" row at
825+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
826+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
827+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
828+ didInitialScroll = true
832+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
833+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
834+ // isPinnedToBottom check flips to false the instant you send — freezing
835+ // auto-scroll. If the user was pinned to the last item just before the run
836+ // began, bring the typing row into view so the pin (and streaming follow) is
837+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
838+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
839+ LaunchedEffect(running) {
840+ if (running && listItems.isNotEmpty()) {
841+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
842+ if (lastVisible >= listItems.lastIndex) {
843+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
848+ LaunchedEffect(Unit) {
852+ // Track list size + the streaming length of the last part so we auto-scroll
853+ // as content arrives, plus the pinned flag. A small data class with primitive
854+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
855+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
856+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
857+ // and tool output — not just TextPart — keeps a pinned view following a long
858+ // reasoning/tool block while it streams (previously it stalled at 0).
859+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
860+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
861+ }.collect { signal ->
862+ if (signal.pinned) {
863+ // Back at the bottom: clear the new-content badge.
864+ hasNewContent = false
865+ if (signal.size > 0) {
866+ // Scroll to the effective last index, including the trailing
867+ // "__typing" row when a run is active so the working indicator
868+ // is brought into view (not just the last message).
869+ val items = currentListItems
870+ val target = if (running) items.size else items.lastIndex
871+ listState.scrollToItem(target)
873+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
874+ // Content arrived while scrolled up — badge the jump-to-latest FAB.
875+ hasNewContent = true
877+ prevSize = signal.size
878+ prevLen = signal.lastTextLength
882+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
883+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
884+ // content padding accounts for the bottomBar's raised height, so the message
885+ // list is already above the keyboard. Adding imePadding here would double-apply
886+ // the IME inset and push messages too far up.
887+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
888+ if (activeConnection == null) {
890+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
891+ horizontalAlignment = Alignment.CenterHorizontally,
894+ stringResource(R.string.not_connected),
895+ color = MaterialTheme.colorScheme.error,
897+ Spacer(Modifier.size(12.dp))
898+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
900+ CircularProgressIndicator(
901+ Modifier.size(20.dp),
902+ color = MaterialTheme.colorScheme.onPrimary,
906+ Text(stringResource(R.string.reconnect))
911+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
912+ // Measure the banner's actual height instead of hardcoding 44dp. At large
913+ // accessibility font scales the banner's labelMedium text + spinner + Retry
914+ // button exceed 44dp, so a fixed inset lets the first message hide behind it
915+ // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
916+ // fires while the banner is composed (visible), so gate the inset on
917+ // bannerVisible and fall back to 44dp until the first measurement arrives.
918+ var bannerHeightPx by remember { mutableIntStateOf(0) }
919+ val density = LocalDensity.current
920+ val topPad = if (bannerVisible) {
921+ if (bannerHeightPx > 0) {
922+ with(density) { bannerHeightPx.toDp() } + 4.dp
930+ state = connectionState,
931+ modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
932+ isOnline = isOnline,
933+ // On a hard failure, retry by forcing an SSE reconnect (which
934+ // re-seeds from REST). refreshMessages is the right recovery path
935+ // when the connection is present but the stream died; reconnect()
936+ // is the path when the whole connection is gone (handled by the
937+ // separate "Not connected" state below).
938+ onRetry = { vm.refreshMessages() },
940+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
941+ // recovery is a swipe away everywhere — not just when the message list is
942+ // populated. Previously PTR was only around the populated list, leaving the
943+ // error/loading states reachable only via a button tap.
945+ isRefreshing = refreshing,
946+ onRefresh = { vm.refreshMessages() },
947+ // Cap width and center on large screens for readability — full-width
948+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
949+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
950+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
952+ // Reserve top space when the banner is visible so it doesn't overlap the
953+ // first message / state content. (topPad computed above.)
954+ if (loading && messages.isEmpty()) {
955+ val loadingLabel = stringResource(R.string.loading)
956+ // Attach the a11y label directly to the spinner (a detached zero-size Box
957+ // isn't reliably focused/announced by TalkBack) and show a visible label so
958+ // sighted users get "Loading…" rather than a bare spinner.
960+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
961+ horizontalAlignment = Alignment.CenterHorizontally,
963+ CircularProgressIndicator(
964+ Modifier.semantics { contentDescription = loadingLabel },
967+ Spacer(Modifier.size(8.dp))
970+ style = MaterialTheme.typography.labelMedium,
971+ color = MaterialTheme.colorScheme.onSurfaceVariant,
974+ } else if (loadError && messages.isEmpty()) {
975+ // A failed load with nothing to show. Distinct from the empty
976+ // conversation state below — the conversation isn't empty, it
977+ // failed to load, and offering "Start a conversation" here is
978+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
980+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
981+ horizontalAlignment = Alignment.CenterHorizontally,
984+ stringResource(R.string.load_messages_failed),
985+ color = MaterialTheme.colorScheme.error,
987+ Spacer(Modifier.size(12.dp))
988+ Button(onClick = { vm.refreshMessages() }) {
989+ Text(stringResource(R.string.retry))
992+ } else if (messages.isEmpty() && running) {
993+ // A run just started but no parts have arrived yet — the empty
994+ // list with only the trailing "working…" row looks broken, so
995+ // surface a clear starting state until the first part streams in.
996+ val workingText = stringResource(R.string.working)
998+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
999+ horizontalAlignment = Alignment.CenterHorizontally,
1001+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
1002+ Spacer(Modifier.size(12.dp))
1003+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
1005+ } else if (messages.isEmpty()) {
1009+ // Focus the input so the user can edit the suggestion before
1010+ // sending, instead of having to manually tap the field.
1011+ runCatching { inputFocusRequester.requestFocus() }
1013+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1016+ val lastMessageId = messages.lastOrNull()?.info?.id
1017+ // Text-to-speech for reading assistant replies aloud; shuts down when the
1018+ // message list leaves composition.
1019+ val tts = rememberTtsController()
1020+ val speakingMessageId by tts.speakingId
1023+ modifier = Modifier.fillMaxSize(),
1024+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
1025+ // never floats over the last message. Top padding grows when the
1026+ // connection banner is visible so it doesn't overlap the first message.
1027+ contentPadding = PaddingValues(
1031+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1033+ verticalArrangement = Arrangement.spacedBy(16.dp),
1038+ contentType = { it.contentType },
1040+ // Default placement animation so inserted/moved rows glide in. Skipped
1041+ // entirely under reduced motion so a streaming message growing in place
1042+ // doesn't animate on every token (and respects the a11y preference).
1044+ if (LocalReducedMotion.current) Modifier else Modifier.animateItem(),
1047+ is MessageListItem.Separator -> DateSeparator(item.label)
1048+ is MessageListItem.Message -> {
1049+ val message = item.message
1050+ // Only the last (streaming) message needs isRunning — it drives the
1051+ // reasoning-block spinner. Passing the live flag to every bubble
1052+ // makes all visible messages recompose whenever a run starts or stops.
1053+ val modelLabel = remember(message.info, models) {
1054+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1055+ ?.let { resolveModelLabel(it, models) }
1057+ // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1058+ // image/code-only messages, which then opt out of the swipe gesture.
1059+ val quoteText = remember(message.parts) {
1061+ .filterIsInstance<TextPart>()
1062+ .joinToString("\n\n") { it.text }
1064+ .takeIf { it.isNotEmpty() }
1066+ // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1067+ // snapping back (the message isn't dismissed — the quote fills the composer).
1068+ // Only enabled when there's text to quote, so non-text messages don't
1069+ // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1070+ val swipeState = rememberSwipeToDismissBoxState(
1071+ confirmValueChange = { value ->
1072+ if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1073+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1074+ vm.quoteReply(quoteText)
1075+ runCatching { inputFocusRequester.requestFocus() }
1081+ state = swipeState,
1082+ enableDismissFromEndToStart = false,
1083+ enableDismissFromStartToEnd = quoteText != null,
1084+ backgroundContent = {
1086+ Modifier.fillMaxSize().padding(horizontal = 16.dp),
1087+ contentAlignment = Alignment.CenterStart,
1090+ Icons.AutoMirrored.Filled.Reply,
1091+ contentDescription = null,
1092+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1099+ isRunning = running && message.info.id == lastMessageId,
1100+ imageContext = imageContext,
1101+ modelLabel = modelLabel,
1102+ onOpenFile = onOpenFile,
1103+ onRevert = { vm.revertTo(message.info.id) },
1105+ // editMessage reverts to before this message (hiding it and
1106+ // everything after); the revert banner surfaces the rewind
1107+ // with an Undo. Focus + scroll the composer into view like the
1108+ // Quote action so the prefilled draft isn't off-screen.
1109+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1110+ vm.editMessage(message.info.id, text)
1111+ runCatching { inputFocusRequester.requestFocus() }
1112+ contentScope.launch {
1113+ runCatchingCancellable {
1114+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1118+ onSpeak = { text -> tts.toggle(message.info.id, text) },
1119+ isSpeaking = message.info.id == speakingMessageId,
1120+ onQuote = { text ->
1121+ vm.quoteReply(text)
1122+ runCatching { inputFocusRequester.requestFocus() }
1124+ onBranch = { text -> vm.branchFrom(text) },
1125+ sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1126+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1127+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1129+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1130+ onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1132+ { vm.retryOptimisticMessage(message.info.id) }
1137+ onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1139+ { vm.dismissOptimistic(message.info.id) }
1151+ item(key = "__typing") {
1152+ val workingText = stringResource(R.string.working)
1154+ verticalAlignment = Alignment.CenterVertically,
1155+ modifier = Modifier.semantics {
1156+ contentDescription = workingText
1159+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1160+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1167+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1168+ val fabMotion = rememberVisibilityTransitions()
1169+ AnimatedVisibility(
1170+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1171+ enter = fabMotion.enter,
1172+ exit = fabMotion.exit,
1173+ modifier = Modifier.align(Alignment.BottomEnd),
1175+ // Badge the FAB when new content arrived while the user was scrolled up, so
1176+ // they know there's something new to jump to (cleared once back at bottom).
1179+ if (hasNewContent) {
1180+ val newContentLabel = stringResource(R.string.new_messages)
1181+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1184+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1186+ ExtendedFloatingActionButton(
1188+ hasNewContent = false
1189+ if (listItems.isNotEmpty()) {
1190+ // Scroll to the effective last index, including the
1191+ // trailing "__typing" row when a run is active.
1192+ val target = if (running) listItems.size else listItems.lastIndex
1193+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1196+ // contentDescription null: the visible "Latest" text already labels
1197+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1198+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1199+ text = { Text(stringResource(R.string.latest)) },
1203+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1204+ // user has scrolled down past the first few messages. Symmetric to the
1205+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1206+ val scrolledDown by remember {
1207+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1209+ AnimatedVisibility(
1210+ visible = scrolledDown && listItems.size > 4,
1211+ enter = fabMotion.enter,
1212+ exit = fabMotion.exit,
1213+ modifier = Modifier.align(Alignment.BottomStart),
1215+ SmallFloatingActionButton(
1217+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1219+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1222+ Icons.Filled.KeyboardArrowUp,
1223+ contentDescription = stringResource(R.string.scroll_to_top),
1232+ if (showExitConfirm) {
1234+ onDismissRequest = { showExitConfirm = false },
1235+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1236+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1238+ TextButton(onClick = {
1239+ showExitConfirm = false
1240+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1243+ }) { Text(stringResource(R.string.stop_and_exit)) }
1246+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1251+ if (showStopConfirm) {
1253+ onDismissRequest = { showStopConfirm = false },
1254+ title = { Text(stringResource(R.string.stop_run_title)) },
1255+ text = { Text(stringResource(R.string.stop_run_text)) },
1257+ TextButton(onClick = {
1258+ showStopConfirm = false
1259+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1261+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1264+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1269+ if (showSummarizeConfirm) {
1271+ onDismissRequest = { showSummarizeConfirm = false },
1272+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
1273+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
1275+ TextButton(onClick = {
1276+ showSummarizeConfirm = false
1278+ }) { Text(stringResource(R.string.action_continue)) }
1281+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1286+ if (showInitConfirm) {
1288+ onDismissRequest = { showInitConfirm = false },
1289+ title = { Text(stringResource(R.string.init_confirm_title)) },
1290+ text = { Text(stringResource(R.string.init_confirm_text)) },
1292+ TextButton(onClick = {
1293+ showInitConfirm = false
1295+ }) { Text(stringResource(R.string.action_continue)) }
1298+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1303+ if (showRenameDialog) {
1304+ RenameSessionChatDialog(
1305+ initialTitle = sessionTitle ?: "",
1306+ onDismiss = { showRenameDialog = false },
1307+ onConfirm = { newName ->
1308+ showRenameDialog = false
1309+ vm.renameSession(newName)
1314+ if (showDeleteDialog) {
1316+ onDismissRequest = { showDeleteDialog = false },
1317+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1318+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1320+ TextButton(onClick = {
1321+ showDeleteDialog = false
1322+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1324+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1327+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1332+ if (showShellDialog) {
1333+ ShellCommandDialog(
1334+ onDismiss = { showShellDialog = false },
1336+ showShellDialog = false
1342+ if (showModelPicker) {
1345+ selected = selectedModel,
1346+ loading = modelsLoading,
1347+ error = modelsError,
1348+ onSelect = { vm.selectModel(it) },
1349+ onRetry = { vm.reloadModels() },
1350+ onDismiss = { showModelPicker = false },
1354+ if (showAgentPicker) {
1357+ selected = selectedAgent,
1358+ loading = agentsLoading,
1359+ error = agentsError,
1360+ onSelect = { vm.selectAgent(it?.name) },
1361+ onRetry = { vm.reloadAgents() },
1362+ onDismiss = { showAgentPicker = false },
1366+ if (showCommandPicker) {
1367+ CommandPickerSheet(
1368+ commands = commands,
1369+ loading = commandsLoading,
1370+ error = commandsError,
1371+ onSelect = { vm.runCommand(it) },
1372+ onRetry = { vm.reloadCommands() },
1373+ onDismiss = { showCommandPicker = false },
1377+ pendingPermission?.let { permission ->
1379+ permission = permission,
1380+ position = permissionProgress.position,
1381+ total = permissionProgress.total,
1382+ onRespond = { response -> vm.respondPermission(permission, response) },
1387+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1392+private fun ChatInputBar(
1394+ onValueChange: (String) -> Unit,
1398+ sendOnEnter: Boolean,
1399+ onSend: () -> Unit,
1400+ onAbort: () -> Unit,
1401+ queuedFollowUp: String?,
1402+ onQueueFollowUp: (String) -> Unit,
1403+ onCancelQueue: () -> Unit,
1404+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1405+ attachments: List<PendingAttachment>,
1407+ onRemoveAttachment: (String) -> Unit,
1408+ onPickPhoto: () -> Unit,
1409+ onPickFile: () -> Unit,
1410+ onCamera: () -> Unit,
1411+ onVoice: () -> Unit,
1413+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1414+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1415+ // Full-screen editor state: opened when the user wants more space for a long prompt.
1416+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1417+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1418+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1419+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1420+ // user sees their message will be sent when the run finishes, and can cancel.
1421+ if (queuedFollowUp != null) {
1423+ modifier = Modifier
1425+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1426+ verticalAlignment = Alignment.CenterVertically,
1428+ Column(modifier = Modifier.weight(1f)) {
1430+ stringResource(R.string.queued),
1431+ style = MaterialTheme.typography.labelSmall,
1432+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1436+ style = MaterialTheme.typography.bodySmall,
1437+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1439+ overflow = TextOverflow.Ellipsis,
1442+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1443+ Text(stringResource(R.string.cancel))
1447+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1448+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1450+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1451+ verticalAlignment = Alignment.Bottom,
1453+ // Attach menu: photo picker, camera, or any file.
1454+ var showAttachMenu by remember { mutableStateOf(false) }
1456+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1457+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1459+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1461+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1462+ text = { Text(stringResource(R.string.attach_photo)) },
1463+ onClick = { showAttachMenu = false; onPickPhoto() },
1466+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1467+ text = { Text(stringResource(R.string.attach_camera)) },
1468+ onClick = { showAttachMenu = false; onCamera() },
1471+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1472+ text = { Text(stringResource(R.string.attach_file)) },
1473+ onClick = { showAttachMenu = false; onPickFile() },
1477+ // Voice dictation: appends recognized speech to the draft.
1478+ IconButton(onClick = onVoice, enabled = enabled) {
1479+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1481+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1482+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1483+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1487+ onValueChange = { v ->
1488+ // Cap input length so a huge paste can't stall the UI. Shares are
1489+ // capped separately in MainActivity; this guards typed/pasted drafts.
1490+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1492+ modifier = Modifier
1494+ .focusRequester(focusRequester)
1495+ .testTag("chat_input")
1496+ .onPreviewKeyEvent { event ->
1497+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1498+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1499+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1500+ val send = enterShouldSend(
1502+ hasContent = hasContent,
1503+ sendOnEnter = sendOnEnter,
1504+ shift = event.isShiftPressed,
1505+ ctrl = event.isCtrlPressed,
1508+ if (running) onQueueFollowUp(value) else onSend()
1514+ // While a run is active a typed message only queues (sends after the run), so
1515+ // the placeholder says so instead of the plain "Message…".
1517+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1521+ // Show a "N / max" countdown once the draft crosses a high fraction of
1522+ // the cap, so the user knows a paste is about to be truncated instead
1523+ // of being silently cut off. Hidden for normal short prompts to avoid
1524+ // clutter under a typical one-line message.
1526+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1527+ if (value.length >= threshold) {
1530+ R.string.draft_chars_remaining,
1531+ NetworkConfig.maxDraftLengthChars - value.length,
1532+ NetworkConfig.maxDraftLengthChars,
1534+ style = MaterialTheme.typography.labelSmall,
1535+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1536+ else MaterialTheme.colorScheme.onSurfaceVariant,
1540+ keyboardOptions = KeyboardOptions(
1541+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
1542+ // keyboard shows a send key — matching the setting's intent and
1543+ // giving touch-only users a keyboard send affordance. When off,
1544+ // ImeAction.Default keeps the enter/newline key for multi-line input.
1545+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1546+ capitalization = KeyboardCapitalization.Sentences,
1548+ keyboardActions = KeyboardActions(
1550+ if (enabled && hasContent) onSend()
1554+ ComposerTrailingButton(
1556+ aborting = aborting,
1557+ canSend = enabled && hasContent,
1558+ canQueue = enabled && value.isNotBlank(),
1561+ onQueue = { onQueueFollowUp(value) },
1565+ if (showFullScreenEditor) {
1568+ onValueChange = onValueChange,
1569+ onDismiss = { showFullScreenEditor = false },
1570+ onSend = { showFullScreenEditor = false; onSend() },
1571+ canSend = enabled && hasContent,
1577+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1578+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1579+@OptIn(ExperimentalMaterial3Api::class)
1581+private fun FullScreenEditor(
1583+ onValueChange: (String) -> Unit,
1584+ onDismiss: () -> Unit,
1585+ onSend: () -> Unit,
1588+ androidx.compose.ui.window.Dialog(
1589+ onDismissRequest = onDismiss,
1590+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1594+ androidx.compose.material3.TopAppBar(
1595+ title = { Text(stringResource(R.string.message_placeholder)) },
1597+ androidx.compose.material3.TextButton(onClick = onDismiss) {
1598+ Text(stringResource(R.string.collapse_editor))
1604+ Surface(tonalElevation = 3.dp) {
1606+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1607+ horizontalArrangement = Arrangement.End,
1609+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1610+ Text(stringResource(R.string.send))
1618+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1619+ modifier = Modifier.fillMaxSize().padding(padding),
1620+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
1621+ maxLines = Int.MAX_VALUE,
1622+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1628+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1629+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1630+private fun enterShouldSend(
1632+ hasContent: Boolean,
1633+ sendOnEnter: Boolean,
1637+ !enabled || !hasContent -> false
1638+ sendOnEnter -> !shift
1642+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1643+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1644+ * [ChatInputBar] stays under the complexity threshold. */
1646+private fun ComposerTrailingButton(
1651+ onSend: () -> Unit,
1652+ onAbort: () -> Unit,
1653+ onQueue: () -> Unit,
1656+ Row(verticalAlignment = Alignment.CenterVertically) {
1657+ // While a run is active the trailing action is Stop, so the only send affordance is
1658+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1659+ // That leaves a touch-only user with the setting off no way to queue a follow-up
1660+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1661+ // there's typed TEXT so queuing is always reachable, without changing the user's
1662+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1663+ // canSend, which is also true for an attachment-only composer — because queuing "" just
1664+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1665+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1669+ modifier = Modifier.testTag("queue_button"),
1671+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1672+ // icon (which can be read as "snooze" or "later"), and isn't confused with
1673+ // the Send action sitting right beside the Stop button.
1675+ Icons.AutoMirrored.Filled.PlaylistAdd,
1676+ contentDescription = stringResource(R.string.queue_followup),
1680+ // Show a spinner while the abort REST call is in flight so the user sees the stop
1681+ // was sent, and disable to prevent a double-tap.
1684+ enabled = !aborting,
1685+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1688+ val stopLabel = stringResource(R.string.stop)
1689+ CircularProgressIndicator(
1690+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1691+ strokeWidth = 2.dp,
1694+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1702+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1704+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1709+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1711+private fun EmptyConversation(
1712+ onSuggestion: (String) -> Unit,
1713+ modifier: Modifier = Modifier,
1715+ // A few example prompts so a first-time user has a one-tap path to their first
1716+ // message instead of staring at a blank input. Tapping a chip fills the draft
1717+ // (without sending) so the user can edit it before sending.
1718+ val suggestions = remember {
1720+ R.string.empty_chat_suggest_1,
1721+ R.string.empty_chat_suggest_2,
1722+ R.string.empty_chat_suggest_3,
1726+ modifier = modifier.padding(32.dp),
1727+ horizontalAlignment = Alignment.CenterHorizontally,
1730+ Icons.Filled.AutoAwesome,
1731+ contentDescription = null,
1732+ modifier = Modifier.size(48.dp),
1733+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1735+ Spacer(Modifier.size(16.dp))
1737+ stringResource(R.string.empty_chat_title),
1738+ style = MaterialTheme.typography.titleMedium,
1740+ Spacer(Modifier.size(8.dp))
1742+ stringResource(R.string.empty_chat_hint),
1743+ style = MaterialTheme.typography.bodyMedium,
1744+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1746+ Spacer(Modifier.size(20.dp))
1747+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1748+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
1750+ modifier = Modifier.fillMaxWidth(),
1751+ horizontalArrangement = Arrangement.spacedBy(8.dp),
1752+ verticalArrangement = Arrangement.spacedBy(8.dp),
1754+ suggestions.forEach { resId ->
1755+ val text = stringResource(resId)
1756+ androidx.compose.material3.AssistChip(
1757+ onClick = { onSuggestion(text) },
1758+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1765+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1767+private fun RevertBanner(onUndo: () -> Unit) {
1769+ color = MaterialTheme.colorScheme.tertiaryContainer,
1770+ tonalElevation = 2.dp,
1771+ modifier = Modifier.fillMaxWidth(),
1774+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1775+ verticalAlignment = Alignment.CenterVertically,
1776+ horizontalArrangement = Arrangement.SpaceBetween,
1778+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1780+ Icons.Filled.Restore,
1781+ contentDescription = null,
1782+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
1783+ modifier = Modifier.size(18.dp),
1786+ stringResource(R.string.reverted_banner),
1787+ style = MaterialTheme.typography.bodySmall,
1788+ color = MaterialTheme.colorScheme.onTertiaryContainer,
1789+ modifier = Modifier.padding(start = 8.dp),
1792+ TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1797+/** A banner shown while messages composed offline are queued in the outbox, with a
1798+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1800+private fun OutboxBanner(
1803+ onFlush: () -> Unit,
1804+ onDiscard: () -> Unit,
1807+ color = MaterialTheme.colorScheme.secondaryContainer,
1808+ tonalElevation = 2.dp,
1809+ modifier = Modifier.fillMaxWidth(),
1812+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1813+ verticalAlignment = Alignment.CenterVertically,
1814+ horizontalArrangement = Arrangement.SpaceBetween,
1816+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1818+ CircularProgressIndicator(
1819+ Modifier.size(16.dp),
1820+ strokeWidth = 2.dp,
1821+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1823+ Spacer(Modifier.size(8.dp))
1827+ stringResource(R.string.outbox_sending)
1829+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1830+ stringResource(res, count)
1832+ style = MaterialTheme.typography.bodySmall,
1833+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1837+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1838+ TextButton(onClick = onDiscard) {
1839+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1846+/** Prompt for a one-off shell command to run in the session's worktree. */
1848+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1849+ var command by rememberSaveable { mutableStateOf("") }
1851+ onDismissRequest = onDismiss,
1852+ title = { Text(stringResource(R.string.run_shell_command)) },
1856+ onValueChange = { command = it },
1857+ modifier = Modifier.fillMaxWidth(),
1858+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1859+ label = { Text(stringResource(R.string.shell_command_label)) },
1861+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1862+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1867+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1868+ enabled = command.isNotBlank(),
1869+ ) { Text(stringResource(R.string.run)) }
1871+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1876+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1877+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1878+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
1880+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1882+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1883+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1884+ * streaming, not just plain assistant text. O(1). */
1885+private fun streamingContentLength(part: Part?): Int = when (part) {
1886+ is TextPart -> part.text.length
1887+ is ReasoningPart -> part.text.length
1888+ is ToolPart -> when (val st = part.state) {
1889+ is ToolCompleted -> st.output?.length ?: 0
1890+ is ToolError -> st.error?.length ?: 0
1891+ is ToolRunning -> st.title?.length ?: 0
1897+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1898+ * dialog but lives in the chat screen so the user can rename without backing out to
1899+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
1901+private fun RenameSessionChatDialog(
1902+ initialTitle: String,
1903+ onDismiss: () -> Unit,
1904+ onConfirm: (String) -> Unit,
1906+ // Seed the field once (no key input) so a later external title change — e.g. opencode
1907+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1908+ // doesn't re-initialize the box and discard the user's in-progress edit.
1909+ var title by rememberSaveable { mutableStateOf(initialTitle) }
1911+ onDismissRequest = onDismiss,
1912+ title = { Text(stringResource(R.string.rename_session_chat)) },
1916+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1917+ modifier = Modifier.fillMaxWidth(),
1918+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
1919+ label = { Text(stringResource(R.string.rename_session_chat)) },
1921+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1922+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1926+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1927+ Text(stringResource(R.string.save))
1931+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1937+ * A single item in the chat message list — either a [Message] bubble or a day
1938+ * [Separator] inserted before the first message of a new day. The separator shifts
1939+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1940+ * the [List] of these items (not `messages.size`/`lastIndex`).
1942+private sealed interface MessageListItem {
1944+ val contentType: Any
1946+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1947+ override val contentType: Any get() = message.info::class
1950+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1951+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1952+ // can share a label (e.g. an untimestamped message — empty label — between two
1953+ // same-day messages, or two untimestamped groups), and a label-only key would
1954+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1955+ // stable for a given message ordering so slots aren't needlessly recreated.
1956+ override val key: Any get() = "sep_${ordinal}_$label"
1957+ // Separators share a contentType so the LazyColumn can recycle their slots.
1958+ override val contentType: Any get() = "separator"
1963+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1964+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1965+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1966+ * Messages with no timestamp are grouped under an empty-label separator only if they
1967+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
1969+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1970+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1971+ * labels; older days fall back to a locale-stable medium-date format.
1973+private fun buildMessageListItems(
1974+ messages: List<MessageWithParts>,
1975+ todayLabel: String,
1976+ yesterdayLabel: String,
1977+): List<MessageListItem> {
1978+ if (messages.isEmpty()) return emptyList()
1979+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1980+ val dateFmt = mediumDateFormat()
1981+ val result = ArrayList<MessageListItem>(messages.size + 4)
1982+ val seenKeys = HashSet<String>(messages.size * 2)
1983+ var lastDayKey: String? = null
1985+ var emptyIdOrdinal = 0
1987+ for (message in messages) {
1988+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1989+ val dayKey = ts?.let { dayKey(it) } ?: ""
1990+ // Emit a separator before the very first message (so a leading un-timestamped message
1991+ // still gets the first divider, empty label and all), and thereafter only when crossing
1992+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1993+ // neither emits its own separator nor resets the day — otherwise a following same-day
1994+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1995+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1996+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1998+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
2000+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
2001+ // empty id — and the reducer intentionally keeps several such messages as distinct
2002+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
2003+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
2004+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
2005+ if (!seenKeys.add(key)) {
2007+ while (!seenKeys.add("$key#$suffix")) suffix++
2008+ key = "$key#$suffix"
2010+ result.add(MessageListItem.Message(message, key))
2016+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2018+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2019+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
2020+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2021+ * every message on every token. Message timestamps are immutable once assigned, so we
2022+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2023+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2024+ * thread during composition, so the coarse lock is uncontended.
2026+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2027+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2030+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2031+ dayKeyCache.getOrPut(epochMillis) {
2032+ java.time.Instant.ofEpochMilli(epochMillis)
2033+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2037+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2038+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2039+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2040+private var cachedDateFmt: java.text.DateFormat? = null
2041+private var cachedDateFmtLocale: java.util.Locale? = null
2043+private fun mediumDateFormat(): java.text.DateFormat {
2044+ val locale = java.util.Locale.getDefault()
2045+ val existing = cachedDateFmt
2046+ if (existing != null && cachedDateFmtLocale == locale) return existing
2047+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2049+ cachedDateFmtLocale = locale
2054+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2055+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2056+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2059+private fun dayLabel(
2062+ today: java.time.LocalDate,
2063+ todayLabel: String,
2064+ yesterdayLabel: String,
2065+ dateFmt: java.text.DateFormat,
2067+ if (dayKey.isEmpty()) return ""
2068+ val epochDay = dayKey.toLongOrNull() ?: return ""
2069+ val date = java.time.LocalDate.ofEpochDay(epochDay)
2071+ date == today -> todayLabel
2072+ date == today.minusDays(1) -> yesterdayLabel
2073+ else -> dateFmt.format(java.util.Date(ts))
2078+ * A centered day divider in the message list. Renders nothing for an empty label
2079+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2082+private fun DateSeparator(label: String) {
2083+ if (label.isBlank()) return
2085+ modifier = Modifier.fillMaxWidth(),
2086+ horizontalArrangement = Arrangement.Center,
2089+ color = MaterialTheme.colorScheme.surfaceVariant,
2090+ shape = MaterialTheme.shapes.small,
2094+ style = MaterialTheme.typography.labelSmall,
2095+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2096+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),