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