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