@@ -0,0 +1,2696 @@
1+@file:Suppress("TooManyFunctions")
2+
3+package soy.iko.opencode.ui.chat
4+
5+import android.app.Activity
6+import android.content.Intent
7+import android.net.Uri
8+import android.speech.RecognizerIntent
9+import androidx.activity.compose.BackHandler
10+import androidx.activity.compose.rememberLauncherForActivityResult
11+import androidx.activity.result.PickVisualMediaRequest
12+import androidx.activity.result.contract.ActivityResultContracts
13+import androidx.compose.animation.AnimatedVisibility
14+import androidx.compose.animation.core.RepeatMode
15+import androidx.compose.animation.core.animateFloat
16+import androidx.compose.animation.core.infiniteRepeatable
17+import androidx.compose.animation.core.rememberInfiniteTransition
18+import androidx.compose.animation.core.tween
19+import androidx.compose.foundation.background
20+import androidx.compose.foundation.clickable
21+import androidx.compose.foundation.content.contentReceiver
22+import androidx.compose.foundation.layout.Arrangement
23+import androidx.compose.foundation.layout.Box
24+import androidx.compose.foundation.layout.Column
25+import androidx.compose.foundation.layout.FlowRow
26+import androidx.compose.foundation.layout.PaddingValues
27+import androidx.compose.foundation.layout.Row
28+import androidx.compose.foundation.layout.Spacer
29+import androidx.compose.foundation.layout.WindowInsets
30+import androidx.compose.foundation.layout.fillMaxSize
31+import androidx.compose.foundation.layout.fillMaxWidth
32+import androidx.compose.foundation.layout.height
33+import androidx.compose.foundation.layout.imePadding
34+import androidx.compose.foundation.layout.navigationBars
35+import androidx.compose.foundation.layout.padding
36+import androidx.compose.foundation.layout.size
37+import androidx.compose.foundation.layout.union
38+import androidx.compose.foundation.layout.widthIn
39+import androidx.compose.foundation.layout.windowInsetsPadding
40+import androidx.compose.foundation.layout.wrapContentWidth
41+import androidx.compose.foundation.lazy.LazyColumn
42+import androidx.compose.foundation.lazy.items
43+import androidx.compose.foundation.lazy.rememberLazyListState
44+import androidx.compose.foundation.shape.RoundedCornerShape
45+import androidx.compose.material.icons.Icons
46+import androidx.compose.material.icons.automirrored.filled.ArrowBack
47+import androidx.compose.material.icons.automirrored.filled.Send
48+import androidx.compose.material.icons.filled.Add
49+import androidx.compose.material.icons.filled.AutoAwesome
50+import androidx.compose.material.icons.filled.Delete
51+import androidx.compose.material.icons.filled.Description
52+import androidx.compose.material.icons.filled.Close
53+import androidx.compose.material.icons.filled.Edit
54+import androidx.compose.material.icons.filled.Expand
55+import androidx.compose.material.icons.filled.ExpandLess
56+import androidx.compose.material.icons.filled.ExpandMore
57+import androidx.compose.material.icons.filled.Search
58+import androidx.compose.material.icons.filled.KeyboardArrowDown
59+import androidx.compose.material.icons.filled.KeyboardArrowUp
60+import androidx.compose.material.icons.filled.Mic
61+import androidx.compose.material.icons.filled.MoreVert
62+import androidx.compose.material.icons.filled.PhotoCamera
63+import androidx.compose.material.icons.filled.PhotoLibrary
64+import androidx.compose.material.icons.filled.Refresh
65+import androidx.compose.material.icons.filled.Restore
66+import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
67+import androidx.compose.material.icons.automirrored.filled.Reply
68+import androidx.compose.material.icons.filled.Schedule
69+import androidx.compose.material.icons.filled.Stop
70+import androidx.compose.material3.AlertDialog
71+import androidx.compose.material3.Badge
72+import androidx.compose.material3.BadgedBox
73+import androidx.compose.material3.Button
74+import androidx.compose.material3.CircularProgressIndicator
75+import androidx.compose.material3.SmallFloatingActionButton
76+import androidx.compose.material3.DropdownMenu
77+import androidx.compose.material3.DropdownMenuItem
78+import androidx.compose.material3.ExperimentalMaterial3Api
79+import androidx.compose.material3.ExtendedFloatingActionButton
80+import androidx.compose.material3.FloatingActionButton
81+import androidx.compose.material3.Icon
82+import androidx.compose.material3.IconButton
83+import androidx.compose.material3.MaterialTheme
84+import androidx.compose.material3.OutlinedTextField
85+import androidx.compose.material3.Scaffold
86+import androidx.compose.material3.SnackbarDuration
87+import androidx.compose.material3.SwipeToDismissBox
88+import androidx.compose.material3.SwipeToDismissBoxValue
89+import androidx.compose.material3.rememberSwipeToDismissBoxState
90+import androidx.compose.material3.SnackbarHost
91+import androidx.compose.material3.SnackbarHostState
92+import androidx.compose.material3.SnackbarResult
93+import androidx.compose.material3.Surface
94+import androidx.compose.material3.Text
95+import androidx.compose.material3.TextButton
96+import androidx.compose.material3.TopAppBar
97+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
98+import androidx.compose.runtime.Composable
99+import androidx.compose.runtime.CompositionLocalProvider
100+import androidx.compose.runtime.DisposableEffect
101+import androidx.compose.runtime.LaunchedEffect
102+import androidx.compose.runtime.derivedStateOf
103+import androidx.compose.runtime.getValue
104+import androidx.compose.runtime.mutableIntStateOf
105+import androidx.compose.runtime.mutableLongStateOf
106+import androidx.compose.runtime.mutableStateOf
107+import androidx.compose.runtime.produceState
108+import androidx.compose.runtime.remember
109+import androidx.compose.runtime.rememberCoroutineScope
110+import androidx.compose.runtime.rememberUpdatedState
111+import androidx.compose.runtime.saveable.rememberSaveable
112+import androidx.compose.runtime.setValue
113+import androidx.compose.runtime.snapshotFlow
114+import androidx.compose.foundation.text.KeyboardActions
115+import androidx.compose.foundation.text.KeyboardOptions
116+import androidx.compose.ui.text.input.KeyboardCapitalization
117+import androidx.compose.ui.Alignment
118+import androidx.compose.ui.Modifier
119+import androidx.compose.ui.draw.alpha
120+import androidx.compose.ui.draw.clip
121+import androidx.compose.ui.focus.focusRequester
122+import androidx.compose.ui.input.key.Key
123+import androidx.compose.ui.input.key.KeyEventType
124+import androidx.compose.ui.input.key.isCtrlPressed
125+import androidx.compose.ui.input.key.isShiftPressed
126+import androidx.compose.ui.input.key.key
127+import androidx.compose.ui.input.key.onPreviewKeyEvent
128+import androidx.compose.ui.input.key.type
129+import androidx.compose.ui.layout.onSizeChanged
130+import androidx.compose.ui.platform.LocalContext
131+import androidx.compose.ui.platform.LocalDensity
132+import androidx.compose.ui.platform.LocalHapticFeedback
133+import androidx.compose.ui.platform.LocalView
134+import androidx.compose.ui.platform.testTag
135+import androidx.compose.ui.res.stringResource
136+import androidx.compose.ui.semantics.Role
137+import androidx.compose.ui.semantics.contentDescription
138+import androidx.compose.ui.semantics.heading
139+import androidx.compose.ui.semantics.semantics
140+import androidx.compose.ui.text.input.ImeAction
141+import androidx.compose.ui.text.style.TextOverflow
142+import androidx.compose.ui.unit.dp
143+import androidx.lifecycle.compose.collectAsStateWithLifecycle
144+import androidx.lifecycle.viewmodel.compose.viewModel
145+import kotlinx.coroutines.Dispatchers
146+import kotlinx.coroutines.coroutineScope
147+import kotlinx.coroutines.delay
148+import kotlinx.coroutines.flow.distinctUntilChanged
149+import kotlinx.coroutines.launch
150+import kotlinx.coroutines.withContext
151+import soy.iko.opencode.data.model.Part
152+import soy.iko.opencode.data.model.MessageWithParts
153+import soy.iko.opencode.data.model.ReasoningPart
154+import soy.iko.opencode.data.model.TextPart
155+import soy.iko.opencode.data.model.ToolCompleted
156+import soy.iko.opencode.data.model.ToolError
157+import soy.iko.opencode.data.model.ToolPart
158+import soy.iko.opencode.data.model.ToolRunning
159+import soy.iko.opencode.data.model.FilePart
160+import soy.iko.opencode.data.model.sourcePath
161+import soy.iko.opencode.data.model.inputElement
162+import soy.iko.opencode.data.network.EventStreamClient
163+import soy.iko.opencode.data.network.NetworkConfig
164+import soy.iko.opencode.di.AppContainer
165+import soy.iko.opencode.R
166+import soy.iko.opencode.ui.components.CommandPalette
167+import soy.iko.opencode.ui.components.ConnectionBanner
168+import soy.iko.opencode.ui.components.DiffView
169+import soy.iko.opencode.ui.components.PaletteAction
170+import soy.iko.opencode.ui.components.LocalReducedMotion
171+import soy.iko.opencode.ui.components.LocalSearchHighlight
172+import soy.iko.opencode.ui.components.reducedMotionAnimateItem
173+import soy.iko.opencode.ui.components.copyToClipboard
174+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
175+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
176+import soy.iko.opencode.ui.components.rememberVisibilityTransitions
177+import soy.iko.opencode.ui.components.showToast
178+import soy.iko.opencode.ui.components.toImageContext
179+import soy.iko.opencode.ui.vmFactory
180+import soy.iko.opencode.util.runCatchingCancellable
181+
182+@OptIn(ExperimentalMaterial3Api::class)
183+@Composable
184+fun ChatScreen(
185+ container: AppContainer,
186+ sessionId: String,
187+ onBack: () -> Unit,
188+ onOpenFile: ((String) -> Unit)? = null,
189+ onOpenSession: ((String) -> Unit)? = null,
190+) {
191+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
192+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
193+ val running by vm.running.collectAsStateWithLifecycle()
194+ val aborting by vm.aborting.collectAsStateWithLifecycle()
195+ val loading by vm.loading.collectAsStateWithLifecycle()
196+ val loadError by vm.loadError.collectAsStateWithLifecycle()
197+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
198+ val models by vm.models.collectAsStateWithLifecycle()
199+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
200+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
201+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
202+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
203+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
204+ val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
205+ val agents by vm.agents.collectAsStateWithLifecycle()
206+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
207+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
208+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
209+ val commands by vm.commands.collectAsStateWithLifecycle()
210+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
211+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
212+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
213+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
214+ val draft by vm.draft.collectAsStateWithLifecycle()
215+ val attachments by vm.attachments.collectAsStateWithLifecycle()
216+ val reverted by vm.reverted.collectAsStateWithLifecycle()
217+ val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
218+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
219+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
220+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
221+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
222+ val haptics = LocalHapticFeedback.current
223+ val scope = rememberCoroutineScope()
224+ val shareContext = LocalContext.current
225+ val defaultShareSubject = stringResource(R.string.share_subject)
226+ val sessionLabel = stringResource(R.string.session)
227+ val defaultModelLabel = stringResource(R.string.default_model)
228+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
229+ buildString {
230+ append(selectedModel?.modelLabel ?: defaultModelLabel)
231+ selectedAgent?.let { append(" · $it") }
232+ }
233+ }
234+
235+ // Connection profile (with auth) for rendering inline image attachments.
236+ // Collect as state so a server switch recomposes the image context.
237+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
238+ val imageContext = remember(activeConnection?.profile) {
239+ activeConnection?.profile?.toImageContext()
240+ }
241+
242+ // Mark this session as read while the user is viewing it; clear on leave so new
243+ // background activity can badge it again.
244+ DisposableEffect(sessionId) {
245+ container.setCurrentSession(sessionId)
246+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
247+ }
248+
249+ // Navigate away when the session is deleted via SSE so the user isn't left
250+ // on a zombie screen showing a conversation that no longer exists. Surface a
251+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
252+ // would be torn down before the user could read it, while a toast survives.
253+ // Covers both SSE-driven deletion (deleted on another device) and a user-
254+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
255+ // sets the same flag on success).
256+ val deletedContext = LocalContext.current
257+ LaunchedEffect(sessionDeleted) {
258+ if (sessionDeleted) {
259+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
260+ onBack()
261+ }
262+ }
263+
264+ val snackbar = remember { SnackbarHostState() }
265+ val retryLabel = stringResource(R.string.retry)
266+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
267+ // Dedicated focus requester for the in-conversation search field. The overflow menu's
268+ // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
269+ // (the composer), so typing went to the composer instead of the search field.
270+ val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
271+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
272+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
273+ var showTitleMenu by rememberSaveable { mutableStateOf(false) }
274+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
275+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
276+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
277+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
278+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
279+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
280+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
281+ var showPalette by rememberSaveable { mutableStateOf(false) }
282+ var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
283+ var searchActive by rememberSaveable { mutableStateOf(false) }
284+ var chatSearch by rememberSaveable { mutableStateOf("") }
285+ // Index of the currently-focused in-conversation search match (into the filtered list).
286+ // Drives the up/down navigation: the search bar's arrows step through matches and scroll
287+ // the list to each one, mirroring desktop chat apps (the bare filtered list previously
288+ // required reading each message to find the term).
289+ var searchPos by rememberSaveable { mutableIntStateOf(0) }
290+ // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
291+ // a confirmation dialog (from both the overflow menu and the command palette).
292+ var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
293+ var showInitConfirm by rememberSaveable { mutableStateOf(false) }
294+
295+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
296+ // action list doesn't need a Composable context. Actions map to the same handlers the
297+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
298+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
299+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
300+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
301+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
302+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
303+ val paletteShellLabel = stringResource(R.string.run_shell_command)
304+ val paletteActions = remember(
305+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
306+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
307+ ) {
308+ buildList {
309+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
310+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
311+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
312+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
313+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
314+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
315+ }
316+ }
317+
318+ // Keep the screen awake while the agent is working in *this* session. The foreground
319+ // service that holds process priority during a run is managed app-wide off
320+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
321+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
322+ // SSE stream before the completion notification fires.
323+ val currentView = LocalView.current
324+ val appContext = LocalContext.current.applicationContext
325+ DisposableEffect(running) {
326+ currentView.keepScreenOn = running
327+ onDispose { currentView.keepScreenOn = false }
328+ }
329+
330+ LaunchedEffect(Unit) {
331+ vm.errorEvents.collect { event ->
332+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
333+ // message-load failure) would silently re-submit the last prompt on tap.
334+ val result = if (event.retryable) {
335+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
336+ } else {
337+ snackbar.showSnackbar(event.message)
338+ }
339+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
340+ }
341+ }
342+
343+ // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
344+ // window on the container; show the snackbar over the conversation the user is viewing so
345+ // they can cancel without being navigated to the session list first. If the window expires
346+ // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
347+ val undoLabel = stringResource(R.string.undo)
348+ val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
349+ LaunchedEffect(Unit) {
350+ vm.deleteUndoEvents.collect {
351+ coroutineScope {
352+ val dismisser = launch {
353+ delay(NetworkConfig.undoDeleteDelayMs)
354+ snackbar.currentSnackbarData?.dismiss()
355+ }
356+ val result = snackbar.showSnackbar(
357+ message = sessionDeletedLabel,
358+ actionLabel = undoLabel,
359+ duration = SnackbarDuration.Indefinite,
360+ )
361+ dismisser.cancel()
362+ if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
363+ }
364+ }
365+ }
366+
367+ // --- Attachments, voice, and share-link plumbing ---
368+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
369+ val attachFailedMsg = stringResource(R.string.attachment_failed)
370+ val attachLimitMsg = stringResource(R.string.attachment_limit)
371+ val noCameraMsg = stringResource(R.string.no_camera_app)
372+ val noVoiceMsg = stringResource(R.string.no_voice_app)
373+ val voicePrompt = stringResource(R.string.voice_prompt)
374+ val linkCopiedMsg = stringResource(R.string.link_copied)
375+ val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
376+
377+ // Count of picks currently being read + base64-encoded off the main thread, so the
378+ // composer can show a staging placeholder immediately (chips only materialize once done).
379+ var stagingCount by remember { mutableStateOf(0) }
380+
381+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
382+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
383+ fun stageUris(uris: List<Uri>) {
384+ if (uris.isEmpty()) return
385+ scope.launch {
386+ stagingCount++
387+ try {
388+ for (uri in uris) {
389+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
390+ snackbar.showSnackbar(attachLimitMsg)
391+ break
392+ }
393+ when (val result = uri.toAttachmentResult(appContext)) {
394+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
395+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
396+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
397+ }
398+ }
399+ } finally {
400+ stagingCount--
401+ }
402+ }
403+ }
404+
405+ val photoPicker = rememberLauncherForActivityResult(
406+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
407+ ) { uris -> stageUris(uris) }
408+
409+ val filePicker = rememberLauncherForActivityResult(
410+ ActivityResultContracts.GetMultipleContents(),
411+ ) { uris -> stageUris(uris) }
412+
413+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
414+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
415+ val cameraLauncher = rememberLauncherForActivityResult(
416+ ActivityResultContracts.TakePicture(),
417+ ) { success ->
418+ val uri = pendingCaptureUri
419+ pendingCaptureUri = null
420+ if (success && uri != null) stageUris(listOf(uri))
421+ }
422+
423+ val voiceLauncher = rememberLauncherForActivityResult(
424+ ActivityResultContracts.StartActivityForResult(),
425+ ) { result ->
426+ if (result.resultCode == Activity.RESULT_OK) {
427+ val spoken = result.data
428+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
429+ ?.firstOrNull()
430+ ?.takeIf { it.isNotBlank() }
431+ if (spoken != null) {
432+ // Append to the existing draft rather than replacing, so dictation adds to
433+ // whatever the user already typed.
434+ val current = vm.draft.value
435+ val combined = if (current.isBlank()) spoken else "$current $spoken"
436+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
437+ }
438+ }
439+ }
440+
441+ fun launchCamera() {
442+ val uri = newCameraCaptureUri(appContext)
443+ if (uri == null) {
444+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
445+ return
446+ }
447+ pendingCaptureUri = uri
448+ runCatching { cameraLauncher.launch(uri) }
449+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
450+ }
451+
452+ fun launchVoice() {
453+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
454+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
455+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
456+ }
457+ runCatching { voiceLauncher.launch(intent) }
458+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
459+ }
460+
461+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
462+ LaunchedEffect(Unit) {
463+ vm.shareLinkEvents.collect { url ->
464+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
465+ snackbar.showSnackbar(linkCopiedMsg)
466+ }
467+ }
468+
469+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
470+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
471+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
472+ // a dropped branch-navigation event in the gap.
473+ val branchedMsg = stringResource(R.string.branch_created)
474+ LaunchedEffect(Unit) {
475+ vm.branchEvents.collect { newId ->
476+ showToast(shareContext, branchedMsg)
477+ onOpenSession?.invoke(newId)
478+ }
479+ }
480+
481+ // Stage images shared into the app (via the system share sheet) as attachments.
482+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
483+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
484+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
485+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
486+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
487+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
488+ LaunchedEffect(pendingSharedMedia) {
489+ val shared = container.consumePendingSharedMedia()
490+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
491+ }
492+
493+ fun doSend() {
494+ if (vm.send(draft)) {
495+ // TextHandleMove (a light tick) is semantically right for a send commit;
496+ // LongPress is reserved for long-press/swipe gestures.
497+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
498+ }
499+ }
500+
501+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
502+
503+ Scaffold(
504+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
505+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
506+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
507+ // typing (and the composer's own Enter-to-send handling) is untouched.
508+ modifier = Modifier.onPreviewKeyEvent { ev ->
509+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
510+ when {
511+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
512+ // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
513+ // the field so the user can type immediately.
514+ ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
515+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
516+ ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
517+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
518+ showStopConfirm = true; true
519+ }
520+ else -> false
521+ }
522+ },
523+ topBar = {
524+ TopAppBar(
525+ title = {
526+ val changeLabel = stringResource(R.string.change_model_agent)
527+ // The subtitle reads "model · agent", so tapping the title offers *both*
528+ // — a small menu picks which picker to open. Previously the tap went
529+ // straight to the model picker, leaving the agent changeable only via
530+ // the overflow menu despite the title implying otherwise.
531+ Box {
532+ Row(
533+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
534+ // node; the click label rides on `clickable` (onClickLabel) instead of
535+ // an explicit contentDescription, which would have SUPPRESSED the child
536+ // Texts and announced only "Change model and agent".
537+ modifier = Modifier
538+ .clickable(
539+ role = Role.Button,
540+ onClickLabel = changeLabel,
541+ ) { showTitleMenu = true }
542+ .semantics(mergeDescendants = true) {},
543+ verticalAlignment = Alignment.CenterVertically,
544+ ) {
545+ Column(modifier = Modifier.weight(1f, fill = false)) {
546+ // maxLines=1 + Ellipsis so a long session title can't wrap and
547+ // push the top bar to multiple lines, shifting the whole layout.
548+ Text(
549+ sessionTitle ?: sessionLabel,
550+ maxLines = 1,
551+ overflow = TextOverflow.Ellipsis,
552+ )
553+ Text(
554+ subtitle,
555+ style = MaterialTheme.typography.labelSmall,
556+ color = MaterialTheme.colorScheme.onSurfaceVariant,
557+ maxLines = 1,
558+ overflow = TextOverflow.Ellipsis,
559+ )
560+ }
561+ // Always show the affordance so the title reads as tappable even when
562+ // the model catalog failed to load (models empty). Without it the title
563+ // is indistinguishable from plain text and the pickers are effectively
564+ // undiscoverable — and the dropdown items already disable themselves
565+ // while a catalog is loading or unavailable.
566+ Icon(
567+ Icons.Filled.KeyboardArrowDown,
568+ contentDescription = null,
569+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
570+ modifier = Modifier.size(20.dp),
571+ )
572+ }
573+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
574+ DropdownMenuItem(
575+ text = { Text(stringResource(R.string.palette_switch_model)) },
576+ enabled = !modelsLoading || models.isNotEmpty(),
577+ onClick = { showTitleMenu = false; showModelPicker = true },
578+ )
579+ DropdownMenuItem(
580+ text = { Text(stringResource(R.string.palette_choose_agent)) },
581+ enabled = !agentsLoading || agents.isNotEmpty(),
582+ onClick = { showTitleMenu = false; showAgentPicker = true },
583+ )
584+ }
585+ }
586+ },
587+ navigationIcon = {
588+ IconButton(onClick = {
589+ if (running) showExitConfirm = true else onBack()
590+ }) {
591+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
592+ }
593+ },
594+ actions = {
595+ // At-a-glance run status in the top bar. When the user is scrolled
596+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
597+ // trailing "working…" row are off-screen, so a top-bar spinner is the
598+ // only signal the agent is still working.
599+ if (running) {
600+ val workingLabel = stringResource(R.string.working)
601+ CircularProgressIndicator(
602+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
603+ strokeWidth = 2.dp,
604+ )
605+ }
606+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
607+ // from REST. A recovery path when the stream silently drops and the
608+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
609+ // immediate tap feedback — the SSE reconnect may not visibly change
610+ // the connection state when already Connected, so without it the tap
611+ // appears to do nothing.
612+ val refreshLabel = stringResource(R.string.refresh)
613+ IconButton(
614+ onClick = { vm.refreshMessages() },
615+ enabled = activeConnection != null && !refreshing,
616+ ) {
617+ if (refreshing) {
618+ CircularProgressIndicator(
619+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
620+ strokeWidth = 2.dp,
621+ )
622+ } else {
623+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
624+ }
625+ }
626+ // Overflow menu consolidates the less-frequent actions (share,
627+ // commands, agent, model, rename, delete) so the top bar stays
628+ // scannable on narrow phones — previously 5 icons crowded the bar
629+ // alongside the back button and tappable title. Catalog-loading
630+ // spinners stay inline (next to the overflow) so a load state is
631+ // visible without opening the menu.
632+ val moreLabel = stringResource(R.string.more)
633+ val loadingLabel = stringResource(R.string.loading)
634+ val shareLabel = stringResource(R.string.share_conversation)
635+ val commandsLabel = stringResource(R.string.commands)
636+ val renameLabel = stringResource(R.string.rename_session_chat)
637+ val deleteLabel = stringResource(R.string.delete_session_chat)
638+ val createShareLabel = stringResource(R.string.create_share_link)
639+ val copyShareLabel = stringResource(R.string.copy_share_link)
640+ val stopShareLabel = stringResource(R.string.stop_sharing)
641+ val summarizeLabel = stringResource(R.string.summarize_conversation)
642+ val initLabel = stringResource(R.string.generate_agents_md)
643+ val shellLabel = stringResource(R.string.run_shell_command)
644+ Box {
645+ IconButton(onClick = { showOverflowMenu = true }) {
646+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
647+ }
648+ DropdownMenu(
649+ expanded = showOverflowMenu,
650+ onDismissRequest = { showOverflowMenu = false },
651+ ) {
652+ DropdownMenuItem(
653+ text = { Text(shareLabel) },
654+ enabled = hasMessages,
655+ onClick = {
656+ showOverflowMenu = false
657+ scope.launch {
658+ val md = withContext(Dispatchers.Default) {
659+ buildConversationMarkdown(vm.messages.value, sessionTitle)
660+ }
661+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
662+ type = "text/markdown"
663+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
664+ putExtra(android.content.Intent.EXTRA_TEXT, md)
665+ }
666+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
667+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
668+ }
669+ },
670+ )
671+ DropdownMenuItem(
672+ text = { Text(commandsLabel) },
673+ enabled = !commandsLoading || commands.isNotEmpty(),
674+ onClick = { showOverflowMenu = false; showCommandPicker = true },
675+ )
676+ DropdownMenuItem(
677+ text = { Text(stringResource(R.string.keyboard_shortcuts)) },
678+ onClick = { showOverflowMenu = false; showShortcutsDialog = true },
679+ )
680+ DropdownMenuItem(
681+ text = { Text(stringResource(R.string.find_in_conversation)) },
682+ onClick = {
683+ showOverflowMenu = false
684+ searchActive = true
685+ // Focus is requested by the LaunchedEffect(searchActive)
686+ // below, which waits for the search field to be composed
687+ // before requesting focus (calling requestFocus here would
688+ // target a field that isn't in the composition yet).
689+ },
690+ )
691+ androidx.compose.material3.HorizontalDivider()
692+ // Session sharing: create a public link, copy an existing one, or revoke it.
693+ if (shareUrl == null) {
694+ DropdownMenuItem(
695+ text = { Text(createShareLabel) },
696+ enabled = hasMessages,
697+ onClick = { showOverflowMenu = false; vm.shareSession() },
698+ )
699+ } else {
700+ DropdownMenuItem(
701+ text = { Text(copyShareLabel) },
702+ onClick = {
703+ showOverflowMenu = false
704+ shareUrl?.let {
705+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
706+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
707+ }
708+ },
709+ )
710+ DropdownMenuItem(
711+ text = { Text(stopShareLabel) },
712+ onClick = { showOverflowMenu = false; vm.unshareSession() },
713+ )
714+ }
715+ DropdownMenuItem(
716+ text = { Text(summarizeLabel) },
717+ enabled = hasMessages && !running,
718+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
719+ )
720+ DropdownMenuItem(
721+ text = { Text(initLabel) },
722+ enabled = !running,
723+ onClick = { showOverflowMenu = false; showInitConfirm = true },
724+ )
725+ DropdownMenuItem(
726+ text = { Text(shellLabel) },
727+ enabled = !running,
728+ onClick = { showOverflowMenu = false; showShellDialog = true },
729+ )
730+ androidx.compose.material3.HorizontalDivider()
731+ DropdownMenuItem(
732+ text = { Text(renameLabel) },
733+ onClick = { showOverflowMenu = false; showRenameDialog = true },
734+ )
735+ DropdownMenuItem(
736+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
737+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
738+ )
739+ }
740+ // While a catalog is initially loading (empty list + loading flag),
741+ // show a tiny inline spinner beside the overflow so the user can see
742+ // a load is in progress without opening the menu. Once loaded the
743+ // spinner disappears; the menu items are always enabled (tapping a
744+ // picker with no items shows the "no models/agents/commands" state).
745+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
746+ (agentsLoading && agents.isEmpty()) ||
747+ (modelsLoading && models.isEmpty())
748+ if (catalogLoading) {
749+ CircularProgressIndicator(
750+ Modifier
751+ .align(Alignment.TopEnd)
752+ .size(10.dp)
753+ .semantics { contentDescription = loadingLabel },
754+ strokeWidth = 1.dp,
755+ )
756+ }
757+ }
758+ },
759+ )
760+ },
761+ snackbarHost = { SnackbarHost(snackbar) },
762+ bottomBar = {
763+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
764+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
765+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
766+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
767+ Column {
768+ // Pinned above the composer so the agent's plan and progress stay visible
769+ // while scrolled up mid-run; renders nothing when there's no plan.
770+ TodoPlanBar(todoPlan)
771+ val bannerMotion = rememberVisibilityTransitions()
772+ AnimatedVisibility(
773+ visible = reverted,
774+ enter = bannerMotion.enter,
775+ exit = bannerMotion.exit,
776+ ) {
777+ RevertBanner(
778+ diff = revertDiff,
779+ onUndo = { vm.unrevert() },
780+ )
781+ }
782+ AnimatedVisibility(
783+ visible = queuedOffline.isNotEmpty(),
784+ enter = bannerMotion.enter,
785+ exit = bannerMotion.exit,
786+ ) {
787+ OutboxBanner(
788+ count = queuedOffline.size,
789+ sending = outboxSending,
790+ onFlush = { vm.flushQueued() },
791+ onDiscard = { vm.discardAllQueued() },
792+ )
793+ }
794+ ChatInputBar(
795+ value = draft,
796+ onValueChange = vm::updateDraft,
797+ running = running,
798+ aborting = aborting,
799+ enabled = activeConnection != null,
800+ sendOnEnter = sendOnEnter,
801+ onSend = ::doSend,
802+ onAbort = { showStopConfirm = true },
803+ queuedFollowUp = queuedFollowUp,
804+ onQueueFollowUp = vm::queueFollowUp,
805+ onCancelQueue = { vm.queueFollowUp("") },
806+ focusRequester = inputFocusRequester,
807+ attachments = attachments,
808+ staging = stagingCount > 0,
809+ onRemoveAttachment = vm::removeAttachment,
810+ onPickPhoto = {
811+ photoPicker.launch(
812+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
813+ )
814+ },
815+ onPickFile = { filePicker.launch("*/*") },
816+ onCamera = { launchCamera() },
817+ onVoice = { launchVoice() },
818+ onPasteImage = { stageUris(it) },
819+ )
820+ }
821+ },
822+ ) { padding ->
823+ // Collect messages inside the content lambda so streaming token updates
824+ // recompose only this subtree, not the top bar / input bar / 20+ other
825+ // state reads in the ChatScreen body.
826+ val messages by vm.messages.collectAsStateWithLifecycle()
827+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
828+ val listState = rememberLazyListState()
829+ val contentScope = rememberCoroutineScope()
830+ val timeTick = rememberRelativeTimeTick()
831+ // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
832+ // chat affordance for reading while the IME is open. Watching isScrollInProgress via
833+ // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
834+ val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
835+ androidx.compose.runtime.LaunchedEffect(listState) {
836+ androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
837+ .distinctUntilChanged()
838+ .collect { scrolling -> if (scrolling) keyboardController?.hide() }
839+ } // Group messages by day and interleave date separators so a long conversation
840+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
841+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
842+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
843+ // the same list the LazyColumn renders (separators shift the indices vs. the
844+ // raw messages list, so scroll targets must be in listItems space).
845+ val todayLabel = stringResource(R.string.today)
846+ val yesterdayLabel = stringResource(R.string.yesterday)
847+ // In-conversation search: when active, narrow to messages whose text contains the query.
848+ // Computed on the filtered set so day separators still align with the visible messages.
849+ val searchQuery = chatSearch.trim()
850+ val searchMessages = remember(messages, searchQuery) {
851+ if (searchQuery.isEmpty()) messages
852+ else messages.filter { m ->
853+ m.parts.any { p ->
854+ when (p) {
855+ is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
856+ is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
857+ is ToolPart -> {
858+ // Match the tool name plus its running/completed/error text and the
859+ // stringified input, so searching for an error string or a file the
860+ // tool touched actually finds the message it appeared in.
861+ p.tool.contains(searchQuery, ignoreCase = true) ||
862+ (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
863+ (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
864+ p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
865+ (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
866+ p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
867+ }
868+ is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
869+ p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
870+ else -> false
871+ }
872+ }
873+ }
874+ }
875+ // Keep the focused-match index in range as the query (and thus the match set) changes.
876+ // A new query resets to the first match; a shrunk set clamps to the last valid index.
877+ LaunchedEffect(searchQuery, searchMessages.size) {
878+ if (searchPos >= searchMessages.size) searchPos = 0
879+ }
880+ val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
881+ buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
882+ }
883+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
884+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
885+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
886+ // would capture the first composition's list — which is empty, since `messages`
887+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
888+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
889+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
890+ // whose value tracks the latest list.
891+ val currentListItems by rememberUpdatedState(listItems)
892+
893+ // New-content signal for the jump-to-latest FAB: counts how many new items arrived
894+ // while the user was scrolled away from the bottom, cleared once they return. A count
895+ // (vs. a bare dot) tells the user how much they missed at a glance.
896+ var newContentCount by remember { mutableIntStateOf(0) }
897+
898+ val isPinnedToBottom by remember {
899+ derivedStateOf {
900+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
901+ // When a run is active, the LazyColumn has one trailing "__typing"
902+ // item after the last list item. Account for it so "pinned to bottom"
903+ // includes the working indicator — otherwise the pin check targets
904+ // listItems.lastIndex, the typing row sits just below the viewport,
905+ // and the user never sees the progress indicator even when pinned.
906+ val items = currentListItems
907+ val effectiveLast = if (running) items.size else items.lastIndex
908+ lastVisible >= effectiveLast || items.isEmpty()
909+ }
910+ }
911+
912+ // Jump to the newest message once, when the conversation first loads. Guarded by a
913+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
914+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
915+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
916+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
917+ LaunchedEffect(listItems.isNotEmpty()) {
918+ if (listItems.isNotEmpty() && !didInitialScroll) {
919+ // When a run is active the LazyColumn has a trailing "__typing" row at
920+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
921+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
922+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
923+ didInitialScroll = true
924+ }
925+ }
926+
927+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
928+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
929+ // isPinnedToBottom check flips to false the instant you send — freezing
930+ // auto-scroll. If the user was pinned to the last item just before the run
931+ // began, bring the typing row into view so the pin (and streaming follow) is
932+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
933+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
934+ LaunchedEffect(running) {
935+ if (running && listItems.isNotEmpty()) {
936+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
937+ if (lastVisible >= listItems.lastIndex) {
938+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
939+ }
940+ }
941+ }
942+
943+ // Scroll the focused search match into view whenever the user steps through results with
944+ // the up/down arrows. Resolves the filtered message to its slot in listItems (which
945+ // includes date separators) and animates there.
946+ LaunchedEffect(searchPos, searchQuery, listItems) {
947+ if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
948+ val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
949+ val index = listItems.indexOfFirst {
950+ it is MessageListItem.Message && it.message.info.id == target.info.id
951+ }
952+ if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
953+ }
954+
955+ LaunchedEffect(Unit) {
956+ var prevSize = 0
957+ var prevLen = 0
958+ snapshotFlow {
959+ // Track list size + the streaming length of the last part so we auto-scroll
960+ // as content arrives, plus the pinned flag. A small data class with primitive
961+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
962+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
963+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
964+ // and tool output — not just TextPart — keeps a pinned view following a long
965+ // reasoning/tool block while it streams (previously it stalled at 0).
966+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
967+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
968+ }.collect { signal ->
969+ if (signal.pinned) {
970+ // Back at the bottom: clear the new-content badge.
971+ newContentCount = 0
972+ if (signal.size > 0) {
973+ // Scroll to the effective last index, including the trailing
974+ // "__typing" row when a run is active so the working indicator
975+ // is brought into view (not just the last message).
976+ val items = currentListItems
977+ val target = if (running) items.size else items.lastIndex
978+ listState.scrollToItem(target)
979+ }
980+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
981+ // Content arrived while scrolled up — increment the jump-to-latest badge.
982+ // Only count whole new items (not per-token growth) so the number reflects
983+ // new messages, not a token count.
984+ if (signal.size > prevSize) newContentCount += signal.size - prevSize
985+ else if (newContentCount == 0) newContentCount = 1
986+ }
987+ prevSize = signal.size
988+ prevLen = signal.lastTextLength
989+ }
990+ }
991+
992+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
993+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
994+ // content padding accounts for the bottomBar's raised height, so the message
995+ // list is already above the keyboard. Adding imePadding here would double-apply
996+ // the IME inset and push messages too far up.
997+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
998+ if (activeConnection == null) {
999+ Column(
1000+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
1001+ horizontalAlignment = Alignment.CenterHorizontally,
1002+ ) {
1003+ Text(
1004+ stringResource(R.string.not_connected),
1005+ color = MaterialTheme.colorScheme.error,
1006+ )
1007+ Spacer(Modifier.size(12.dp))
1008+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1009+ if (reconnecting) {
1010+ CircularProgressIndicator(
1011+ Modifier.size(20.dp),
1012+ color = MaterialTheme.colorScheme.onPrimary,
1013+ strokeWidth = 2.dp,
1014+ )
1015+ } else {
1016+ Text(stringResource(R.string.reconnect))
1017+ }
1018+ }
1019+ }
1020+ } else {
1021+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1022+ // Measure the banner's actual height instead of hardcoding 44dp. At large
1023+ // accessibility font scales the banner's labelMedium text + spinner + Retry
1024+ // button exceed 44dp, so a fixed inset lets the first message hide behind it
1025+ // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1026+ // fires while the banner is composed (visible), so gate the inset on
1027+ // bannerVisible and fall back to 44dp until the first measurement arrives.
1028+ var bannerHeightPx by remember { mutableIntStateOf(0) }
1029+ val density = LocalDensity.current
1030+ val topPad = if (bannerVisible) {
1031+ if (bannerHeightPx > 0) {
1032+ with(density) { bannerHeightPx.toDp() } + 4.dp
1033+ } else {
1034+ 44.dp
1035+ }
1036+ } else {
1037+ 16.dp
1038+ }
1039+ ConnectionBanner(
1040+ state = connectionState,
1041+ modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1042+ isOnline = isOnline,
1043+ // On a hard failure, retry by forcing an SSE reconnect (which
1044+ // re-seeds from REST). refreshMessages is the right recovery path
1045+ // when the connection is present but the stream died; reconnect()
1046+ // is the path when the whole connection is gone (handled by the
1047+ // separate "Not connected" state below).
1048+ onRetry = { vm.refreshMessages() },
1049+ )
1050+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1051+ // recovery is a swipe away everywhere — not just when the message list is
1052+ // populated. Previously PTR was only around the populated list, leaving the
1053+ // error/loading states reachable only via a button tap.
1054+ PullToRefreshBox(
1055+ isRefreshing = refreshing,
1056+ onRefresh = { vm.refreshMessages() },
1057+ // Cap width and center on large screens for readability — full-width
1058+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1059+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1060+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1061+ ) {
1062+ // Reserve top space when the banner is visible so it doesn't overlap the
1063+ // first message / state content. (topPad computed above.)
1064+ if (loading && messages.isEmpty()) {
1065+ val loadingLabel = stringResource(R.string.loading)
1066+ // Skeleton bubbles pre-structure the layout so the perceived load is faster
1067+ // than a bare centered spinner and the first real messages pop into an
1068+ // already-shaped list instead of a blank-then-pop. Alpha pulses (gated by
1069+ // reduced-motion) to convey ongoing work; the column carries the a11y label.
1070+ val reducedMotion = LocalReducedMotion.current
1071+ val transition = rememberInfiniteTransition(label = "skeleton")
1072+ val pulse by transition.animateFloat(
1073+ initialValue = 0.35f,
1074+ targetValue = 0.7f,
1075+ animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
1076+ label = "skeletonAlpha",
1077+ )
1078+ val skeletonAlpha = if (reducedMotion) 0.5f else pulse
1079+ val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
1080+ @Composable
1081+ fun bar(widthFraction: Float) {
1082+ Box(
1083+ Modifier
1084+ .fillMaxWidth(widthFraction)
1085+ .height(14.dp)
1086+ .clip(RoundedCornerShape(4.dp))
1087+ .background(skeletonColor)
1088+ .alpha(skeletonAlpha),
1089+ )
1090+ }
1091+ Column(
1092+ modifier = Modifier
1093+ .align(Alignment.TopCenter)
1094+ .padding(top = topPad)
1095+ .padding(16.dp)
1096+ .fillMaxWidth()
1097+ .semantics { contentDescription = loadingLabel },
1098+ verticalArrangement = Arrangement.spacedBy(14.dp),
1099+ ) {
1100+ repeat(4) { i ->
1101+ val left = i % 2 == 0
1102+ Row(
1103+ modifier = Modifier.fillMaxWidth(),
1104+ horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
1105+ ) {
1106+ Column(
1107+ modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
1108+ verticalArrangement = Arrangement.spacedBy(6.dp),
1109+ ) {
1110+ bar(1f)
1111+ bar(0.8f)
1112+ }
1113+ }
1114+ }
1115+ }
1116+ } else if (loadError && messages.isEmpty()) {
1117+ // A failed load with nothing to show. Distinct from the empty
1118+ // conversation state below — the conversation isn't empty, it
1119+ // failed to load, and offering "Start a conversation" here is
1120+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
1121+ Column(
1122+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1123+ horizontalAlignment = Alignment.CenterHorizontally,
1124+ ) {
1125+ Text(
1126+ stringResource(R.string.load_messages_failed),
1127+ color = MaterialTheme.colorScheme.error,
1128+ )
1129+ Spacer(Modifier.size(12.dp))
1130+ Button(onClick = { vm.refreshMessages() }) {
1131+ Text(stringResource(R.string.retry))
1132+ }
1133+ }
1134+ } else if (messages.isEmpty() && running) {
1135+ // A run just started but no parts have arrived yet — the empty
1136+ // list with only the trailing "working…" row looks broken, so
1137+ // surface a clear starting state until the first part streams in.
1138+ val workingText = stringResource(R.string.working)
1139+ Column(
1140+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1141+ horizontalAlignment = Alignment.CenterHorizontally,
1142+ ) {
1143+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
1144+ Spacer(Modifier.size(12.dp))
1145+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
1146+ }
1147+ } else if (messages.isEmpty()) {
1148+ EmptyConversation(
1149+ onSuggestion = {
1150+ vm.updateDraft(it)
1151+ // Focus the input so the user can edit the suggestion before
1152+ // sending, instead of having to manually tap the field.
1153+ runCatching { inputFocusRequester.requestFocus() }
1154+ },
1155+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1156+ )
1157+ } else {
1158+ val lastMessageId = messages.lastOrNull()?.info?.id
1159+ // Text-to-speech for reading assistant replies aloud; shuts down when the
1160+ // message list leaves composition.
1161+ val tts = rememberTtsController()
1162+ val speakingMessageId by tts.speakingId
1163+ val ttsState by tts.state
1164+ // Provide the in-conversation search query to the markdown renderer so matching
1165+ // text spans are highlighted in-place (in addition to the focused-row highlight
1166+ // above). Scoped to the list so cleared search stops highlighting immediately.
1167+ val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1168+ CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1169+ LazyColumn(
1170+ state = listState,
1171+ modifier = Modifier.fillMaxSize(),
1172+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
1173+ // never floats over the last message. Top padding grows when the
1174+ // connection banner is visible so it doesn't overlap the first message.
1175+ contentPadding = PaddingValues(
1176+ start = 16.dp,
1177+ top = topPad,
1178+ end = 16.dp,
1179+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1180+ ),
1181+ verticalArrangement = Arrangement.spacedBy(16.dp),
1182+ ) {
1183+ items(
1184+ items = listItems,
1185+ key = { it.key },
1186+ contentType = { it.contentType },
1187+ ) { item ->
1188+ // When in-conversation search is stepping through matches, highlight the
1189+ // focused one's row so the user can spot it at a glance among the filtered
1190+ // results (full in-text term highlighting would require threading the query
1191+ // through the markdown renderer; the row highlight + scroll-to-match covers
1192+ // the navigation use case desktop chat apps solve with next/prev).
1193+ val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1194+ searchMessages.getOrNull(searchPos)?.info?.id
1195+ } else null
1196+ val isFocusedMatch = focusedMatchId != null &&
1197+ item is MessageListItem.Message &&
1198+ item.message.info.id == focusedMatchId
1199+ // Default placement animation so inserted/moved rows glide in. Skipped
1200+ // entirely under reduced motion so a streaming message growing in place
1201+ // doesn't animate on every token (and respects the a11y preference).
1202+ Box(
1203+ Modifier
1204+ .then(reducedMotionAnimateItem())
1205+ .then(
1206+ if (isFocusedMatch) {
1207+ Modifier.background(
1208+ MaterialTheme.colorScheme.secondaryContainer,
1209+ MaterialTheme.shapes.medium,
1210+ )
1211+ } else {
1212+ Modifier
1213+ },
1214+ ),
1215+ ) {
1216+ when (item) {
1217+ is MessageListItem.Separator -> DateSeparator(item.label)
1218+ is MessageListItem.Message -> {
1219+ val message = item.message
1220+ // Only the last (streaming) message needs isRunning — it drives the
1221+ // reasoning-block spinner. Passing the live flag to every bubble
1222+ // makes all visible messages recompose whenever a run starts or stops.
1223+ val modelLabel = remember(message.info, models) {
1224+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1225+ ?.let { resolveModelLabel(it, models) }
1226+ }
1227+ // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1228+ // image/code-only messages, which then opt out of the swipe gesture.
1229+ val quoteText = remember(message.parts) {
1230+ message.parts
1231+ .filterIsInstance<TextPart>()
1232+ .joinToString("\n\n") { it.text }
1233+ .trim()
1234+ .takeIf { it.isNotEmpty() }
1235+ }
1236+ // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1237+ // snapping back (the message isn't dismissed — the quote fills the composer).
1238+ // Only enabled when there's text to quote, so non-text messages don't
1239+ // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1240+ val swipeState = rememberSwipeToDismissBoxState(
1241+ confirmValueChange = { value ->
1242+ if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1243+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1244+ vm.quoteReply(quoteText)
1245+ runCatching { inputFocusRequester.requestFocus() }
1246+ }
1247+ false
1248+ },
1249+ )
1250+ SwipeToDismissBox(
1251+ state = swipeState,
1252+ enableDismissFromEndToStart = false,
1253+ enableDismissFromStartToEnd = quoteText != null,
1254+ backgroundContent = {
1255+ Box(
1256+ Modifier.fillMaxSize().padding(horizontal = 16.dp),
1257+ contentAlignment = Alignment.CenterStart,
1258+ ) {
1259+ Icon(
1260+ Icons.AutoMirrored.Filled.Reply,
1261+ contentDescription = null,
1262+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1263+ )
1264+ }
1265+ },
1266+ ) {
1267+ MessageBubble(
1268+ message,
1269+ isRunning = running && message.info.id == lastMessageId,
1270+ imageContext = imageContext,
1271+ modelLabel = modelLabel,
1272+ onOpenFile = onOpenFile,
1273+ onRevert = { vm.revertTo(message.info.id) },
1274+ onEdit = { text ->
1275+ // editMessage reverts to before this message (hiding it and
1276+ // everything after); the revert banner surfaces the rewind
1277+ // with an Undo. Focus + scroll the composer into view like the
1278+ // Quote action so the prefilled draft isn't off-screen.
1279+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1280+ vm.editMessage(message.info.id, text)
1281+ runCatching { inputFocusRequester.requestFocus() }
1282+ contentScope.launch {
1283+ runCatchingCancellable {
1284+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1285+ }
1286+ }
1287+ },
1288+ onSpeak = { text ->
1289+ if (!tts.toggle(message.info.id, text)) {
1290+ // TTS engine unavailable (init failed / not yet ready
1291+ // / blank text): surface feedback so the button doesn't
1292+ // appear dead. Throttled so a rapid double-tap (stop
1293+ // then immediate re-tap before ready) doesn't spam.
1294+ scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1295+ }
1296+ },
1297+ isSpeaking = message.info.id == speakingMessageId,
1298+ ttsState = if (message.info.id == speakingMessageId) ttsState else TtsState.IDLE,
1299+ onPause = { tts.pause() },
1300+ onResume = { tts.resume() },
1301+ onQuote = { text ->
1302+ vm.quoteReply(text)
1303+ runCatching { inputFocusRequester.requestFocus() }
1304+ },
1305+ onBranch = { text -> vm.branchFrom(text) },
1306+ // Regenerate is only meaningful for a finished assistant reply
1307+ // (not the actively-streaming one), so gate it on !running.
1308+ onRegenerate = if (!running) {
1309+ { vm.regenerate(message.info.id) }
1310+ } else null,
1311+ sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1312+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1313+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1314+ },
1315+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1316+ onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1317+ if (failed) {
1318+ { vm.retryOptimisticMessage(message.info.id) }
1319+ } else {
1320+ null
1321+ }
1322+ },
1323+ onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1324+ if (failed) {
1325+ { vm.dismissOptimistic(message.info.id) }
1326+ } else {
1327+ null
1328+ }
1329+ },
1330+ onShare = {
1331+ // Per-message share: build a single-message Markdown
1332+ // transcript off-thread and fire ACTION_SEND, mirroring the
1333+ // whole-conversation share but scoped to just this message.
1334+ scope.launch {
1335+ val md = withContext(Dispatchers.Default) {
1336+ buildMessageMarkdown(message)
1337+ } ?: return@launch
1338+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1339+ type = "text/markdown"
1340+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1341+ putExtra(android.content.Intent.EXTRA_TEXT, md)
1342+ }
1343+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1344+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1345+ }
1346+ },
1347+ )
1348+ }
1349+ }
1350+ }
1351+ }
1352+ }
1353+ if (running) {
1354+ item(key = "__typing") {
1355+ val workingText = stringResource(R.string.working)
1356+ // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1357+ // survives LazyColumn recycling — a local remember reset to 0:00 when
1358+ // the row was disposed and scrolled back into view. The VM stamps the
1359+ // start on the real false→true transition (send/run/init), not on
1360+ // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1361+ // once per second; the value is decorative (the a11y label is the row's).
1362+ val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1363+ val elapsedMs by produceState(0L, startMs) {
1364+ if (startMs == 0L) return@produceState
1365+ while (true) {
1366+ value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1367+ delay(1000)
1368+ }
1369+ }
1370+ val elapsedText = remember(elapsedMs) {
1371+ val total = elapsedMs / 1000
1372+ // Locale.US for stable digit formatting: on locales with
1373+ // non-ASCII digits (ar-/fa-) the default locale would render
1374+ // localized digits inside the Monospace block, breaking the
1375+ // fixed-width alignment the monospace family was chosen for.
1376+ String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1377+ }
1378+ Row(
1379+ verticalAlignment = Alignment.CenterVertically,
1380+ // Animate this slot in/out so the working row doesn't pop in and
1381+ // jolt the message list when a run starts/stops — matching the
1382+ // AnimatedVisibility used by every other transient banner/FAB here.
1383+ modifier = Modifier
1384+ .then(reducedMotionAnimateItem())
1385+ .padding(vertical = 4.dp),
1386+ ) {
1387+ // Merge the indicator + label + clock into one TalkBack node so
1388+ // it's announced once (the working label, then the elapsed time)
1389+ // instead of "working… / working… / 0:14" with the label read
1390+ // twice. The Stop IconButton below stays separately focusable.
1391+ Row(
1392+ verticalAlignment = Alignment.CenterVertically,
1393+ modifier = Modifier.semantics(mergeDescendants = true) {
1394+ contentDescription = "$workingText $elapsedText"
1395+ },
1396+ ) {
1397+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1398+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1399+ Spacer(Modifier.size(8.dp))
1400+ Icon(
1401+ Icons.Filled.Schedule,
1402+ contentDescription = null,
1403+ modifier = Modifier.size(14.dp),
1404+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1405+ )
1406+ Text(
1407+ elapsedText,
1408+ style = MaterialTheme.typography.labelMedium,
1409+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1410+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1411+ modifier = Modifier.padding(start = 4.dp),
1412+ )
1413+ }
1414+ // A trailing Stop on the working row so the run can be aborted
1415+ // without scrolling back to the composer (which may be off-screen
1416+ // while the user reads the streaming output up-thread).
1417+ Spacer(Modifier.weight(1f))
1418+ val stopLabel = stringResource(R.string.stop)
1419+ IconButton(
1420+ onClick = { showStopConfirm = true },
1421+ modifier = Modifier.semantics { contentDescription = stopLabel },
1422+ ) {
1423+ Icon(Icons.Filled.Stop, contentDescription = null)
1424+ }
1425+ }
1426+ }
1427+ }
1428+ }
1429+ }
1430+ }
1431+ }
1432+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1433+ val fabMotion = rememberVisibilityTransitions()
1434+ AnimatedVisibility(
1435+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1436+ enter = fabMotion.enter,
1437+ exit = fabMotion.exit,
1438+ modifier = Modifier.align(Alignment.BottomEnd),
1439+ ) {
1440+ // Badge the FAB when new content arrived while the user was scrolled up, so
1441+ // they know there's something new to jump to (cleared once back at bottom).
1442+ BadgedBox(
1443+ badge = {
1444+ if (newContentCount > 0) {
1445+ val newContentLabel = stringResource(R.string.new_messages)
1446+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel }) {
1447+ Text(if (newContentCount > 99) "99+" else newContentCount.toString())
1448+ }
1449+ }
1450+ },
1451+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1452+ ) {
1453+ ExtendedFloatingActionButton(
1454+ onClick = {
1455+ newContentCount = 0
1456+ if (listItems.isNotEmpty()) {
1457+ // Scroll to the effective last index, including the
1458+ // trailing "__typing" row when a run is active.
1459+ val target = if (running) listItems.size else listItems.lastIndex
1460+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1461+ }
1462+ },
1463+ // contentDescription null: the visible "Latest" text already labels
1464+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1465+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1466+ text = { Text(stringResource(R.string.latest)) },
1467+ )
1468+ }
1469+ }
1470+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1471+ // user has scrolled down past the first few messages. Symmetric to the
1472+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1473+ val scrolledDown by remember {
1474+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1475+ }
1476+ AnimatedVisibility(
1477+ visible = scrolledDown && listItems.size > 4,
1478+ enter = fabMotion.enter,
1479+ exit = fabMotion.exit,
1480+ modifier = Modifier.align(Alignment.BottomStart),
1481+ ) {
1482+ SmallFloatingActionButton(
1483+ onClick = {
1484+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1485+ },
1486+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1487+ ) {
1488+ Icon(
1489+ Icons.Filled.KeyboardArrowUp,
1490+ contentDescription = stringResource(R.string.scroll_to_top),
1491+ )
1492+ }
1493+ }
1494+ // In-conversation search bar. Overlays the list so typing filters messages in
1495+ // place; the match count + a no-matches note give immediate feedback.
1496+ val searchMotion = rememberVisibilityTransitions()
1497+ AnimatedVisibility(
1498+ visible = searchActive,
1499+ enter = searchMotion.enter,
1500+ exit = searchMotion.exit,
1501+ modifier = Modifier.align(Alignment.TopCenter),
1502+ ) {
1503+ Surface(
1504+ tonalElevation = 3.dp,
1505+ modifier = Modifier
1506+ .padding(horizontal = 12.dp, vertical = 4.dp)
1507+ .fillMaxWidth(),
1508+ ) {
1509+ // Focus the search field when the bar appears (from the overflow menu's
1510+ // "Find in conversation" or Ctrl+F), so the user can start typing
1511+ // immediately. Runs after the search field enters the composition.
1512+ LaunchedEffect(searchActive) {
1513+ if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1514+ }
1515+ Row(
1516+ modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1517+ verticalAlignment = Alignment.CenterVertically,
1518+ ) {
1519+ OutlinedTextField(
1520+ value = chatSearch,
1521+ onValueChange = { chatSearch = it },
1522+ modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1523+ placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1524+ singleLine = true,
1525+ leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1526+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1527+ )
1528+ // Match counter: "N of M" where N is the focused match (1-based) and
1529+ // M is the total matching messages. Only shown when there's a query.
1530+ val matchCount = searchMessages.size
1531+ Text(
1532+ if (searchQuery.isNotEmpty() && matchCount > 0) {
1533+ stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1534+ } else if (searchQuery.isNotEmpty()) {
1535+ stringResource(R.string.search_no_matches)
1536+ } else "",
1537+ style = MaterialTheme.typography.labelSmall,
1538+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1539+ modifier = Modifier.padding(horizontal = 4.dp),
1540+ )
1541+ // Step through matches (Previous / Next), disabled when there are
1542+ // fewer than two to navigate. Wrap around at the ends so repeated
1543+ // taps cycle through every hit.
1544+ val prevLabel = stringResource(R.string.find_previous)
1545+ val nextLabel = stringResource(R.string.find_next)
1546+ IconButton(
1547+ onClick = {
1548+ if (matchCount > 0) {
1549+ searchPos = (searchPos - 1 + matchCount) % matchCount
1550+ }
1551+ },
1552+ enabled = matchCount > 1,
1553+ ) {
1554+ Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1555+ }
1556+ IconButton(
1557+ onClick = {
1558+ if (matchCount > 0) {
1559+ searchPos = (searchPos + 1) % matchCount
1560+ }
1561+ },
1562+ enabled = matchCount > 1,
1563+ ) {
1564+ Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1565+ }
1566+ IconButton(onClick = {
1567+ searchActive = false
1568+ chatSearch = ""
1569+ }) {
1570+ Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1571+ }
1572+ }
1573+ }
1574+ }
1575+ // When a search yields no matches (but the conversation isn't empty), say so
1576+ // instead of showing a blank list.
1577+ if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1578+ Text(
1579+ stringResource(R.string.search_no_matches),
1580+ style = MaterialTheme.typography.bodyMedium,
1581+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1582+ modifier = Modifier.align(Alignment.Center),
1583+ )
1584+ }
1585+ }
1586+ }
1587+ }
1588+ }
1589+
1590+ if (showExitConfirm) {
1591+ AlertDialog(
1592+ onDismissRequest = { showExitConfirm = false },
1593+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1594+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1595+ confirmButton = {
1596+ TextButton(onClick = {
1597+ showExitConfirm = false
1598+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1599+ vm.abort()
1600+ onBack()
1601+ }) { Text(stringResource(R.string.stop_and_exit)) }
1602+ },
1603+ dismissButton = {
1604+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1605+ },
1606+ )
1607+ }
1608+
1609+ if (showStopConfirm) {
1610+ AlertDialog(
1611+ onDismissRequest = { showStopConfirm = false },
1612+ title = { Text(stringResource(R.string.stop_run_title)) },
1613+ text = { Text(stringResource(R.string.stop_run_text)) },
1614+ confirmButton = {
1615+ TextButton(onClick = {
1616+ showStopConfirm = false
1617+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1618+ vm.abort()
1619+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1620+ },
1621+ dismissButton = {
1622+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1623+ },
1624+ )
1625+ }
1626+
1627+ if (showSummarizeConfirm) {
1628+ AlertDialog(
1629+ onDismissRequest = { showSummarizeConfirm = false },
1630+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
1631+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
1632+ confirmButton = {
1633+ TextButton(onClick = {
1634+ showSummarizeConfirm = false
1635+ vm.summarize()
1636+ }) { Text(stringResource(R.string.action_continue)) }
1637+ },
1638+ dismissButton = {
1639+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1640+ },
1641+ )
1642+ }
1643+
1644+ if (showInitConfirm) {
1645+ AlertDialog(
1646+ onDismissRequest = { showInitConfirm = false },
1647+ title = { Text(stringResource(R.string.init_confirm_title)) },
1648+ text = { Text(stringResource(R.string.init_confirm_text)) },
1649+ confirmButton = {
1650+ TextButton(onClick = {
1651+ showInitConfirm = false
1652+ vm.initProject()
1653+ }) { Text(stringResource(R.string.action_continue)) }
1654+ },
1655+ dismissButton = {
1656+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1657+ },
1658+ )
1659+ }
1660+
1661+ if (showRenameDialog) {
1662+ RenameSessionChatDialog(
1663+ initialTitle = sessionTitle ?: "",
1664+ onDismiss = { showRenameDialog = false },
1665+ onConfirm = { newName ->
1666+ showRenameDialog = false
1667+ vm.renameSession(newName)
1668+ },
1669+ )
1670+ }
1671+
1672+ if (showDeleteDialog) {
1673+ AlertDialog(
1674+ onDismissRequest = { showDeleteDialog = false },
1675+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1676+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1677+ confirmButton = {
1678+ TextButton(onClick = {
1679+ showDeleteDialog = false
1680+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1681+ vm.deleteSession()
1682+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1683+ },
1684+ dismissButton = {
1685+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1686+ },
1687+ )
1688+ }
1689+
1690+ if (showShellDialog) {
1691+ ShellCommandDialog(
1692+ onDismiss = { showShellDialog = false },
1693+ onRun = { cmd ->
1694+ showShellDialog = false
1695+ vm.runShell(cmd)
1696+ },
1697+ )
1698+ }
1699+
1700+ if (showModelPicker) {
1701+ ModelPickerSheet(
1702+ options = models,
1703+ selected = selectedModel,
1704+ loading = modelsLoading,
1705+ error = modelsError,
1706+ onSelect = { vm.selectModel(it) },
1707+ onRetry = { vm.reloadModels() },
1708+ onDismiss = { showModelPicker = false },
1709+ )
1710+ }
1711+
1712+ if (showAgentPicker) {
1713+ AgentPickerSheet(
1714+ agents = agents,
1715+ selected = selectedAgent,
1716+ loading = agentsLoading,
1717+ error = agentsError,
1718+ onSelect = { vm.selectAgent(it?.name) },
1719+ onRetry = { vm.reloadAgents() },
1720+ onDismiss = { showAgentPicker = false },
1721+ )
1722+ }
1723+
1724+ if (showCommandPicker) {
1725+ CommandPickerSheet(
1726+ commands = commands,
1727+ loading = commandsLoading,
1728+ error = commandsError,
1729+ onSelect = { vm.runCommand(it) },
1730+ onRetry = { vm.reloadCommands() },
1731+ onDismiss = { showCommandPicker = false },
1732+ )
1733+ }
1734+
1735+ pendingPermission?.let { permission ->
1736+ PermissionDialog(
1737+ permission = permission,
1738+ position = permissionProgress.position,
1739+ total = permissionProgress.total,
1740+ onRespond = { response -> vm.respondPermission(permission, response) },
1741+ )
1742+ }
1743+
1744+ if (showPalette) {
1745+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1746+ }
1747+
1748+ if (showShortcutsDialog) {
1749+ // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
1750+ // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
1751+ // depends on the "Send on Enter" setting, noted inline.
1752+ AlertDialog(
1753+ onDismissRequest = { showShortcutsDialog = false },
1754+ title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
1755+ text = {
1756+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
1757+ ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
1758+ ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
1759+ ShortcutRow("Esc", stringResource(R.string.shortcut_close))
1760+ ShortcutRow("Enter", stringResource(R.string.shortcut_send))
1761+ ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
1762+ }
1763+ },
1764+ confirmButton = {
1765+ TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
1766+ },
1767+ )
1768+ }
1769+}
1770+
1771+@Composable
1772+private fun ShortcutRow(keys: String, desc: String) {
1773+ Row(verticalAlignment = Alignment.CenterVertically) {
1774+ Text(
1775+ keys,
1776+ style = MaterialTheme.typography.labelLarge,
1777+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1778+ modifier = Modifier.widthIn(min = 160.dp),
1779+ )
1780+ Text(
1781+ desc,
1782+ style = MaterialTheme.typography.bodyMedium,
1783+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1784+ )
1785+ }
1786+}
1787+
1788+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
1789+@Composable
1790+private fun ChatInputBar(
1791+ value: String,
1792+ onValueChange: (String) -> Unit,
1793+ running: Boolean,
1794+ aborting: Boolean,
1795+ enabled: Boolean,
1796+ sendOnEnter: Boolean,
1797+ onSend: () -> Unit,
1798+ onAbort: () -> Unit,
1799+ queuedFollowUp: String?,
1800+ onQueueFollowUp: (String) -> Unit,
1801+ onCancelQueue: () -> Unit,
1802+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1803+ attachments: List<PendingAttachment>,
1804+ staging: Boolean,
1805+ onRemoveAttachment: (String) -> Unit,
1806+ onPickPhoto: () -> Unit,
1807+ onPickFile: () -> Unit,
1808+ onCamera: () -> Unit,
1809+ onVoice: () -> Unit,
1810+ onPasteImage: (List<Uri>) -> Unit,
1811+) {
1812+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1813+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1814+ val context = LocalContext.current
1815+ // Full-screen editor state: opened when the user wants more space for a long prompt.
1816+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1817+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1818+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1819+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1820+ // user sees their message will be sent when the run finishes, and can cancel.
1821+ if (queuedFollowUp != null) {
1822+ val editLabel = stringResource(R.string.edit)
1823+ Row(
1824+ modifier = Modifier
1825+ .fillMaxWidth()
1826+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1827+ verticalAlignment = Alignment.CenterVertically,
1828+ ) {
1829+ // Tapping the chip reloads the queued text into the draft (and clears the
1830+ // queue) so a typo spotted while queuing can be fixed without retyping.
1831+ Column(
1832+ modifier = Modifier
1833+ .weight(1f)
1834+ .clip(MaterialTheme.shapes.small)
1835+ .clickable(role = Role.Button, onClickLabel = editLabel) {
1836+ onValueChange(queuedFollowUp)
1837+ onCancelQueue()
1838+ }
1839+ .padding(vertical = 4.dp),
1840+ ) {
1841+ Text(
1842+ stringResource(R.string.queued),
1843+ style = MaterialTheme.typography.labelSmall,
1844+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1845+ )
1846+ Text(
1847+ queuedFollowUp,
1848+ style = MaterialTheme.typography.bodySmall,
1849+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1850+ maxLines = 1,
1851+ overflow = TextOverflow.Ellipsis,
1852+ )
1853+ }
1854+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1855+ Text(stringResource(R.string.cancel))
1856+ }
1857+ }
1858+ }
1859+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1860+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1861+ Row(
1862+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1863+ verticalAlignment = Alignment.Bottom,
1864+ ) {
1865+ // Attach menu: photo picker, camera, or any file.
1866+ var showAttachMenu by remember { mutableStateOf(false) }
1867+ Box {
1868+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1869+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1870+ }
1871+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1872+ DropdownMenuItem(
1873+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1874+ text = { Text(stringResource(R.string.attach_photo)) },
1875+ onClick = { showAttachMenu = false; onPickPhoto() },
1876+ )
1877+ DropdownMenuItem(
1878+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1879+ text = { Text(stringResource(R.string.attach_camera)) },
1880+ onClick = { showAttachMenu = false; onCamera() },
1881+ )
1882+ DropdownMenuItem(
1883+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1884+ text = { Text(stringResource(R.string.attach_file)) },
1885+ onClick = { showAttachMenu = false; onPickFile() },
1886+ )
1887+ }
1888+ }
1889+ // Voice dictation: appends recognized speech to the draft. Hidden (not just
1890+ // disabled) when the device has no speech-recognition activity, so a user
1891+ // without a voice app doesn't get a button that only fails noisily on tap.
1892+ val voiceAvailable = remember {
1893+ val pm = context.packageManager
1894+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
1895+ pm.queryIntentActivities(intent, 0).isNotEmpty()
1896+ }
1897+ if (voiceAvailable) {
1898+ IconButton(onClick = onVoice, enabled = enabled) {
1899+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1900+ }
1901+ }
1902+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1903+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1904+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1905+ }
1906+ OutlinedTextField(
1907+ value = value,
1908+ onValueChange = { v ->
1909+ // Cap input length so a huge paste can't stall the UI. Shares are
1910+ // capped separately in MainActivity; this guards typed/pasted drafts.
1911+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1912+ },
1913+ modifier = Modifier
1914+ .weight(1f)
1915+ .focusRequester(focusRequester)
1916+ .testTag("chat_input")
1917+ // Intercept image content pasted/dropped into the field (keyboard paste
1918+ // of a copied screenshot, drag from Files, etc.) and route it through the
1919+ // same staging path as the attach menu. Non-image content (text) falls
1920+ // through unchanged so normal typing/paste works.
1921+ .contentReceiver(
1922+ remember {
1923+ androidx.compose.foundation.content.ReceiveContentListener { transferable ->
1924+ val clipData = transferable.clipEntry?.clipData
1925+ if (clipData != null) {
1926+ val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
1927+ val item = clipData.getItemAt(i)
1928+ item.uri?.takeIf { uri ->
1929+ item.text == null && uri.toString().let { s ->
1930+ s.startsWith("content:") || s.startsWith("file:")
1931+ }
1932+ }
1933+ }
1934+ if (imageUris.isNotEmpty()) {
1935+ onPasteImage(imageUris)
1936+ }
1937+ }
1938+ transferable
1939+ }
1940+ },
1941+ )
1942+ .onPreviewKeyEvent { event ->
1943+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1944+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1945+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1946+ val send = enterShouldSend(
1947+ enabled = enabled,
1948+ hasContent = hasContent,
1949+ sendOnEnter = sendOnEnter,
1950+ shift = event.isShiftPressed,
1951+ ctrl = event.isCtrlPressed,
1952+ )
1953+ if (send) {
1954+ if (running) onQueueFollowUp(value) else onSend()
1955+ true
1956+ } else {
1957+ false
1958+ }
1959+ },
1960+ // While a run is active a typed message only queues (sends after the run), so
1961+ // the placeholder says so instead of the plain "Message…".
1962+ placeholder = {
1963+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1964+ },
1965+ enabled = enabled,
1966+ maxLines = 6,
1967+ // Show a "N / max" countdown once the draft crosses a high fraction of
1968+ // the cap, so the user knows a paste is about to be truncated instead
1969+ // of being silently cut off. Hidden for normal short prompts to avoid
1970+ // clutter under a typical one-line message.
1971+ supportingText = {
1972+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1973+ if (value.length >= threshold) {
1974+ Text(
1975+ stringResource(
1976+ R.string.draft_chars_remaining,
1977+ NetworkConfig.maxDraftLengthChars - value.length,
1978+ NetworkConfig.maxDraftLengthChars,
1979+ ),
1980+ style = MaterialTheme.typography.labelSmall,
1981+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1982+ else MaterialTheme.colorScheme.onSurfaceVariant,
1983+ )
1984+ }
1985+ },
1986+ keyboardOptions = KeyboardOptions(
1987+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
1988+ // keyboard shows a send key — matching the setting's intent and
1989+ // giving touch-only users a keyboard send affordance. When off,
1990+ // ImeAction.Default keeps the enter/newline key for multi-line input.
1991+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1992+ capitalization = KeyboardCapitalization.Sentences,
1993+ ),
1994+ keyboardActions = KeyboardActions(
1995+ onSend = {
1996+ if (enabled && hasContent) onSend()
1997+ },
1998+ ),
1999+ )
2000+ ComposerTrailingButton(
2001+ running = running,
2002+ aborting = aborting,
2003+ canSend = enabled && hasContent,
2004+ canQueue = enabled && value.isNotBlank(),
2005+ onSend = onSend,
2006+ onAbort = onAbort,
2007+ onQueue = { onQueueFollowUp(value) },
2008+ )
2009+ }
2010+ }
2011+ if (showFullScreenEditor) {
2012+ FullScreenEditor(
2013+ value = value,
2014+ onValueChange = onValueChange,
2015+ onDismiss = { showFullScreenEditor = false },
2016+ onSend = {
2017+ showFullScreenEditor = false
2018+ // Mirror the inline composer's behavior: while a run is active a send
2019+ // can't go immediately, so queue the follow-up instead of silently
2020+ // dropping it (vm.send() returns false during a run, which previously
2021+ // lost the typed message with no feedback).
2022+ if (running) onQueueFollowUp(value) else onSend()
2023+ },
2024+ canSend = enabled && hasContent,
2025+ running = running,
2026+ sendOnEnter = sendOnEnter,
2027+ attachments = attachments,
2028+ onRemoveAttachment = onRemoveAttachment,
2029+ staging = staging,
2030+ )
2031+ }
2032+ }
2033+}
2034+
2035+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2036+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2037+@OptIn(ExperimentalMaterial3Api::class)
2038+@Composable
2039+private fun FullScreenEditor(
2040+ value: String,
2041+ onValueChange: (String) -> Unit,
2042+ onDismiss: () -> Unit,
2043+ onSend: () -> Unit,
2044+ canSend: Boolean,
2045+ running: Boolean = false,
2046+ sendOnEnter: Boolean = false,
2047+ attachments: List<PendingAttachment> = emptyList(),
2048+ onRemoveAttachment: (String) -> Unit = {},
2049+ staging: Boolean = false,
2050+) {
2051+ androidx.compose.ui.window.Dialog(
2052+ onDismissRequest = onDismiss,
2053+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2054+ ) {
2055+ // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2056+ // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2057+ // gives the available width so we can center a capped-width column.
2058+ androidx.compose.foundation.layout.BoxWithConstraints(
2059+ modifier = Modifier.fillMaxSize(),
2060+ contentAlignment = Alignment.Center,
2061+ ) {
2062+ val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2063+ ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2064+ else 0.dp
2065+ Scaffold(
2066+ modifier = Modifier.padding(horizontal = hPad),
2067+ topBar = {
2068+ androidx.compose.material3.TopAppBar(
2069+ title = { Text(stringResource(R.string.compose_editor_title)) },
2070+ navigationIcon = {
2071+ androidx.compose.material3.TextButton(onClick = onDismiss) {
2072+ Text(stringResource(R.string.collapse_editor))
2073+ }
2074+ },
2075+ )
2076+ },
2077+ bottomBar = {
2078+ Surface(tonalElevation = 3.dp) {
2079+ Row(
2080+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2081+ horizontalArrangement = Arrangement.End,
2082+ ) {
2083+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2084+ Text(stringResource(if (running) R.string.queue else R.string.send))
2085+ }
2086+ }
2087+ }
2088+ },
2089+ ) { padding ->
2090+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2091+ // Show staged attachments in the full-screen editor too, so a user who staged
2092+ // images then expanded for a long prompt can still see and remove them without
2093+ // collapsing first (mirrors the inline composer's AttachmentStrip).
2094+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
2095+ OutlinedTextField(
2096+ value = value,
2097+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2098+ modifier = Modifier
2099+ .fillMaxSize()
2100+ .weight(1f)
2101+ // Honor the "Send on Enter" setting here too, so the full-screen
2102+ // editor matches the inline composer: Enter sends (Shift+Enter
2103+ // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2104+ // when off. Previously this hard-coded ImeAction.Default and had no
2105+ // key handler, so a hardware-keyboard user got a different behaviour
2106+ // from the inline composer depending on which they happened to open.
2107+ .onPreviewKeyEvent { event ->
2108+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2109+ val send = enterShouldSend(
2110+ enabled = canSend,
2111+ hasContent = canSend,
2112+ sendOnEnter = sendOnEnter,
2113+ shift = event.isShiftPressed,
2114+ ctrl = event.isCtrlPressed,
2115+ )
2116+ if (send) { onSend(); true } else false
2117+ },
2118+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
2119+ maxLines = Int.MAX_VALUE,
2120+ keyboardOptions = KeyboardOptions(
2121+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2122+ capitalization = KeyboardCapitalization.Sentences,
2123+ ),
2124+ keyboardActions = KeyboardActions(
2125+ onSend = { if (canSend) onSend() },
2126+ ),
2127+ )
2128+ }
2129+ }
2130+ }
2131+ }
2132+}
2133+
2134+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2135+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2136+private fun enterShouldSend(
2137+ enabled: Boolean,
2138+ hasContent: Boolean,
2139+ sendOnEnter: Boolean,
2140+ shift: Boolean,
2141+ ctrl: Boolean,
2142+): Boolean = when {
2143+ !enabled || !hasContent -> false
2144+ sendOnEnter -> !shift
2145+ else -> ctrl
2146+}
2147+
2148+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2149+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2150+ * [ChatInputBar] stays under the complexity threshold. */
2151+@Composable
2152+private fun ComposerTrailingButton(
2153+ running: Boolean,
2154+ aborting: Boolean,
2155+ canSend: Boolean,
2156+ canQueue: Boolean,
2157+ onSend: () -> Unit,
2158+ onAbort: () -> Unit,
2159+ onQueue: () -> Unit,
2160+) {
2161+ if (running) {
2162+ Row(verticalAlignment = Alignment.CenterVertically) {
2163+ // While a run is active the trailing action is Stop, so the only send affordance is
2164+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2165+ // That leaves a touch-only user with the setting off no way to queue a follow-up
2166+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2167+ // there's typed TEXT so queuing is always reachable, without changing the user's
2168+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2169+ // canSend, which is also true for an attachment-only composer — because queuing "" just
2170+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2171+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2172+ if (canQueue) {
2173+ IconButton(
2174+ onClick = onQueue,
2175+ modifier = Modifier.testTag("queue_button"),
2176+ ) {
2177+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2178+ // icon (which can be read as "snooze" or "later"), and isn't confused with
2179+ // the Send action sitting right beside the Stop button.
2180+ Icon(
2181+ Icons.AutoMirrored.Filled.PlaylistAdd,
2182+ contentDescription = stringResource(R.string.queue_followup),
2183+ )
2184+ }
2185+ }
2186+ // Show a spinner while the abort REST call is in flight so the user sees the stop
2187+ // was sent, and disable to prevent a double-tap.
2188+ IconButton(
2189+ onClick = onAbort,
2190+ enabled = !aborting,
2191+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2192+ ) {
2193+ if (aborting) {
2194+ val stopLabel = stringResource(R.string.stop)
2195+ CircularProgressIndicator(
2196+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2197+ strokeWidth = 2.dp,
2198+ )
2199+ } else {
2200+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2201+ }
2202+ }
2203+ }
2204+ } else {
2205+ IconButton(
2206+ onClick = onSend,
2207+ enabled = canSend,
2208+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2209+ ) {
2210+ // Tint the send icon with primary when there's content to send so the commit action
2211+ // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2212+ Icon(
2213+ Icons.AutoMirrored.Filled.Send,
2214+ contentDescription = stringResource(R.string.send),
2215+ tint = if (canSend) MaterialTheme.colorScheme.primary
2216+ else MaterialTheme.colorScheme.onSurfaceVariant,
2217+ )
2218+ }
2219+ }
2220+}
2221+
2222+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2223+@Composable
2224+private fun EmptyConversation(
2225+ onSuggestion: (String) -> Unit,
2226+ modifier: Modifier = Modifier,
2227+) {
2228+ // A few example prompts so a first-time user has a one-tap path to their first
2229+ // message instead of staring at a blank input. Tapping a chip fills the draft
2230+ // (without sending) so the user can edit it before sending.
2231+ val suggestions = remember {
2232+ listOf(
2233+ R.string.empty_chat_suggest_1,
2234+ R.string.empty_chat_suggest_2,
2235+ R.string.empty_chat_suggest_3,
2236+ )
2237+ }
2238+ Column(
2239+ modifier = modifier.padding(32.dp),
2240+ horizontalAlignment = Alignment.CenterHorizontally,
2241+ ) {
2242+ Icon(
2243+ Icons.Filled.AutoAwesome,
2244+ contentDescription = null,
2245+ modifier = Modifier.size(48.dp),
2246+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
2247+ )
2248+ Spacer(Modifier.size(16.dp))
2249+ Text(
2250+ stringResource(R.string.empty_chat_title),
2251+ style = MaterialTheme.typography.titleMedium,
2252+ )
2253+ Spacer(Modifier.size(8.dp))
2254+ Text(
2255+ stringResource(R.string.empty_chat_hint),
2256+ style = MaterialTheme.typography.bodyMedium,
2257+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2258+ )
2259+ Spacer(Modifier.size(20.dp))
2260+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2261+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
2262+ FlowRow(
2263+ modifier = Modifier.fillMaxWidth(),
2264+ horizontalArrangement = Arrangement.spacedBy(8.dp),
2265+ verticalArrangement = Arrangement.spacedBy(8.dp),
2266+ ) {
2267+ suggestions.forEach { resId ->
2268+ val text = stringResource(resId)
2269+ androidx.compose.material3.AssistChip(
2270+ onClick = { onSuggestion(text) },
2271+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2272+ )
2273+ }
2274+ }
2275+ }
2276+}
2277+
2278+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2279+ * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2280+ * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2281+@Composable
2282+private fun RevertBanner(diff: String?, onUndo: () -> Unit) {
2283+ val haptics = LocalHapticFeedback.current
2284+ var showDiff by rememberSaveable { mutableStateOf(false) }
2285+ val expandMotion = rememberVisibilityTransitions()
2286+ Surface(
2287+ color = MaterialTheme.colorScheme.tertiaryContainer,
2288+ tonalElevation = 2.dp,
2289+ modifier = Modifier.fillMaxWidth(),
2290+ ) {
2291+ Column {
2292+ Row(
2293+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2294+ verticalAlignment = Alignment.CenterVertically,
2295+ horizontalArrangement = Arrangement.SpaceBetween,
2296+ ) {
2297+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2298+ Icon(
2299+ Icons.Filled.Restore,
2300+ contentDescription = null,
2301+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
2302+ modifier = Modifier.size(18.dp),
2303+ )
2304+ Text(
2305+ stringResource(R.string.reverted_banner),
2306+ style = MaterialTheme.typography.bodySmall,
2307+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2308+ modifier = Modifier.padding(start = 8.dp),
2309+ )
2310+ // "Show what changed" toggle, shown only when the server provided a diff.
2311+ // Collapsible so the banner stays compact by default; a user curious about
2312+ // what the revert rolled back can expand it inline without leaving the chat.
2313+ if (!diff.isNullOrBlank()) {
2314+ TextButton(
2315+ onClick = {
2316+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2317+ showDiff = !showDiff
2318+ },
2319+ contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2320+ ) {
2321+ Icon(
2322+ if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2323+ contentDescription = null,
2324+ modifier = Modifier.size(16.dp),
2325+ )
2326+ Text(
2327+ stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2328+ style = MaterialTheme.typography.labelSmall,
2329+ modifier = Modifier.padding(start = 4.dp),
2330+ )
2331+ }
2332+ }
2333+ }
2334+ TextButton(onClick = {
2335+ // Haptic on undo to match the other destructive/important confirmations: a
2336+ // revert restores potentially hundreds of hidden messages.
2337+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2338+ onUndo()
2339+ }) { Text(stringResource(R.string.undo)) }
2340+ }
2341+ // The diff render lives inside the banner's Surface so it inherits the tertiary
2342+ // tonal container and reads as part of the banner, not a floating panel.
2343+ if (!diff.isNullOrBlank()) {
2344+ AnimatedVisibility(
2345+ visible = showDiff,
2346+ enter = expandMotion.enter,
2347+ exit = expandMotion.exit,
2348+ ) {
2349+ Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2350+ Text(
2351+ stringResource(R.string.revert_diff_header),
2352+ style = MaterialTheme.typography.labelSmall,
2353+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2354+ modifier = Modifier.padding(bottom = 4.dp),
2355+ )
2356+ DiffView(diff, saveKey = "revertDiff")
2357+ }
2358+ }
2359+ }
2360+ }
2361+ }
2362+}
2363+
2364+/** A banner shown while messages composed offline are queued in the outbox, with a
2365+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2366+@Composable
2367+private fun OutboxBanner(
2368+ count: Int,
2369+ sending: Boolean,
2370+ onFlush: () -> Unit,
2371+ onDiscard: () -> Unit,
2372+) {
2373+ var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2374+ Surface(
2375+ color = MaterialTheme.colorScheme.secondaryContainer,
2376+ tonalElevation = 2.dp,
2377+ modifier = Modifier.fillMaxWidth(),
2378+ ) {
2379+ Row(
2380+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2381+ verticalAlignment = Alignment.CenterVertically,
2382+ horizontalArrangement = Arrangement.SpaceBetween,
2383+ ) {
2384+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2385+ if (sending) {
2386+ CircularProgressIndicator(
2387+ Modifier.size(16.dp),
2388+ strokeWidth = 2.dp,
2389+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2390+ )
2391+ Spacer(Modifier.size(8.dp))
2392+ }
2393+ Text(
2394+ if (sending) {
2395+ stringResource(R.string.outbox_sending)
2396+ } else {
2397+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2398+ stringResource(res, count)
2399+ },
2400+ style = MaterialTheme.typography.bodySmall,
2401+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2402+ )
2403+ }
2404+ if (!sending) {
2405+ val haptics = LocalHapticFeedback.current
2406+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2407+ TextButton(onClick = {
2408+ // Confirm before discarding all queued messages (irreversible), matching
2409+ // the confirmation pattern used by deleteSession and other destructive
2410+ // actions. Previously a single tap dropped every queued message.
2411+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2412+ showDiscardConfirm = true
2413+ }) {
2414+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2415+ }
2416+ }
2417+ }
2418+ }
2419+ if (showDiscardConfirm) {
2420+ androidx.compose.material3.AlertDialog(
2421+ onDismissRequest = { showDiscardConfirm = false },
2422+ title = { Text(stringResource(R.string.discard_queued_title)) },
2423+ text = { Text(stringResource(R.string.discard_queued_text, count)) },
2424+ confirmButton = {
2425+ androidx.compose.material3.TextButton(onClick = {
2426+ showDiscardConfirm = false
2427+ onDiscard()
2428+ }) { Text(stringResource(R.string.discard)) }
2429+ },
2430+ dismissButton = {
2431+ androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
2432+ Text(stringResource(R.string.cancel))
2433+ }
2434+ },
2435+ )
2436+ }
2437+}
2438+
2439+/** Prompt for a one-off shell command to run in the session's worktree. */
2440+@Composable
2441+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
2442+ var command by rememberSaveable { mutableStateOf("") }
2443+ AlertDialog(
2444+ onDismissRequest = onDismiss,
2445+ title = { Text(stringResource(R.string.run_shell_command)) },
2446+ text = {
2447+ OutlinedTextField(
2448+ value = command,
2449+ onValueChange = { command = it },
2450+ modifier = Modifier.fillMaxWidth(),
2451+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
2452+ label = { Text(stringResource(R.string.shell_command_label)) },
2453+ singleLine = true,
2454+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2455+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
2456+ )
2457+ },
2458+ confirmButton = {
2459+ TextButton(
2460+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
2461+ enabled = command.isNotBlank(),
2462+ ) { Text(stringResource(R.string.run)) }
2463+ },
2464+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
2465+ )
2466+}
2467+
2468+/**
2469+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
2470+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
2471+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
2472+ */
2473+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
2474+
2475+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
2476+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
2477+ * streaming, not just plain assistant text. O(1). */
2478+private fun streamingContentLength(part: Part?): Int = when (part) {
2479+ is TextPart -> part.text.length
2480+ is ReasoningPart -> part.text.length
2481+ is ToolPart -> when (val st = part.state) {
2482+ is ToolCompleted -> st.output?.length ?: 0
2483+ is ToolError -> st.error?.length ?: 0
2484+ is ToolRunning -> st.title?.length ?: 0
2485+ else -> 0
2486+ }
2487+ else -> 0
2488+}
2489+
2490+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
2491+ * dialog but lives in the chat screen so the user can rename without backing out to
2492+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
2493+@Composable
2494+private fun RenameSessionChatDialog(
2495+ initialTitle: String,
2496+ onDismiss: () -> Unit,
2497+ onConfirm: (String) -> Unit,
2498+) {
2499+ // Seed the field once (no key input) so a later external title change — e.g. opencode
2500+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
2501+ // doesn't re-initialize the box and discard the user's in-progress edit.
2502+ var title by rememberSaveable { mutableStateOf(initialTitle) }
2503+ AlertDialog(
2504+ onDismissRequest = onDismiss,
2505+ title = { Text(stringResource(R.string.rename_session_chat)) },
2506+ text = {
2507+ OutlinedTextField(
2508+ value = title,
2509+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
2510+ modifier = Modifier.fillMaxWidth(),
2511+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
2512+ label = { Text(stringResource(R.string.rename_session_chat)) },
2513+ singleLine = true,
2514+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2515+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
2516+ )
2517+ },
2518+ confirmButton = {
2519+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
2520+ Text(stringResource(R.string.save))
2521+ }
2522+ },
2523+ dismissButton = {
2524+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
2525+ },
2526+ )
2527+}
2528+
2529+/**
2530+ * A single item in the chat message list — either a [Message] bubble or a day
2531+ * [Separator] inserted before the first message of a new day. The separator shifts
2532+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
2533+ * the [List] of these items (not `messages.size`/`lastIndex`).
2534+ */
2535+private sealed interface MessageListItem {
2536+ val key: Any
2537+ val contentType: Any
2538+
2539+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
2540+ override val contentType: Any get() = message.info::class
2541+ }
2542+
2543+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
2544+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
2545+ // can share a label (e.g. an untimestamped message — empty label — between two
2546+ // same-day messages, or two untimestamped groups), and a label-only key would
2547+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
2548+ // stable for a given message ordering so slots aren't needlessly recreated.
2549+ override val key: Any get() = "sep_${ordinal}_$label"
2550+ // Separators share a contentType so the LazyColumn can recycle their slots.
2551+ override val contentType: Any get() = "separator"
2552+ }
2553+}
2554+
2555+/**
2556+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
2557+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
2558+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
2559+ * Messages with no timestamp are grouped under an empty-label separator only if they
2560+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
2561+ *
2562+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
2563+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
2564+ * labels; older days fall back to a locale-stable medium-date format.
2565+ */
2566+private fun buildMessageListItems(
2567+ messages: List<MessageWithParts>,
2568+ todayLabel: String,
2569+ yesterdayLabel: String,
2570+): List<MessageListItem> {
2571+ if (messages.isEmpty()) return emptyList()
2572+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
2573+ val dateFmt = mediumDateFormat()
2574+ val result = ArrayList<MessageListItem>(messages.size + 4)
2575+ val seenKeys = HashSet<String>(messages.size * 2)
2576+ var lastDayKey: String? = null
2577+ var sepOrdinal = 0
2578+ var emptyIdOrdinal = 0
2579+ var first = true
2580+ for (message in messages) {
2581+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
2582+ val dayKey = ts?.let { dayKey(it) } ?: ""
2583+ // Emit a separator before the very first message (so a leading un-timestamped message
2584+ // still gets the first divider, empty label and all), and thereafter only when crossing
2585+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
2586+ // neither emits its own separator nor resets the day — otherwise a following same-day
2587+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
2588+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
2589+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
2590+ }
2591+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
2592+ first = false
2593+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
2594+ // empty id — and the reducer intentionally keeps several such messages as distinct
2595+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
2596+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
2597+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
2598+ if (!seenKeys.add(key)) {
2599+ var suffix = 1
2600+ while (!seenKeys.add("$key#$suffix")) suffix++
2601+ key = "$key#$suffix"
2602+ }
2603+ result.add(MessageListItem.Message(message, key))
2604+ }
2605+ return result
2606+}
2607+
2608+/**
2609+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2610+ *
2611+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2612+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
2613+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2614+ * every message on every token. Message timestamps are immutable once assigned, so we
2615+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2616+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2617+ * thread during composition, so the coarse lock is uncontended.
2618+ */
2619+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2620+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2621+}
2622+
2623+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2624+ dayKeyCache.getOrPut(epochMillis) {
2625+ java.time.Instant.ofEpochMilli(epochMillis)
2626+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2627+ }
2628+}
2629+
2630+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2631+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2632+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2633+private var cachedDateFmt: java.text.DateFormat? = null
2634+private var cachedDateFmtLocale: java.util.Locale? = null
2635+
2636+private fun mediumDateFormat(): java.text.DateFormat {
2637+ val locale = java.util.Locale.getDefault()
2638+ val existing = cachedDateFmt
2639+ if (existing != null && cachedDateFmtLocale == locale) return existing
2640+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2641+ cachedDateFmt = it
2642+ cachedDateFmtLocale = locale
2643+ }
2644+}
2645+
2646+/**
2647+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2648+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2649+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2650+ * messages.
2651+ */
2652+private fun dayLabel(
2653+ dayKey: String,
2654+ ts: Long,
2655+ today: java.time.LocalDate,
2656+ todayLabel: String,
2657+ yesterdayLabel: String,
2658+ dateFmt: java.text.DateFormat,
2659+): String {
2660+ if (dayKey.isEmpty()) return ""
2661+ val epochDay = dayKey.toLongOrNull() ?: return ""
2662+ val date = java.time.LocalDate.ofEpochDay(epochDay)
2663+ return when {
2664+ date == today -> todayLabel
2665+ date == today.minusDays(1) -> yesterdayLabel
2666+ else -> dateFmt.format(java.util.Date(ts))
2667+ }
2668+}
2669+
2670+/**
2671+ * A centered day divider in the message list. Renders nothing for an empty label
2672+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2673+ */
2674+@Composable
2675+private fun DateSeparator(label: String) {
2676+ if (label.isBlank()) return
2677+ Row(
2678+ modifier = Modifier.fillMaxWidth(),
2679+ horizontalArrangement = Arrangement.Center,
2680+ ) {
2681+ Surface(
2682+ color = MaterialTheme.colorScheme.surfaceVariant,
2683+ shape = MaterialTheme.shapes.small,
2684+ // Marked as a heading so TalkBack users can navigate day-by-day with the
2685+ // heading-skip gesture — the canonical affordance for date dividers in a list.
2686+ modifier = Modifier.semantics(mergeDescendants = true) { heading() },
2687+ ) {
2688+ Text(
2689+ label,
2690+ style = MaterialTheme.typography.labelSmall,
2691+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2692+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
2693+ )
2694+ }
2695+ }
2696+}