@@ -0,0 +1,1955 @@
1+@file:Suppress("TooManyFunctions")
2+
3+package soy.iko.opencode.ui.chat
4+
5+import android.app.Activity
6+import android.content.Intent
7+import android.net.Uri
8+import android.speech.RecognizerIntent
9+import androidx.activity.compose.BackHandler
10+import androidx.activity.compose.rememberLauncherForActivityResult
11+import androidx.activity.result.PickVisualMediaRequest
12+import androidx.activity.result.contract.ActivityResultContracts
13+import androidx.compose.animation.AnimatedVisibility
14+import androidx.compose.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.filled.Schedule
55+import androidx.compose.material.icons.filled.Stop
56+import androidx.compose.material3.AlertDialog
57+import androidx.compose.material3.Badge
58+import androidx.compose.material3.BadgedBox
59+import androidx.compose.material3.Button
60+import androidx.compose.material3.CircularProgressIndicator
61+import androidx.compose.material3.SmallFloatingActionButton
62+import androidx.compose.material3.DropdownMenu
63+import androidx.compose.material3.DropdownMenuItem
64+import androidx.compose.material3.ExperimentalMaterial3Api
65+import androidx.compose.material3.ExtendedFloatingActionButton
66+import androidx.compose.material3.FloatingActionButton
67+import androidx.compose.material3.Icon
68+import androidx.compose.material3.IconButton
69+import androidx.compose.material3.MaterialTheme
70+import androidx.compose.material3.OutlinedTextField
71+import androidx.compose.material3.Scaffold
72+import androidx.compose.material3.SnackbarHost
73+import androidx.compose.material3.SnackbarHostState
74+import androidx.compose.material3.Surface
75+import androidx.compose.material3.Text
76+import androidx.compose.material3.TextButton
77+import androidx.compose.material3.TopAppBar
78+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
79+import androidx.compose.runtime.Composable
80+import androidx.compose.runtime.CompositionLocalProvider
81+import androidx.compose.runtime.DisposableEffect
82+import androidx.compose.runtime.LaunchedEffect
83+import androidx.compose.runtime.derivedStateOf
84+import androidx.compose.runtime.getValue
85+import androidx.compose.runtime.mutableStateOf
86+import androidx.compose.runtime.remember
87+import androidx.compose.runtime.rememberCoroutineScope
88+import androidx.compose.runtime.rememberUpdatedState
89+import androidx.compose.runtime.saveable.rememberSaveable
90+import androidx.compose.runtime.setValue
91+import androidx.compose.runtime.snapshotFlow
92+import androidx.compose.foundation.text.KeyboardActions
93+import androidx.compose.foundation.text.KeyboardOptions
94+import androidx.compose.ui.text.input.KeyboardCapitalization
95+import androidx.compose.ui.Alignment
96+import androidx.compose.ui.Modifier
97+import androidx.compose.ui.focus.focusRequester
98+import androidx.compose.ui.input.key.Key
99+import androidx.compose.ui.input.key.KeyEventType
100+import androidx.compose.ui.input.key.isCtrlPressed
101+import androidx.compose.ui.input.key.isShiftPressed
102+import androidx.compose.ui.input.key.key
103+import androidx.compose.ui.input.key.onPreviewKeyEvent
104+import androidx.compose.ui.input.key.type
105+import androidx.compose.ui.platform.LocalContext
106+import androidx.compose.ui.platform.LocalHapticFeedback
107+import androidx.compose.ui.platform.LocalView
108+import androidx.compose.ui.platform.testTag
109+import androidx.compose.ui.res.stringResource
110+import androidx.compose.ui.semantics.Role
111+import androidx.compose.ui.semantics.contentDescription
112+import androidx.compose.ui.semantics.semantics
113+import androidx.compose.ui.text.input.ImeAction
114+import androidx.compose.ui.text.style.TextOverflow
115+import androidx.compose.ui.unit.dp
116+import androidx.lifecycle.compose.collectAsStateWithLifecycle
117+import androidx.lifecycle.viewmodel.compose.viewModel
118+import kotlinx.coroutines.Dispatchers
119+import kotlinx.coroutines.launch
120+import kotlinx.coroutines.withContext
121+import soy.iko.opencode.data.model.Part
122+import soy.iko.opencode.data.model.MessageWithParts
123+import soy.iko.opencode.data.model.ReasoningPart
124+import soy.iko.opencode.data.model.TextPart
125+import soy.iko.opencode.data.model.ToolCompleted
126+import soy.iko.opencode.data.model.ToolError
127+import soy.iko.opencode.data.model.ToolPart
128+import soy.iko.opencode.data.model.ToolRunning
129+import soy.iko.opencode.data.network.EventStreamClient
130+import soy.iko.opencode.data.network.NetworkConfig
131+import soy.iko.opencode.di.AppContainer
132+import soy.iko.opencode.R
133+import soy.iko.opencode.ui.components.CommandPalette
134+import soy.iko.opencode.ui.components.ConnectionBanner
135+import soy.iko.opencode.ui.components.PaletteAction
136+import soy.iko.opencode.ui.components.copyToClipboard
137+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
138+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
139+import soy.iko.opencode.ui.components.showToast
140+import soy.iko.opencode.ui.components.toImageContext
141+import soy.iko.opencode.ui.vmFactory
142+import soy.iko.opencode.util.runCatchingCancellable
143+
144+@OptIn(ExperimentalMaterial3Api::class)
145+@Composable
146+fun ChatScreen(
147+ container: AppContainer,
148+ sessionId: String,
149+ onBack: () -> Unit,
150+ onOpenFile: ((String) -> Unit)? = null,
151+ onOpenSession: ((String) -> Unit)? = null,
152+) {
153+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
154+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
155+ val running by vm.running.collectAsStateWithLifecycle()
156+ val aborting by vm.aborting.collectAsStateWithLifecycle()
157+ val loading by vm.loading.collectAsStateWithLifecycle()
158+ val loadError by vm.loadError.collectAsStateWithLifecycle()
159+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
160+ val models by vm.models.collectAsStateWithLifecycle()
161+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
162+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
163+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
164+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
165+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
166+ val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
167+ val agents by vm.agents.collectAsStateWithLifecycle()
168+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
169+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
170+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
171+ val commands by vm.commands.collectAsStateWithLifecycle()
172+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
173+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
174+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
175+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
176+ val draft by vm.draft.collectAsStateWithLifecycle()
177+ val attachments by vm.attachments.collectAsStateWithLifecycle()
178+ val reverted by vm.reverted.collectAsStateWithLifecycle()
179+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
180+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
181+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
182+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
183+ val haptics = LocalHapticFeedback.current
184+ val scope = rememberCoroutineScope()
185+ val shareContext = LocalContext.current
186+ val defaultShareSubject = stringResource(R.string.share_subject)
187+ val sessionLabel = stringResource(R.string.session)
188+ val defaultModelLabel = stringResource(R.string.default_model)
189+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
190+ buildString {
191+ append(selectedModel?.modelLabel ?: defaultModelLabel)
192+ selectedAgent?.let { append(" · $it") }
193+ }
194+ }
195+
196+ // Connection profile (with auth) for rendering inline image attachments.
197+ // Collect as state so a server switch recomposes the image context.
198+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
199+ val imageContext = remember(activeConnection?.profile) {
200+ activeConnection?.profile?.toImageContext()
201+ }
202+
203+ // Mark this session as read while the user is viewing it; clear on leave so new
204+ // background activity can badge it again.
205+ DisposableEffect(sessionId) {
206+ container.setCurrentSession(sessionId)
207+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
208+ }
209+
210+ // Navigate away when the session is deleted via SSE so the user isn't left
211+ // on a zombie screen showing a conversation that no longer exists. Surface a
212+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
213+ // would be torn down before the user could read it, while a toast survives.
214+ // Covers both SSE-driven deletion (deleted on another device) and a user-
215+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
216+ // sets the same flag on success).
217+ val deletedContext = LocalContext.current
218+ LaunchedEffect(sessionDeleted) {
219+ if (sessionDeleted) {
220+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
221+ onBack()
222+ }
223+ }
224+
225+ val snackbar = remember { SnackbarHostState() }
226+ val retryLabel = stringResource(R.string.retry)
227+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
228+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
229+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
230+ var showTitleMenu by rememberSaveable { mutableStateOf(false) }
231+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
232+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
233+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
234+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
235+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
236+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
237+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
238+ var showPalette by rememberSaveable { mutableStateOf(false) }
239+ // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
240+ // a confirmation dialog (from both the overflow menu and the command palette).
241+ var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
242+ var showInitConfirm by rememberSaveable { mutableStateOf(false) }
243+
244+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
245+ // action list doesn't need a Composable context. Actions map to the same handlers the
246+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
247+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
248+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
249+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
250+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
251+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
252+ val paletteShellLabel = stringResource(R.string.run_shell_command)
253+ val paletteActions = remember(
254+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
255+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
256+ ) {
257+ buildList {
258+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
259+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
260+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
261+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
262+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
263+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
264+ }
265+ }
266+
267+ // Keep the screen awake while the agent is working in *this* session. The foreground
268+ // service that holds process priority during a run is managed app-wide off
269+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
270+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
271+ // SSE stream before the completion notification fires.
272+ val currentView = LocalView.current
273+ val appContext = LocalContext.current.applicationContext
274+ DisposableEffect(running) {
275+ currentView.keepScreenOn = running
276+ onDispose { currentView.keepScreenOn = false }
277+ }
278+
279+ LaunchedEffect(Unit) {
280+ vm.errorEvents.collect { event ->
281+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
282+ // message-load failure) would silently re-submit the last prompt on tap.
283+ val result = if (event.retryable) {
284+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
285+ } else {
286+ snackbar.showSnackbar(event.message)
287+ }
288+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
289+ }
290+ }
291+
292+ // --- Attachments, voice, and share-link plumbing ---
293+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
294+ val attachFailedMsg = stringResource(R.string.attachment_failed)
295+ val attachLimitMsg = stringResource(R.string.attachment_limit)
296+ val noCameraMsg = stringResource(R.string.no_camera_app)
297+ val noVoiceMsg = stringResource(R.string.no_voice_app)
298+ val voicePrompt = stringResource(R.string.voice_prompt)
299+ val linkCopiedMsg = stringResource(R.string.link_copied)
300+
301+ // Count of picks currently being read + base64-encoded off the main thread, so the
302+ // composer can show a staging placeholder immediately (chips only materialize once done).
303+ var stagingCount by remember { mutableStateOf(0) }
304+
305+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
306+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
307+ fun stageUris(uris: List<Uri>) {
308+ if (uris.isEmpty()) return
309+ scope.launch {
310+ stagingCount++
311+ try {
312+ for (uri in uris) {
313+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
314+ snackbar.showSnackbar(attachLimitMsg)
315+ break
316+ }
317+ when (val result = uri.toAttachmentResult(appContext)) {
318+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
319+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
320+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
321+ }
322+ }
323+ } finally {
324+ stagingCount--
325+ }
326+ }
327+ }
328+
329+ val photoPicker = rememberLauncherForActivityResult(
330+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
331+ ) { uris -> stageUris(uris) }
332+
333+ val filePicker = rememberLauncherForActivityResult(
334+ ActivityResultContracts.GetMultipleContents(),
335+ ) { uris -> stageUris(uris) }
336+
337+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
338+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
339+ val cameraLauncher = rememberLauncherForActivityResult(
340+ ActivityResultContracts.TakePicture(),
341+ ) { success ->
342+ val uri = pendingCaptureUri
343+ pendingCaptureUri = null
344+ if (success && uri != null) stageUris(listOf(uri))
345+ }
346+
347+ val voiceLauncher = rememberLauncherForActivityResult(
348+ ActivityResultContracts.StartActivityForResult(),
349+ ) { result ->
350+ if (result.resultCode == Activity.RESULT_OK) {
351+ val spoken = result.data
352+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
353+ ?.firstOrNull()
354+ ?.takeIf { it.isNotBlank() }
355+ if (spoken != null) {
356+ // Append to the existing draft rather than replacing, so dictation adds to
357+ // whatever the user already typed.
358+ val current = vm.draft.value
359+ val combined = if (current.isBlank()) spoken else "$current $spoken"
360+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
361+ }
362+ }
363+ }
364+
365+ fun launchCamera() {
366+ val uri = newCameraCaptureUri(appContext)
367+ if (uri == null) {
368+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
369+ return
370+ }
371+ pendingCaptureUri = uri
372+ runCatching { cameraLauncher.launch(uri) }
373+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
374+ }
375+
376+ fun launchVoice() {
377+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
378+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
379+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
380+ }
381+ runCatching { voiceLauncher.launch(intent) }
382+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
383+ }
384+
385+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
386+ LaunchedEffect(Unit) {
387+ vm.shareLinkEvents.collect { url ->
388+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
389+ snackbar.showSnackbar(linkCopiedMsg)
390+ }
391+ }
392+
393+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
394+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
395+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
396+ // a dropped branch-navigation event in the gap.
397+ val branchedMsg = stringResource(R.string.branch_created)
398+ LaunchedEffect(Unit) {
399+ vm.branchEvents.collect { newId ->
400+ showToast(shareContext, branchedMsg)
401+ onOpenSession?.invoke(newId)
402+ }
403+ }
404+
405+ // Stage images shared into the app (via the system share sheet) as attachments.
406+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
407+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
408+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
409+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
410+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
411+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
412+ LaunchedEffect(pendingSharedMedia) {
413+ val shared = container.consumePendingSharedMedia()
414+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
415+ }
416+
417+ fun doSend() {
418+ if (vm.send(draft)) {
419+ // TextHandleMove (a light tick) is semantically right for a send commit;
420+ // LongPress is reserved for long-press/swipe gestures.
421+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
422+ }
423+ }
424+
425+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
426+
427+ Scaffold(
428+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
429+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
430+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
431+ // typing (and the composer's own Enter-to-send handling) is untouched.
432+ modifier = Modifier.onPreviewKeyEvent { ev ->
433+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
434+ when {
435+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
436+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
437+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
438+ showStopConfirm = true; true
439+ }
440+ else -> false
441+ }
442+ },
443+ topBar = {
444+ TopAppBar(
445+ title = {
446+ val changeLabel = stringResource(R.string.change_model_agent)
447+ // The subtitle reads "model · agent", so tapping the title offers *both*
448+ // — a small menu picks which picker to open. Previously the tap went
449+ // straight to the model picker, leaving the agent changeable only via
450+ // the overflow menu despite the title implying otherwise.
451+ Box {
452+ Row(
453+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
454+ // node; the click label rides on `clickable` (onClickLabel) instead of
455+ // an explicit contentDescription, which would have SUPPRESSED the child
456+ // Texts and announced only "Change model and agent".
457+ modifier = Modifier
458+ .clickable(
459+ enabled = models.isNotEmpty(),
460+ role = Role.Button,
461+ onClickLabel = changeLabel,
462+ ) { showTitleMenu = true }
463+ .semantics(mergeDescendants = true) {},
464+ verticalAlignment = Alignment.CenterVertically,
465+ ) {
466+ Column(modifier = Modifier.weight(1f, fill = false)) {
467+ // maxLines=1 + Ellipsis so a long session title can't wrap and
468+ // push the top bar to multiple lines, shifting the whole layout.
469+ Text(
470+ sessionTitle ?: sessionLabel,
471+ maxLines = 1,
472+ overflow = TextOverflow.Ellipsis,
473+ )
474+ Text(
475+ subtitle,
476+ style = MaterialTheme.typography.labelSmall,
477+ color = MaterialTheme.colorScheme.onSurfaceVariant,
478+ maxLines = 1,
479+ overflow = TextOverflow.Ellipsis,
480+ )
481+ }
482+ // Visual affordance that the title is tappable; without it the
483+ // title is indistinguishable from plain text and the pickers are
484+ // effectively undiscoverable.
485+ if (models.isNotEmpty()) {
486+ Icon(
487+ Icons.Filled.KeyboardArrowDown,
488+ contentDescription = null,
489+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
490+ modifier = Modifier.size(20.dp),
491+ )
492+ }
493+ }
494+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
495+ DropdownMenuItem(
496+ text = { Text(stringResource(R.string.palette_switch_model)) },
497+ enabled = !modelsLoading || models.isNotEmpty(),
498+ onClick = { showTitleMenu = false; showModelPicker = true },
499+ )
500+ DropdownMenuItem(
501+ text = { Text(stringResource(R.string.palette_choose_agent)) },
502+ enabled = !agentsLoading || agents.isNotEmpty(),
503+ onClick = { showTitleMenu = false; showAgentPicker = true },
504+ )
505+ }
506+ }
507+ },
508+ navigationIcon = {
509+ IconButton(onClick = {
510+ if (running) showExitConfirm = true else onBack()
511+ }) {
512+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
513+ }
514+ },
515+ actions = {
516+ // At-a-glance run status in the top bar. When the user is scrolled
517+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
518+ // trailing "working…" row are off-screen, so a top-bar spinner is the
519+ // only signal the agent is still working.
520+ if (running) {
521+ val workingLabel = stringResource(R.string.working)
522+ CircularProgressIndicator(
523+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
524+ strokeWidth = 2.dp,
525+ )
526+ }
527+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
528+ // from REST. A recovery path when the stream silently drops and the
529+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
530+ // immediate tap feedback — the SSE reconnect may not visibly change
531+ // the connection state when already Connected, so without it the tap
532+ // appears to do nothing.
533+ val refreshLabel = stringResource(R.string.refresh)
534+ IconButton(
535+ onClick = { vm.refreshMessages() },
536+ enabled = activeConnection != null && !refreshing,
537+ ) {
538+ if (refreshing) {
539+ CircularProgressIndicator(
540+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
541+ strokeWidth = 2.dp,
542+ )
543+ } else {
544+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
545+ }
546+ }
547+ // Overflow menu consolidates the less-frequent actions (share,
548+ // commands, agent, model, rename, delete) so the top bar stays
549+ // scannable on narrow phones — previously 5 icons crowded the bar
550+ // alongside the back button and tappable title. Catalog-loading
551+ // spinners stay inline (next to the overflow) so a load state is
552+ // visible without opening the menu.
553+ val moreLabel = stringResource(R.string.more)
554+ val loadingLabel = stringResource(R.string.loading)
555+ val shareLabel = stringResource(R.string.share_conversation)
556+ val commandsLabel = stringResource(R.string.commands)
557+ val renameLabel = stringResource(R.string.rename_session_chat)
558+ val deleteLabel = stringResource(R.string.delete_session_chat)
559+ val createShareLabel = stringResource(R.string.create_share_link)
560+ val copyShareLabel = stringResource(R.string.copy_share_link)
561+ val stopShareLabel = stringResource(R.string.stop_sharing)
562+ val summarizeLabel = stringResource(R.string.summarize_conversation)
563+ val initLabel = stringResource(R.string.generate_agents_md)
564+ val shellLabel = stringResource(R.string.run_shell_command)
565+ Box {
566+ IconButton(onClick = { showOverflowMenu = true }) {
567+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
568+ }
569+ DropdownMenu(
570+ expanded = showOverflowMenu,
571+ onDismissRequest = { showOverflowMenu = false },
572+ ) {
573+ DropdownMenuItem(
574+ text = { Text(shareLabel) },
575+ enabled = hasMessages,
576+ onClick = {
577+ showOverflowMenu = false
578+ scope.launch {
579+ val md = withContext(Dispatchers.Default) {
580+ buildConversationMarkdown(vm.messages.value, sessionTitle)
581+ }
582+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
583+ type = "text/markdown"
584+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
585+ putExtra(android.content.Intent.EXTRA_TEXT, md)
586+ }
587+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
588+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
589+ }
590+ },
591+ )
592+ DropdownMenuItem(
593+ text = { Text(commandsLabel) },
594+ enabled = !commandsLoading || commands.isNotEmpty(),
595+ onClick = { showOverflowMenu = false; showCommandPicker = true },
596+ )
597+ androidx.compose.material3.HorizontalDivider()
598+ // Session sharing: create a public link, copy an existing one, or revoke it.
599+ if (shareUrl == null) {
600+ DropdownMenuItem(
601+ text = { Text(createShareLabel) },
602+ enabled = hasMessages,
603+ onClick = { showOverflowMenu = false; vm.shareSession() },
604+ )
605+ } else {
606+ DropdownMenuItem(
607+ text = { Text(copyShareLabel) },
608+ onClick = {
609+ showOverflowMenu = false
610+ shareUrl?.let {
611+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
612+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
613+ }
614+ },
615+ )
616+ DropdownMenuItem(
617+ text = { Text(stopShareLabel) },
618+ onClick = { showOverflowMenu = false; vm.unshareSession() },
619+ )
620+ }
621+ DropdownMenuItem(
622+ text = { Text(summarizeLabel) },
623+ enabled = hasMessages && !running,
624+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
625+ )
626+ DropdownMenuItem(
627+ text = { Text(initLabel) },
628+ enabled = !running,
629+ onClick = { showOverflowMenu = false; showInitConfirm = true },
630+ )
631+ DropdownMenuItem(
632+ text = { Text(shellLabel) },
633+ enabled = !running,
634+ onClick = { showOverflowMenu = false; showShellDialog = true },
635+ )
636+ androidx.compose.material3.HorizontalDivider()
637+ DropdownMenuItem(
638+ text = { Text(renameLabel) },
639+ onClick = { showOverflowMenu = false; showRenameDialog = true },
640+ )
641+ DropdownMenuItem(
642+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
643+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
644+ )
645+ }
646+ // While a catalog is initially loading (empty list + loading flag),
647+ // show a tiny inline spinner beside the overflow so the user can see
648+ // a load is in progress without opening the menu. Once loaded the
649+ // spinner disappears; the menu items are always enabled (tapping a
650+ // picker with no items shows the "no models/agents/commands" state).
651+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
652+ (agentsLoading && agents.isEmpty()) ||
653+ (modelsLoading && models.isEmpty())
654+ if (catalogLoading) {
655+ CircularProgressIndicator(
656+ Modifier
657+ .align(Alignment.TopEnd)
658+ .size(10.dp)
659+ .semantics { contentDescription = loadingLabel },
660+ strokeWidth = 1.dp,
661+ )
662+ }
663+ }
664+ },
665+ )
666+ },
667+ snackbarHost = { SnackbarHost(snackbar) },
668+ bottomBar = {
669+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
670+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
671+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
672+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
673+ Column {
674+ // Pinned above the composer so the agent's plan and progress stay visible
675+ // while scrolled up mid-run; renders nothing when there's no plan.
676+ TodoPlanBar(todoPlan)
677+ AnimatedVisibility(visible = reverted) {
678+ RevertBanner(onUndo = { vm.unrevert() })
679+ }
680+ AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
681+ OutboxBanner(
682+ count = queuedOffline.size,
683+ sending = outboxSending,
684+ onFlush = { vm.flushQueued() },
685+ onDiscard = { vm.discardAllQueued() },
686+ )
687+ }
688+ ChatInputBar(
689+ value = draft,
690+ onValueChange = vm::updateDraft,
691+ running = running,
692+ aborting = aborting,
693+ enabled = activeConnection != null,
694+ sendOnEnter = sendOnEnter,
695+ onSend = ::doSend,
696+ onAbort = { showStopConfirm = true },
697+ queuedFollowUp = queuedFollowUp,
698+ onQueueFollowUp = vm::queueFollowUp,
699+ onCancelQueue = { vm.queueFollowUp("") },
700+ focusRequester = inputFocusRequester,
701+ attachments = attachments,
702+ staging = stagingCount > 0,
703+ onRemoveAttachment = vm::removeAttachment,
704+ onPickPhoto = {
705+ photoPicker.launch(
706+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
707+ )
708+ },
709+ onPickFile = { filePicker.launch("*/*") },
710+ onCamera = { launchCamera() },
711+ onVoice = { launchVoice() },
712+ )
713+ }
714+ },
715+ ) { padding ->
716+ // Collect messages inside the content lambda so streaming token updates
717+ // recompose only this subtree, not the top bar / input bar / 20+ other
718+ // state reads in the ChatScreen body.
719+ val messages by vm.messages.collectAsStateWithLifecycle()
720+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
721+ val listState = rememberLazyListState()
722+ val contentScope = rememberCoroutineScope()
723+ val timeTick = rememberRelativeTimeTick()
724+ // Group messages by day and interleave date separators so a long conversation
725+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
726+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
727+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
728+ // the same list the LazyColumn renders (separators shift the indices vs. the
729+ // raw messages list, so scroll targets must be in listItems space).
730+ val todayLabel = stringResource(R.string.today)
731+ val yesterdayLabel = stringResource(R.string.yesterday)
732+ val listItems = remember(messages, todayLabel, yesterdayLabel) {
733+ buildMessageListItems(messages, todayLabel, yesterdayLabel)
734+ }
735+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
736+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
737+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
738+ // would capture the first composition's list — which is empty, since `messages`
739+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
740+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
741+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
742+ // whose value tracks the latest list.
743+ val currentListItems by rememberUpdatedState(listItems)
744+
745+ // New-content signal for the jump-to-latest FAB: set when content grows while the user
746+ // is scrolled away from the bottom, cleared once they return (see the collector below).
747+ var hasNewContent by remember { mutableStateOf(false) }
748+
749+ val isPinnedToBottom by remember {
750+ derivedStateOf {
751+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
752+ // When a run is active, the LazyColumn has one trailing "__typing"
753+ // item after the last list item. Account for it so "pinned to bottom"
754+ // includes the working indicator — otherwise the pin check targets
755+ // listItems.lastIndex, the typing row sits just below the viewport,
756+ // and the user never sees the progress indicator even when pinned.
757+ val items = currentListItems
758+ val effectiveLast = if (running) items.size else items.lastIndex
759+ lastVisible >= effectiveLast || items.isEmpty()
760+ }
761+ }
762+
763+ // Jump to the newest message once, when the conversation first loads. Guarded by a
764+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
765+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
766+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
767+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
768+ LaunchedEffect(listItems.isNotEmpty()) {
769+ if (listItems.isNotEmpty() && !didInitialScroll) {
770+ // When a run is active the LazyColumn has a trailing "__typing" row at
771+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
772+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
773+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
774+ didInitialScroll = true
775+ }
776+ }
777+
778+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
779+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
780+ // isPinnedToBottom check flips to false the instant you send — freezing
781+ // auto-scroll. If the user was pinned to the last item just before the run
782+ // began, bring the typing row into view so the pin (and streaming follow) is
783+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
784+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
785+ LaunchedEffect(running) {
786+ if (running && listItems.isNotEmpty()) {
787+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
788+ if (lastVisible >= listItems.lastIndex) {
789+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
790+ }
791+ }
792+ }
793+
794+ LaunchedEffect(Unit) {
795+ var prevSize = 0
796+ var prevLen = 0
797+ snapshotFlow {
798+ // Track list size + the streaming length of the last part so we auto-scroll
799+ // as content arrives, plus the pinned flag. A small data class with primitive
800+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
801+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
802+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
803+ // and tool output — not just TextPart — keeps a pinned view following a long
804+ // reasoning/tool block while it streams (previously it stalled at 0).
805+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
806+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
807+ }.collect { signal ->
808+ if (signal.pinned) {
809+ // Back at the bottom: clear the new-content badge.
810+ hasNewContent = false
811+ if (signal.size > 0) {
812+ // Scroll to the effective last index, including the trailing
813+ // "__typing" row when a run is active so the working indicator
814+ // is brought into view (not just the last message).
815+ val items = currentListItems
816+ val target = if (running) items.size else items.lastIndex
817+ listState.scrollToItem(target)
818+ }
819+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
820+ // Content arrived while scrolled up — badge the jump-to-latest FAB.
821+ hasNewContent = true
822+ }
823+ prevSize = signal.size
824+ prevLen = signal.lastTextLength
825+ }
826+ }
827+
828+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
829+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
830+ // content padding accounts for the bottomBar's raised height, so the message
831+ // list is already above the keyboard. Adding imePadding here would double-apply
832+ // the IME inset and push messages too far up.
833+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
834+ if (activeConnection == null) {
835+ Column(
836+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
837+ horizontalAlignment = Alignment.CenterHorizontally,
838+ ) {
839+ Text(
840+ stringResource(R.string.not_connected),
841+ color = MaterialTheme.colorScheme.error,
842+ )
843+ Spacer(Modifier.size(12.dp))
844+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
845+ if (reconnecting) {
846+ CircularProgressIndicator(
847+ Modifier.size(20.dp),
848+ color = MaterialTheme.colorScheme.onPrimary,
849+ strokeWidth = 2.dp,
850+ )
851+ } else {
852+ Text(stringResource(R.string.reconnect))
853+ }
854+ }
855+ }
856+ } else {
857+ ConnectionBanner(
858+ state = connectionState,
859+ modifier = Modifier.align(Alignment.TopCenter),
860+ isOnline = isOnline,
861+ // On a hard failure, retry by forcing an SSE reconnect (which
862+ // re-seeds from REST). refreshMessages is the right recovery path
863+ // when the connection is present but the stream died; reconnect()
864+ // is the path when the whole connection is gone (handled by the
865+ // separate "Not connected" state below).
866+ onRetry = { vm.refreshMessages() },
867+ )
868+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
869+ // recovery is a swipe away everywhere — not just when the message list is
870+ // populated. Previously PTR was only around the populated list, leaving the
871+ // error/loading states reachable only via a button tap.
872+ PullToRefreshBox(
873+ isRefreshing = refreshing,
874+ onRefresh = { vm.refreshMessages() },
875+ // Cap width and center on large screens for readability — full-width
876+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
877+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
878+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
879+ ) {
880+ // Reserve top space when the banner is visible so it doesn't overlap the
881+ // first message / state content.
882+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
883+ val topPad = if (bannerVisible) 44.dp else 16.dp
884+ if (loading && messages.isEmpty()) {
885+ val loadingLabel = stringResource(R.string.loading)
886+ CircularProgressIndicator(
887+ Modifier.align(Alignment.Center).padding(top = topPad),
888+ strokeWidth = 2.dp,
889+ )
890+ Box(modifier = Modifier.semantics { contentDescription = loadingLabel })
891+ } else if (loadError && messages.isEmpty()) {
892+ // A failed load with nothing to show. Distinct from the empty
893+ // conversation state below — the conversation isn't empty, it
894+ // failed to load, and offering "Start a conversation" here is
895+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
896+ Column(
897+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
898+ horizontalAlignment = Alignment.CenterHorizontally,
899+ ) {
900+ Text(
901+ stringResource(R.string.load_messages_failed),
902+ color = MaterialTheme.colorScheme.error,
903+ )
904+ Spacer(Modifier.size(12.dp))
905+ Button(onClick = { vm.refreshMessages() }) {
906+ Text(stringResource(R.string.retry))
907+ }
908+ }
909+ } else if (messages.isEmpty() && running) {
910+ // A run just started but no parts have arrived yet — the empty
911+ // list with only the trailing "working…" row looks broken, so
912+ // surface a clear starting state until the first part streams in.
913+ val workingText = stringResource(R.string.working)
914+ Column(
915+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
916+ horizontalAlignment = Alignment.CenterHorizontally,
917+ ) {
918+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
919+ Spacer(Modifier.size(12.dp))
920+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
921+ }
922+ } else if (messages.isEmpty()) {
923+ EmptyConversation(
924+ onSuggestion = {
925+ vm.updateDraft(it)
926+ // Focus the input so the user can edit the suggestion before
927+ // sending, instead of having to manually tap the field.
928+ runCatching { inputFocusRequester.requestFocus() }
929+ },
930+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
931+ )
932+ } else {
933+ val lastMessageId = messages.lastOrNull()?.info?.id
934+ // Text-to-speech for reading assistant replies aloud; shuts down when the
935+ // message list leaves composition.
936+ val tts = rememberTtsController()
937+ val speakingMessageId by tts.speakingId
938+ LazyColumn(
939+ state = listState,
940+ modifier = Modifier.fillMaxSize(),
941+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
942+ // never floats over the last message. Top padding grows when the
943+ // connection banner is visible so it doesn't overlap the first message.
944+ contentPadding = PaddingValues(
945+ start = 16.dp,
946+ top = topPad,
947+ end = 16.dp,
948+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
949+ ),
950+ verticalArrangement = Arrangement.spacedBy(16.dp),
951+ ) {
952+ items(
953+ items = listItems,
954+ key = { it.key },
955+ contentType = { it.contentType },
956+ ) { item ->
957+ // Default placement animation so inserted/moved rows glide in. Kept to the
958+ // default (no heavy fade spec) so a streaming message growing in place
959+ // doesn't animate on every token.
960+ Box(Modifier.animateItem()) {
961+ when (item) {
962+ is MessageListItem.Separator -> DateSeparator(item.label)
963+ is MessageListItem.Message -> {
964+ val message = item.message
965+ // Only the last (streaming) message needs isRunning — it drives the
966+ // reasoning-block spinner. Passing the live flag to every bubble
967+ // makes all visible messages recompose whenever a run starts or stops.
968+ val modelLabel = remember(message.info, models) {
969+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
970+ ?.let { resolveModelLabel(it, models) }
971+ }
972+ MessageBubble(
973+ message,
974+ isRunning = running && message.info.id == lastMessageId,
975+ imageContext = imageContext,
976+ modelLabel = modelLabel,
977+ onOpenFile = onOpenFile,
978+ onRevert = { vm.revertTo(message.info.id) },
979+ onEdit = { text ->
980+ // editMessage reverts to before this message (hiding it and
981+ // everything after); the revert banner surfaces the rewind
982+ // with an Undo. Focus + scroll the composer into view like the
983+ // Quote action so the prefilled draft isn't off-screen.
984+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
985+ vm.editMessage(message.info.id, text)
986+ runCatching { inputFocusRequester.requestFocus() }
987+ contentScope.launch {
988+ runCatchingCancellable {
989+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
990+ }
991+ }
992+ },
993+ onSpeak = { text -> tts.toggle(message.info.id, text) },
994+ isSpeaking = message.info.id == speakingMessageId,
995+ onQuote = { text ->
996+ vm.quoteReply(text)
997+ runCatching { inputFocusRequester.requestFocus() }
998+ },
999+ onBranch = { text -> vm.branchFrom(text) },
1000+ sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1001+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1002+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1003+ },
1004+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1005+ )
1006+ }
1007+ }
1008+ }
1009+ }
1010+ if (running) {
1011+ item(key = "__typing") {
1012+ val workingText = stringResource(R.string.working)
1013+ Row(
1014+ verticalAlignment = Alignment.CenterVertically,
1015+ modifier = Modifier.semantics {
1016+ contentDescription = workingText
1017+ },
1018+ ) {
1019+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1020+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1021+ }
1022+ }
1023+ }
1024+ }
1025+ }
1026+ }
1027+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1028+ AnimatedVisibility(
1029+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1030+ modifier = Modifier.align(Alignment.BottomEnd),
1031+ ) {
1032+ // Badge the FAB when new content arrived while the user was scrolled up, so
1033+ // they know there's something new to jump to (cleared once back at bottom).
1034+ BadgedBox(
1035+ badge = {
1036+ if (hasNewContent) {
1037+ val newContentLabel = stringResource(R.string.new_messages)
1038+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1039+ }
1040+ },
1041+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1042+ ) {
1043+ ExtendedFloatingActionButton(
1044+ onClick = {
1045+ hasNewContent = false
1046+ if (listItems.isNotEmpty()) {
1047+ // Scroll to the effective last index, including the
1048+ // trailing "__typing" row when a run is active.
1049+ val target = if (running) listItems.size else listItems.lastIndex
1050+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1051+ }
1052+ },
1053+ // contentDescription null: the visible "Latest" text already labels
1054+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1055+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1056+ text = { Text(stringResource(R.string.latest)) },
1057+ )
1058+ }
1059+ }
1060+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1061+ // user has scrolled down past the first few messages. Symmetric to the
1062+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1063+ val scrolledDown by remember {
1064+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1065+ }
1066+ AnimatedVisibility(
1067+ visible = scrolledDown && listItems.size > 4,
1068+ modifier = Modifier.align(Alignment.BottomStart),
1069+ ) {
1070+ SmallFloatingActionButton(
1071+ onClick = {
1072+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1073+ },
1074+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1075+ ) {
1076+ Icon(
1077+ Icons.Filled.KeyboardArrowUp,
1078+ contentDescription = stringResource(R.string.scroll_to_top),
1079+ )
1080+ }
1081+ }
1082+ }
1083+ }
1084+ }
1085+ }
1086+
1087+ if (showExitConfirm) {
1088+ AlertDialog(
1089+ onDismissRequest = { showExitConfirm = false },
1090+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1091+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1092+ confirmButton = {
1093+ TextButton(onClick = {
1094+ showExitConfirm = false
1095+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1096+ vm.abort()
1097+ onBack()
1098+ }) { Text(stringResource(R.string.stop_and_exit)) }
1099+ },
1100+ dismissButton = {
1101+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1102+ },
1103+ )
1104+ }
1105+
1106+ if (showStopConfirm) {
1107+ AlertDialog(
1108+ onDismissRequest = { showStopConfirm = false },
1109+ title = { Text(stringResource(R.string.stop_run_title)) },
1110+ text = { Text(stringResource(R.string.stop_run_text)) },
1111+ confirmButton = {
1112+ TextButton(onClick = {
1113+ showStopConfirm = false
1114+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1115+ vm.abort()
1116+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1117+ },
1118+ dismissButton = {
1119+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1120+ },
1121+ )
1122+ }
1123+
1124+ if (showSummarizeConfirm) {
1125+ AlertDialog(
1126+ onDismissRequest = { showSummarizeConfirm = false },
1127+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
1128+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
1129+ confirmButton = {
1130+ TextButton(onClick = {
1131+ showSummarizeConfirm = false
1132+ vm.summarize()
1133+ }) { Text(stringResource(R.string.action_continue)) }
1134+ },
1135+ dismissButton = {
1136+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1137+ },
1138+ )
1139+ }
1140+
1141+ if (showInitConfirm) {
1142+ AlertDialog(
1143+ onDismissRequest = { showInitConfirm = false },
1144+ title = { Text(stringResource(R.string.init_confirm_title)) },
1145+ text = { Text(stringResource(R.string.init_confirm_text)) },
1146+ confirmButton = {
1147+ TextButton(onClick = {
1148+ showInitConfirm = false
1149+ vm.initProject()
1150+ }) { Text(stringResource(R.string.action_continue)) }
1151+ },
1152+ dismissButton = {
1153+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1154+ },
1155+ )
1156+ }
1157+
1158+ if (showRenameDialog) {
1159+ RenameSessionChatDialog(
1160+ initialTitle = sessionTitle ?: "",
1161+ onDismiss = { showRenameDialog = false },
1162+ onConfirm = { newName ->
1163+ showRenameDialog = false
1164+ vm.renameSession(newName)
1165+ },
1166+ )
1167+ }
1168+
1169+ if (showDeleteDialog) {
1170+ AlertDialog(
1171+ onDismissRequest = { showDeleteDialog = false },
1172+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1173+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1174+ confirmButton = {
1175+ TextButton(onClick = {
1176+ showDeleteDialog = false
1177+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1178+ vm.deleteSession()
1179+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1180+ },
1181+ dismissButton = {
1182+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1183+ },
1184+ )
1185+ }
1186+
1187+ if (showShellDialog) {
1188+ ShellCommandDialog(
1189+ onDismiss = { showShellDialog = false },
1190+ onRun = { cmd ->
1191+ showShellDialog = false
1192+ vm.runShell(cmd)
1193+ },
1194+ )
1195+ }
1196+
1197+ if (showModelPicker) {
1198+ ModelPickerSheet(
1199+ options = models,
1200+ selected = selectedModel,
1201+ loading = modelsLoading,
1202+ error = modelsError,
1203+ onSelect = { vm.selectModel(it) },
1204+ onRetry = { vm.reloadModels() },
1205+ onDismiss = { showModelPicker = false },
1206+ )
1207+ }
1208+
1209+ if (showAgentPicker) {
1210+ AgentPickerSheet(
1211+ agents = agents,
1212+ selected = selectedAgent,
1213+ loading = agentsLoading,
1214+ error = agentsError,
1215+ onSelect = { vm.selectAgent(it?.name) },
1216+ onRetry = { vm.reloadAgents() },
1217+ onDismiss = { showAgentPicker = false },
1218+ )
1219+ }
1220+
1221+ if (showCommandPicker) {
1222+ CommandPickerSheet(
1223+ commands = commands,
1224+ loading = commandsLoading,
1225+ error = commandsError,
1226+ onSelect = { vm.runCommand(it) },
1227+ onRetry = { vm.reloadCommands() },
1228+ onDismiss = { showCommandPicker = false },
1229+ )
1230+ }
1231+
1232+ pendingPermission?.let { permission ->
1233+ PermissionDialog(
1234+ permission = permission,
1235+ position = permissionProgress.position,
1236+ total = permissionProgress.total,
1237+ onRespond = { response -> vm.respondPermission(permission, response) },
1238+ )
1239+ }
1240+
1241+ if (showPalette) {
1242+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1243+ }
1244+}
1245+
1246+@Composable
1247+private fun ChatInputBar(
1248+ value: String,
1249+ onValueChange: (String) -> Unit,
1250+ running: Boolean,
1251+ aborting: Boolean,
1252+ enabled: Boolean,
1253+ sendOnEnter: Boolean,
1254+ onSend: () -> Unit,
1255+ onAbort: () -> Unit,
1256+ queuedFollowUp: String?,
1257+ onQueueFollowUp: (String) -> Unit,
1258+ onCancelQueue: () -> Unit,
1259+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1260+ attachments: List<PendingAttachment>,
1261+ staging: Boolean,
1262+ onRemoveAttachment: (String) -> Unit,
1263+ onPickPhoto: () -> Unit,
1264+ onPickFile: () -> Unit,
1265+ onCamera: () -> Unit,
1266+ onVoice: () -> Unit,
1267+) {
1268+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1269+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1270+ // Full-screen editor state: opened when the user wants more space for a long prompt.
1271+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1272+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1273+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1274+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1275+ // user sees their message will be sent when the run finishes, and can cancel.
1276+ if (queuedFollowUp != null) {
1277+ Row(
1278+ modifier = Modifier
1279+ .fillMaxWidth()
1280+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1281+ verticalAlignment = Alignment.CenterVertically,
1282+ ) {
1283+ Column(modifier = Modifier.weight(1f)) {
1284+ Text(
1285+ stringResource(R.string.queued),
1286+ style = MaterialTheme.typography.labelSmall,
1287+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1288+ )
1289+ Text(
1290+ queuedFollowUp,
1291+ style = MaterialTheme.typography.bodySmall,
1292+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1293+ maxLines = 1,
1294+ overflow = TextOverflow.Ellipsis,
1295+ )
1296+ }
1297+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1298+ Text(stringResource(R.string.cancel))
1299+ }
1300+ }
1301+ }
1302+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1303+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1304+ Row(
1305+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1306+ verticalAlignment = Alignment.Bottom,
1307+ ) {
1308+ // Attach menu: photo picker, camera, or any file.
1309+ var showAttachMenu by remember { mutableStateOf(false) }
1310+ Box {
1311+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1312+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1313+ }
1314+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1315+ DropdownMenuItem(
1316+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1317+ text = { Text(stringResource(R.string.attach_photo)) },
1318+ onClick = { showAttachMenu = false; onPickPhoto() },
1319+ )
1320+ DropdownMenuItem(
1321+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1322+ text = { Text(stringResource(R.string.attach_camera)) },
1323+ onClick = { showAttachMenu = false; onCamera() },
1324+ )
1325+ DropdownMenuItem(
1326+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1327+ text = { Text(stringResource(R.string.attach_file)) },
1328+ onClick = { showAttachMenu = false; onPickFile() },
1329+ )
1330+ }
1331+ }
1332+ // Voice dictation: appends recognized speech to the draft.
1333+ IconButton(onClick = onVoice, enabled = enabled) {
1334+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1335+ }
1336+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1337+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1338+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1339+ }
1340+ OutlinedTextField(
1341+ value = value,
1342+ onValueChange = { v ->
1343+ // Cap input length so a huge paste can't stall the UI. Shares are
1344+ // capped separately in MainActivity; this guards typed/pasted drafts.
1345+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1346+ },
1347+ modifier = Modifier
1348+ .weight(1f)
1349+ .focusRequester(focusRequester)
1350+ .testTag("chat_input")
1351+ .onPreviewKeyEvent { event ->
1352+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1353+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1354+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1355+ val send = enterShouldSend(
1356+ enabled = enabled,
1357+ hasContent = hasContent,
1358+ sendOnEnter = sendOnEnter,
1359+ shift = event.isShiftPressed,
1360+ ctrl = event.isCtrlPressed,
1361+ )
1362+ if (send) {
1363+ if (running) onQueueFollowUp(value) else onSend()
1364+ true
1365+ } else {
1366+ false
1367+ }
1368+ },
1369+ // While a run is active a typed message only queues (sends after the run), so
1370+ // the placeholder says so instead of the plain "Message…".
1371+ placeholder = {
1372+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1373+ },
1374+ enabled = enabled,
1375+ maxLines = 6,
1376+ // Show a "N / max" countdown once the draft crosses a high fraction of
1377+ // the cap, so the user knows a paste is about to be truncated instead
1378+ // of being silently cut off. Hidden for normal short prompts to avoid
1379+ // clutter under a typical one-line message.
1380+ supportingText = {
1381+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1382+ if (value.length >= threshold) {
1383+ Text(
1384+ stringResource(
1385+ R.string.draft_chars_remaining,
1386+ NetworkConfig.maxDraftLengthChars - value.length,
1387+ NetworkConfig.maxDraftLengthChars,
1388+ ),
1389+ style = MaterialTheme.typography.labelSmall,
1390+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1391+ else MaterialTheme.colorScheme.onSurfaceVariant,
1392+ )
1393+ }
1394+ },
1395+ keyboardOptions = KeyboardOptions(
1396+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
1397+ // keyboard shows a send key — matching the setting's intent and
1398+ // giving touch-only users a keyboard send affordance. When off,
1399+ // ImeAction.Default keeps the enter/newline key for multi-line input.
1400+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1401+ capitalization = KeyboardCapitalization.Sentences,
1402+ ),
1403+ keyboardActions = KeyboardActions(
1404+ onSend = {
1405+ if (enabled && hasContent) onSend()
1406+ },
1407+ ),
1408+ )
1409+ ComposerTrailingButton(
1410+ running = running,
1411+ aborting = aborting,
1412+ canSend = enabled && hasContent,
1413+ canQueue = enabled && value.isNotBlank(),
1414+ onSend = onSend,
1415+ onAbort = onAbort,
1416+ onQueue = { onQueueFollowUp(value) },
1417+ )
1418+ }
1419+ }
1420+ if (showFullScreenEditor) {
1421+ FullScreenEditor(
1422+ value = value,
1423+ onValueChange = onValueChange,
1424+ onDismiss = { showFullScreenEditor = false },
1425+ onSend = { showFullScreenEditor = false; onSend() },
1426+ canSend = enabled && hasContent,
1427+ )
1428+ }
1429+ }
1430+}
1431+
1432+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1433+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1434+@OptIn(ExperimentalMaterial3Api::class)
1435+@Composable
1436+private fun FullScreenEditor(
1437+ value: String,
1438+ onValueChange: (String) -> Unit,
1439+ onDismiss: () -> Unit,
1440+ onSend: () -> Unit,
1441+ canSend: Boolean,
1442+) {
1443+ androidx.compose.ui.window.Dialog(
1444+ onDismissRequest = onDismiss,
1445+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1446+ ) {
1447+ Scaffold(
1448+ topBar = {
1449+ androidx.compose.material3.TopAppBar(
1450+ title = { Text(stringResource(R.string.message_placeholder)) },
1451+ navigationIcon = {
1452+ androidx.compose.material3.TextButton(onClick = onDismiss) {
1453+ Text(stringResource(R.string.collapse_editor))
1454+ }
1455+ },
1456+ )
1457+ },
1458+ bottomBar = {
1459+ Surface(tonalElevation = 3.dp) {
1460+ Row(
1461+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1462+ horizontalArrangement = Arrangement.End,
1463+ ) {
1464+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1465+ Text(stringResource(R.string.send))
1466+ }
1467+ }
1468+ }
1469+ },
1470+ ) { padding ->
1471+ OutlinedTextField(
1472+ value = value,
1473+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1474+ modifier = Modifier.fillMaxSize().padding(padding),
1475+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
1476+ maxLines = Int.MAX_VALUE,
1477+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1478+ )
1479+ }
1480+ }
1481+}
1482+
1483+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1484+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1485+private fun enterShouldSend(
1486+ enabled: Boolean,
1487+ hasContent: Boolean,
1488+ sendOnEnter: Boolean,
1489+ shift: Boolean,
1490+ ctrl: Boolean,
1491+): Boolean = when {
1492+ !enabled || !hasContent -> false
1493+ sendOnEnter -> !shift
1494+ else -> ctrl
1495+}
1496+
1497+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1498+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1499+ * [ChatInputBar] stays under the complexity threshold. */
1500+@Composable
1501+private fun ComposerTrailingButton(
1502+ running: Boolean,
1503+ aborting: Boolean,
1504+ canSend: Boolean,
1505+ canQueue: Boolean,
1506+ onSend: () -> Unit,
1507+ onAbort: () -> Unit,
1508+ onQueue: () -> Unit,
1509+) {
1510+ if (running) {
1511+ Row(verticalAlignment = Alignment.CenterVertically) {
1512+ // While a run is active the trailing action is Stop, so the only send affordance is
1513+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1514+ // That leaves a touch-only user with the setting off no way to queue a follow-up
1515+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1516+ // there's typed TEXT so queuing is always reachable, without changing the user's
1517+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1518+ // canSend, which is also true for an attachment-only composer — because queuing "" just
1519+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1520+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1521+ if (canQueue) {
1522+ IconButton(
1523+ onClick = onQueue,
1524+ modifier = Modifier.testTag("queue_button"),
1525+ ) {
1526+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1527+ // icon (which can be read as "snooze" or "later"), and isn't confused with
1528+ // the Send action sitting right beside the Stop button.
1529+ Icon(
1530+ Icons.AutoMirrored.Filled.PlaylistAdd,
1531+ contentDescription = stringResource(R.string.queue_followup),
1532+ )
1533+ }
1534+ }
1535+ // Show a spinner while the abort REST call is in flight so the user sees the stop
1536+ // was sent, and disable to prevent a double-tap.
1537+ IconButton(
1538+ onClick = onAbort,
1539+ enabled = !aborting,
1540+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1541+ ) {
1542+ if (aborting) {
1543+ val stopLabel = stringResource(R.string.stop)
1544+ CircularProgressIndicator(
1545+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1546+ strokeWidth = 2.dp,
1547+ )
1548+ } else {
1549+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1550+ }
1551+ }
1552+ }
1553+ } else {
1554+ IconButton(
1555+ onClick = onSend,
1556+ enabled = canSend,
1557+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1558+ ) {
1559+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1560+ }
1561+ }
1562+}
1563+
1564+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1565+@Composable
1566+private fun EmptyConversation(
1567+ onSuggestion: (String) -> Unit,
1568+ modifier: Modifier = Modifier,
1569+) {
1570+ // A few example prompts so a first-time user has a one-tap path to their first
1571+ // message instead of staring at a blank input. Tapping a chip fills the draft
1572+ // (without sending) so the user can edit it before sending.
1573+ val suggestions = remember {
1574+ listOf(
1575+ R.string.empty_chat_suggest_1,
1576+ R.string.empty_chat_suggest_2,
1577+ R.string.empty_chat_suggest_3,
1578+ )
1579+ }
1580+ Column(
1581+ modifier = modifier.padding(32.dp),
1582+ horizontalAlignment = Alignment.CenterHorizontally,
1583+ ) {
1584+ Icon(
1585+ Icons.Filled.AutoAwesome,
1586+ contentDescription = null,
1587+ modifier = Modifier.size(48.dp),
1588+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1589+ )
1590+ Spacer(Modifier.size(16.dp))
1591+ Text(
1592+ stringResource(R.string.empty_chat_title),
1593+ style = MaterialTheme.typography.titleMedium,
1594+ )
1595+ Spacer(Modifier.size(8.dp))
1596+ Text(
1597+ stringResource(R.string.empty_chat_hint),
1598+ style = MaterialTheme.typography.bodyMedium,
1599+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1600+ )
1601+ Spacer(Modifier.size(20.dp))
1602+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1603+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
1604+ FlowRow(
1605+ modifier = Modifier.fillMaxWidth(),
1606+ horizontalArrangement = Arrangement.spacedBy(8.dp),
1607+ verticalArrangement = Arrangement.spacedBy(8.dp),
1608+ ) {
1609+ suggestions.forEach { resId ->
1610+ val text = stringResource(resId)
1611+ androidx.compose.material3.AssistChip(
1612+ onClick = { onSuggestion(text) },
1613+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1614+ )
1615+ }
1616+ }
1617+ }
1618+}
1619+
1620+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1621+@Composable
1622+private fun RevertBanner(onUndo: () -> Unit) {
1623+ Surface(
1624+ color = MaterialTheme.colorScheme.tertiaryContainer,
1625+ tonalElevation = 2.dp,
1626+ modifier = Modifier.fillMaxWidth(),
1627+ ) {
1628+ Row(
1629+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1630+ verticalAlignment = Alignment.CenterVertically,
1631+ horizontalArrangement = Arrangement.SpaceBetween,
1632+ ) {
1633+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1634+ Icon(
1635+ Icons.Filled.Restore,
1636+ contentDescription = null,
1637+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
1638+ modifier = Modifier.size(18.dp),
1639+ )
1640+ Text(
1641+ stringResource(R.string.reverted_banner),
1642+ style = MaterialTheme.typography.bodySmall,
1643+ color = MaterialTheme.colorScheme.onTertiaryContainer,
1644+ modifier = Modifier.padding(start = 8.dp),
1645+ )
1646+ }
1647+ TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1648+ }
1649+ }
1650+}
1651+
1652+/** A banner shown while messages composed offline are queued in the outbox, with a
1653+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1654+@Composable
1655+private fun OutboxBanner(
1656+ count: Int,
1657+ sending: Boolean,
1658+ onFlush: () -> Unit,
1659+ onDiscard: () -> Unit,
1660+) {
1661+ Surface(
1662+ color = MaterialTheme.colorScheme.secondaryContainer,
1663+ tonalElevation = 2.dp,
1664+ modifier = Modifier.fillMaxWidth(),
1665+ ) {
1666+ Row(
1667+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1668+ verticalAlignment = Alignment.CenterVertically,
1669+ horizontalArrangement = Arrangement.SpaceBetween,
1670+ ) {
1671+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1672+ if (sending) {
1673+ CircularProgressIndicator(
1674+ Modifier.size(16.dp),
1675+ strokeWidth = 2.dp,
1676+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1677+ )
1678+ Spacer(Modifier.size(8.dp))
1679+ }
1680+ Text(
1681+ if (sending) {
1682+ stringResource(R.string.outbox_sending)
1683+ } else {
1684+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1685+ stringResource(res, count)
1686+ },
1687+ style = MaterialTheme.typography.bodySmall,
1688+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1689+ )
1690+ }
1691+ if (!sending) {
1692+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1693+ TextButton(onClick = onDiscard) {
1694+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1695+ }
1696+ }
1697+ }
1698+ }
1699+}
1700+
1701+/** Prompt for a one-off shell command to run in the session's worktree. */
1702+@Composable
1703+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1704+ var command by rememberSaveable { mutableStateOf("") }
1705+ AlertDialog(
1706+ onDismissRequest = onDismiss,
1707+ title = { Text(stringResource(R.string.run_shell_command)) },
1708+ text = {
1709+ OutlinedTextField(
1710+ value = command,
1711+ onValueChange = { command = it },
1712+ modifier = Modifier.fillMaxWidth(),
1713+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1714+ label = { Text(stringResource(R.string.shell_command_label)) },
1715+ singleLine = true,
1716+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1717+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1718+ )
1719+ },
1720+ confirmButton = {
1721+ TextButton(
1722+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1723+ enabled = command.isNotBlank(),
1724+ ) { Text(stringResource(R.string.run)) }
1725+ },
1726+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1727+ )
1728+}
1729+
1730+/**
1731+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1732+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1733+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
1734+ */
1735+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1736+
1737+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1738+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1739+ * streaming, not just plain assistant text. O(1). */
1740+private fun streamingContentLength(part: Part?): Int = when (part) {
1741+ is TextPart -> part.text.length
1742+ is ReasoningPart -> part.text.length
1743+ is ToolPart -> when (val st = part.state) {
1744+ is ToolCompleted -> st.output?.length ?: 0
1745+ is ToolError -> st.error?.length ?: 0
1746+ is ToolRunning -> st.title?.length ?: 0
1747+ else -> 0
1748+ }
1749+ else -> 0
1750+}
1751+
1752+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1753+ * dialog but lives in the chat screen so the user can rename without backing out to
1754+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
1755+@Composable
1756+private fun RenameSessionChatDialog(
1757+ initialTitle: String,
1758+ onDismiss: () -> Unit,
1759+ onConfirm: (String) -> Unit,
1760+) {
1761+ // Seed the field once (no key input) so a later external title change — e.g. opencode
1762+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1763+ // doesn't re-initialize the box and discard the user's in-progress edit.
1764+ var title by rememberSaveable { mutableStateOf(initialTitle) }
1765+ AlertDialog(
1766+ onDismissRequest = onDismiss,
1767+ title = { Text(stringResource(R.string.rename_session_chat)) },
1768+ text = {
1769+ OutlinedTextField(
1770+ value = title,
1771+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1772+ modifier = Modifier.fillMaxWidth(),
1773+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
1774+ label = { Text(stringResource(R.string.rename_session_chat)) },
1775+ singleLine = true,
1776+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1777+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1778+ )
1779+ },
1780+ confirmButton = {
1781+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1782+ Text(stringResource(R.string.save))
1783+ }
1784+ },
1785+ dismissButton = {
1786+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1787+ },
1788+ )
1789+}
1790+
1791+/**
1792+ * A single item in the chat message list — either a [Message] bubble or a day
1793+ * [Separator] inserted before the first message of a new day. The separator shifts
1794+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1795+ * the [List] of these items (not `messages.size`/`lastIndex`).
1796+ */
1797+private sealed interface MessageListItem {
1798+ val key: Any
1799+ val contentType: Any
1800+
1801+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1802+ override val contentType: Any get() = message.info::class
1803+ }
1804+
1805+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1806+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1807+ // can share a label (e.g. an untimestamped message — empty label — between two
1808+ // same-day messages, or two untimestamped groups), and a label-only key would
1809+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1810+ // stable for a given message ordering so slots aren't needlessly recreated.
1811+ override val key: Any get() = "sep_${ordinal}_$label"
1812+ // Separators share a contentType so the LazyColumn can recycle their slots.
1813+ override val contentType: Any get() = "separator"
1814+ }
1815+}
1816+
1817+/**
1818+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1819+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1820+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1821+ * Messages with no timestamp are grouped under an empty-label separator only if they
1822+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
1823+ *
1824+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1825+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1826+ * labels; older days fall back to a locale-stable medium-date format.
1827+ */
1828+private fun buildMessageListItems(
1829+ messages: List<MessageWithParts>,
1830+ todayLabel: String,
1831+ yesterdayLabel: String,
1832+): List<MessageListItem> {
1833+ if (messages.isEmpty()) return emptyList()
1834+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1835+ val dateFmt = mediumDateFormat()
1836+ val result = ArrayList<MessageListItem>(messages.size + 4)
1837+ val seenKeys = HashSet<String>(messages.size * 2)
1838+ var lastDayKey: String? = null
1839+ var sepOrdinal = 0
1840+ var emptyIdOrdinal = 0
1841+ var first = true
1842+ for (message in messages) {
1843+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1844+ val dayKey = ts?.let { dayKey(it) } ?: ""
1845+ // Emit a separator before the very first message (so a leading un-timestamped message
1846+ // still gets the first divider, empty label and all), and thereafter only when crossing
1847+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1848+ // neither emits its own separator nor resets the day — otherwise a following same-day
1849+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1850+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1851+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1852+ }
1853+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
1854+ first = false
1855+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1856+ // empty id — and the reducer intentionally keeps several such messages as distinct
1857+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
1858+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1859+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1860+ if (!seenKeys.add(key)) {
1861+ var suffix = 1
1862+ while (!seenKeys.add("$key#$suffix")) suffix++
1863+ key = "$key#$suffix"
1864+ }
1865+ result.add(MessageListItem.Message(message, key))
1866+ }
1867+ return result
1868+}
1869+
1870+/**
1871+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1872+ *
1873+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1874+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
1875+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1876+ * every message on every token. Message timestamps are immutable once assigned, so we
1877+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1878+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1879+ * thread during composition, so the coarse lock is uncontended.
1880+ */
1881+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1882+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1883+}
1884+
1885+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1886+ dayKeyCache.getOrPut(epochMillis) {
1887+ java.time.Instant.ofEpochMilli(epochMillis)
1888+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1889+ }
1890+}
1891+
1892+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1893+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1894+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1895+private var cachedDateFmt: java.text.DateFormat? = null
1896+private var cachedDateFmtLocale: java.util.Locale? = null
1897+
1898+private fun mediumDateFormat(): java.text.DateFormat {
1899+ val locale = java.util.Locale.getDefault()
1900+ val existing = cachedDateFmt
1901+ if (existing != null && cachedDateFmtLocale == locale) return existing
1902+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1903+ cachedDateFmt = it
1904+ cachedDateFmtLocale = locale
1905+ }
1906+}
1907+
1908+/**
1909+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1910+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1911+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1912+ * messages.
1913+ */
1914+private fun dayLabel(
1915+ dayKey: String,
1916+ ts: Long,
1917+ today: java.time.LocalDate,
1918+ todayLabel: String,
1919+ yesterdayLabel: String,
1920+ dateFmt: java.text.DateFormat,
1921+): String {
1922+ if (dayKey.isEmpty()) return ""
1923+ val epochDay = dayKey.toLongOrNull() ?: return ""
1924+ val date = java.time.LocalDate.ofEpochDay(epochDay)
1925+ return when {
1926+ date == today -> todayLabel
1927+ date == today.minusDays(1) -> yesterdayLabel
1928+ else -> dateFmt.format(java.util.Date(ts))
1929+ }
1930+}
1931+
1932+/**
1933+ * A centered day divider in the message list. Renders nothing for an empty label
1934+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1935+ */
1936+@Composable
1937+private fun DateSeparator(label: String) {
1938+ if (label.isBlank()) return
1939+ Row(
1940+ modifier = Modifier.fillMaxWidth(),
1941+ horizontalArrangement = Arrangement.Center,
1942+ ) {
1943+ Surface(
1944+ color = MaterialTheme.colorScheme.surfaceVariant,
1945+ shape = MaterialTheme.shapes.small,
1946+ ) {
1947+ Text(
1948+ label,
1949+ style = MaterialTheme.typography.labelSmall,
1950+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1951+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
1952+ )
1953+ }
1954+ }
1955+}