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