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