@@ -0,0 +1,3352 @@
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+ if (enabled && hasContent) onSend()
2522+ },
2523+ ),
2524+ )
2525+ ComposerTrailingButton(
2526+ running = running,
2527+ aborting = aborting,
2528+ canSend = enabled && hasContent,
2529+ canQueue = enabled && value.isNotBlank(),
2530+ onSend = onSend,
2531+ onAbort = onAbort,
2532+ onQueue = { onQueueFollowUp(value) },
2533+ )
2534+ }
2535+ }
2536+ if (showFullScreenEditor) {
2537+ FullScreenEditor(
2538+ value = value,
2539+ onValueChange = onValueChange,
2540+ onDismiss = { showFullScreenEditor = false },
2541+ onSend = {
2542+ showFullScreenEditor = false
2543+ // Mirror the inline composer's behavior: while a run is active a send
2544+ // can't go immediately, so queue the follow-up instead of silently
2545+ // dropping it (vm.send() returns false during a run, which previously
2546+ // lost the typed message with no feedback).
2547+ if (running) onQueueFollowUp(value) else onSend()
2548+ },
2549+ canSend = enabled && hasContent,
2550+ running = running,
2551+ sendOnEnter = sendOnEnter,
2552+ attachments = attachments,
2553+ onRemoveAttachment = onRemoveAttachment,
2554+ staging = staging,
2555+ stagingFileCount = stagingFileCount,
2556+ )
2557+ }
2558+ }
2559+}
2560+
2561+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2562+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2563+@OptIn(ExperimentalMaterial3Api::class)
2564+@Composable
2565+private fun FullScreenEditor(
2566+ value: String,
2567+ onValueChange: (String) -> Unit,
2568+ onDismiss: () -> Unit,
2569+ onSend: () -> Unit,
2570+ canSend: Boolean,
2571+ running: Boolean = false,
2572+ sendOnEnter: Boolean = false,
2573+ attachments: List<PendingAttachment> = emptyList(),
2574+ onRemoveAttachment: (String) -> Unit = {},
2575+ staging: Boolean = false,
2576+ stagingFileCount: Int = 0,
2577+) {
2578+ androidx.compose.ui.window.Dialog(
2579+ onDismissRequest = onDismiss,
2580+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2581+ ) {
2582+ // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2583+ // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2584+ // gives the available width so we can center a capped-width column.
2585+ androidx.compose.foundation.layout.BoxWithConstraints(
2586+ modifier = Modifier.fillMaxSize(),
2587+ contentAlignment = Alignment.Center,
2588+ ) {
2589+ val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2590+ ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2591+ else 0.dp
2592+ Scaffold(
2593+ modifier = Modifier.padding(horizontal = hPad),
2594+ topBar = {
2595+ androidx.compose.material3.TopAppBar(
2596+ title = { Text(stringResource(R.string.compose_editor_title)) },
2597+ navigationIcon = {
2598+ androidx.compose.material3.TextButton(onClick = onDismiss) {
2599+ Text(stringResource(R.string.collapse_editor))
2600+ }
2601+ },
2602+ )
2603+ },
2604+ bottomBar = {
2605+ Surface(tonalElevation = 3.dp) {
2606+ Row(
2607+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2608+ horizontalArrangement = Arrangement.End,
2609+ ) {
2610+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2611+ Text(stringResource(if (running) R.string.queue else R.string.send))
2612+ }
2613+ }
2614+ }
2615+ },
2616+ ) { padding ->
2617+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2618+ // Show staged attachments in the full-screen editor too, so a user who staged
2619+ // images then expanded for a long prompt can still see and remove them without
2620+ // collapsing first (mirrors the inline composer's AttachmentStrip).
2621+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2622+ OutlinedTextField(
2623+ value = value,
2624+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2625+ modifier = Modifier
2626+ .fillMaxSize()
2627+ .weight(1f)
2628+ // Honor the "Send on Enter" setting here too, so the full-screen
2629+ // editor matches the inline composer: Enter sends (Shift+Enter
2630+ // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2631+ // when off. Previously this hard-coded ImeAction.Default and had no
2632+ // key handler, so a hardware-keyboard user got a different behaviour
2633+ // from the inline composer depending on which they happened to open.
2634+ .onPreviewKeyEvent { event ->
2635+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2636+ val send = enterShouldSend(
2637+ enabled = canSend,
2638+ hasContent = canSend,
2639+ sendOnEnter = sendOnEnter,
2640+ shift = event.isShiftPressed,
2641+ ctrl = event.isCtrlPressed,
2642+ )
2643+ if (send) { onSend(); true } else false
2644+ },
2645+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
2646+ maxLines = Int.MAX_VALUE,
2647+ keyboardOptions = KeyboardOptions(
2648+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2649+ capitalization = KeyboardCapitalization.Sentences,
2650+ ),
2651+ keyboardActions = KeyboardActions(
2652+ onSend = { if (canSend) onSend() },
2653+ ),
2654+ )
2655+ }
2656+ }
2657+ }
2658+ }
2659+}
2660+
2661+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2662+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2663+private fun enterShouldSend(
2664+ enabled: Boolean,
2665+ hasContent: Boolean,
2666+ sendOnEnter: Boolean,
2667+ shift: Boolean,
2668+ ctrl: Boolean,
2669+): Boolean = when {
2670+ !enabled || !hasContent -> false
2671+ sendOnEnter -> !shift
2672+ else -> ctrl
2673+}
2674+
2675+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2676+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2677+ * [ChatInputBar] stays under the complexity threshold. */
2678+@Composable
2679+private fun ComposerTrailingButton(
2680+ running: Boolean,
2681+ aborting: Boolean,
2682+ canSend: Boolean,
2683+ canQueue: Boolean,
2684+ onSend: () -> Unit,
2685+ onAbort: () -> Unit,
2686+ onQueue: () -> Unit,
2687+) {
2688+ if (running) {
2689+ Row(verticalAlignment = Alignment.CenterVertically) {
2690+ // While a run is active the trailing action is Stop, so the only send affordance is
2691+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2692+ // That leaves a touch-only user with the setting off no way to queue a follow-up
2693+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2694+ // there's typed TEXT so queuing is always reachable, without changing the user's
2695+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2696+ // canSend, which is also true for an attachment-only composer — because queuing "" just
2697+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2698+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2699+ if (canQueue) {
2700+ IconButton(
2701+ onClick = onQueue,
2702+ modifier = Modifier.testTag("queue_button"),
2703+ ) {
2704+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2705+ // icon (which can be read as "snooze" or "later"), and isn't confused with
2706+ // the Send action sitting right beside the Stop button.
2707+ Icon(
2708+ Icons.AutoMirrored.Filled.PlaylistAdd,
2709+ contentDescription = stringResource(R.string.queue_followup),
2710+ )
2711+ }
2712+ }
2713+ // Show a spinner while the abort REST call is in flight so the user sees the stop
2714+ // was sent, and disable to prevent a double-tap.
2715+ IconButton(
2716+ onClick = onAbort,
2717+ enabled = !aborting,
2718+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2719+ ) {
2720+ if (aborting) {
2721+ val stopLabel = stringResource(R.string.stop)
2722+ CircularProgressIndicator(
2723+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2724+ strokeWidth = 2.dp,
2725+ )
2726+ } else {
2727+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2728+ }
2729+ }
2730+ }
2731+ } else {
2732+ IconButton(
2733+ onClick = onSend,
2734+ enabled = canSend,
2735+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2736+ ) {
2737+ // Tint the send icon with primary when there's content to send so the commit action
2738+ // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2739+ Icon(
2740+ Icons.AutoMirrored.Filled.Send,
2741+ contentDescription = stringResource(R.string.send),
2742+ tint = if (canSend) MaterialTheme.colorScheme.primary
2743+ else MaterialTheme.colorScheme.onSurfaceVariant,
2744+ )
2745+ }
2746+ }
2747+}
2748+
2749+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2750+@Composable
2751+private fun EmptyConversation(
2752+ onSuggestion: (String) -> Unit,
2753+ modifier: Modifier = Modifier,
2754+) {
2755+ // A few example prompts so a first-time user has a one-tap path to their first
2756+ // message instead of staring at a blank input. Tapping a chip fills the draft
2757+ // (without sending) so the user can edit it before sending.
2758+ val suggestions = remember {
2759+ listOf(
2760+ R.string.empty_chat_suggest_1,
2761+ R.string.empty_chat_suggest_2,
2762+ R.string.empty_chat_suggest_3,
2763+ )
2764+ }
2765+ Column(
2766+ modifier = modifier.padding(32.dp),
2767+ horizontalAlignment = Alignment.CenterHorizontally,
2768+ ) {
2769+ Icon(
2770+ Icons.Filled.AutoAwesome,
2771+ contentDescription = null,
2772+ modifier = Modifier.size(48.dp),
2773+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
2774+ )
2775+ Spacer(Modifier.size(16.dp))
2776+ Text(
2777+ stringResource(R.string.empty_chat_title),
2778+ style = MaterialTheme.typography.titleMedium,
2779+ )
2780+ Spacer(Modifier.size(8.dp))
2781+ Text(
2782+ stringResource(R.string.empty_chat_hint),
2783+ style = MaterialTheme.typography.bodyMedium,
2784+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2785+ )
2786+ Spacer(Modifier.size(20.dp))
2787+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2788+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
2789+ FlowRow(
2790+ modifier = Modifier.fillMaxWidth(),
2791+ horizontalArrangement = Arrangement.spacedBy(8.dp),
2792+ verticalArrangement = Arrangement.spacedBy(8.dp),
2793+ ) {
2794+ suggestions.forEach { resId ->
2795+ val text = stringResource(resId)
2796+ androidx.compose.material3.AssistChip(
2797+ onClick = { onSuggestion(text) },
2798+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2799+ )
2800+ }
2801+ }
2802+ }
2803+}
2804+
2805+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2806+ * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2807+ * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2808+@Composable
2809+private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2810+ val haptics = LocalHapticFeedback.current
2811+ var showDiff by rememberSaveable { mutableStateOf(false) }
2812+ val expandMotion = rememberVisibilityTransitions()
2813+ Surface(
2814+ color = MaterialTheme.colorScheme.tertiaryContainer,
2815+ tonalElevation = 2.dp,
2816+ modifier = Modifier.fillMaxWidth(),
2817+ ) {
2818+ Column {
2819+ Row(
2820+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2821+ verticalAlignment = Alignment.CenterVertically,
2822+ horizontalArrangement = Arrangement.SpaceBetween,
2823+ ) {
2824+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2825+ Icon(
2826+ if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2827+ contentDescription = null,
2828+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
2829+ modifier = Modifier.size(18.dp),
2830+ )
2831+ Text(
2832+ stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2833+ style = MaterialTheme.typography.bodySmall,
2834+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2835+ modifier = Modifier.padding(start = 8.dp),
2836+ )
2837+ // "Show what changed" toggle, shown only when the server provided a diff.
2838+ // Collapsible so the banner stays compact by default; a user curious about
2839+ // what the revert rolled back can expand it inline without leaving the chat.
2840+ if (!diff.isNullOrBlank()) {
2841+ TextButton(
2842+ onClick = {
2843+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2844+ showDiff = !showDiff
2845+ },
2846+ contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2847+ ) {
2848+ Icon(
2849+ if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2850+ contentDescription = null,
2851+ modifier = Modifier.size(16.dp),
2852+ )
2853+ Text(
2854+ stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2855+ style = MaterialTheme.typography.labelSmall,
2856+ modifier = Modifier.padding(start = 4.dp),
2857+ )
2858+ }
2859+ }
2860+ }
2861+ TextButton(onClick = {
2862+ // Haptic on undo to match the other destructive/important confirmations: a
2863+ // revert restores potentially hundreds of hidden messages.
2864+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2865+ onUndo()
2866+ }) { Text(stringResource(R.string.undo)) }
2867+ }
2868+ // The diff render lives inside the banner's Surface so it inherits the tertiary
2869+ // tonal container and reads as part of the banner, not a floating panel.
2870+ if (!diff.isNullOrBlank()) {
2871+ AnimatedVisibility(
2872+ visible = showDiff,
2873+ enter = expandMotion.enter,
2874+ exit = expandMotion.exit,
2875+ ) {
2876+ Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2877+ Text(
2878+ stringResource(R.string.revert_diff_header),
2879+ style = MaterialTheme.typography.labelSmall,
2880+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2881+ modifier = Modifier.padding(bottom = 4.dp),
2882+ )
2883+ DiffView(diff, saveKey = "revertDiff")
2884+ }
2885+ }
2886+ }
2887+ }
2888+ }
2889+}
2890+
2891+/** A dismissible preview card shown above the composer when the user quote-replied to a
2892+ * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2893+ * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2894+ * the Discord/Slack quote-preview pattern. */
2895+@Composable
2896+private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2897+ val haptics = LocalHapticFeedback.current
2898+ Surface(
2899+ color = MaterialTheme.colorScheme.secondaryContainer,
2900+ tonalElevation = 2.dp,
2901+ modifier = Modifier.fillMaxWidth(),
2902+ ) {
2903+ Row(
2904+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2905+ verticalAlignment = Alignment.Top,
2906+ ) {
2907+ Icon(
2908+ Icons.Filled.FormatQuote,
2909+ contentDescription = null,
2910+ tint = MaterialTheme.colorScheme.onSecondaryContainer,
2911+ modifier = Modifier.size(18.dp).padding(top = 2.dp),
2912+ )
2913+ Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2914+ Text(
2915+ stringResource(R.string.quote_reply_banner),
2916+ style = MaterialTheme.typography.labelSmall,
2917+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2918+ )
2919+ Text(
2920+ quotedText,
2921+ style = MaterialTheme.typography.bodySmall,
2922+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2923+ maxLines = 2,
2924+ overflow = TextOverflow.Ellipsis,
2925+ )
2926+ }
2927+ IconButton(onClick = {
2928+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2929+ onCancel()
2930+ }) {
2931+ Icon(
2932+ Icons.Filled.Close,
2933+ contentDescription = stringResource(R.string.cancel_quote_reply),
2934+ tint = MaterialTheme.colorScheme.onSecondaryContainer,
2935+ modifier = Modifier.size(18.dp),
2936+ )
2937+ }
2938+ }
2939+ }
2940+}
2941+
2942+/** A banner shown while messages composed offline are queued in the outbox, with a
2943+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2944+@Composable
2945+private fun OutboxBanner(
2946+ count: Int,
2947+ sending: Boolean,
2948+ onFlush: () -> Unit,
2949+ onDiscard: () -> Unit,
2950+) {
2951+ var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2952+ Surface(
2953+ color = MaterialTheme.colorScheme.secondaryContainer,
2954+ tonalElevation = 2.dp,
2955+ modifier = Modifier.fillMaxWidth(),
2956+ ) {
2957+ Row(
2958+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2959+ verticalAlignment = Alignment.CenterVertically,
2960+ horizontalArrangement = Arrangement.SpaceBetween,
2961+ ) {
2962+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2963+ if (sending) {
2964+ CircularProgressIndicator(
2965+ Modifier.size(16.dp),
2966+ strokeWidth = 2.dp,
2967+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2968+ )
2969+ Spacer(Modifier.size(8.dp))
2970+ }
2971+ Text(
2972+ if (sending) {
2973+ stringResource(R.string.outbox_sending)
2974+ } else {
2975+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2976+ stringResource(res, count)
2977+ },
2978+ style = MaterialTheme.typography.bodySmall,
2979+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2980+ )
2981+ }
2982+ if (!sending) {
2983+ val haptics = LocalHapticFeedback.current
2984+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2985+ TextButton(onClick = {
2986+ // Confirm before discarding all queued messages (irreversible), matching
2987+ // the confirmation pattern used by deleteSession and other destructive
2988+ // actions. Previously a single tap dropped every queued message.
2989+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2990+ showDiscardConfirm = true
2991+ }) {
2992+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2993+ }
2994+ }
2995+ }
2996+ }
2997+ if (showDiscardConfirm) {
2998+ androidx.compose.material3.AlertDialog(
2999+ onDismissRequest = { showDiscardConfirm = false },
3000+ title = { Text(stringResource(R.string.discard_queued_title)) },
3001+ text = { Text(stringResource(R.string.discard_queued_text, count)) },
3002+ confirmButton = {
3003+ androidx.compose.material3.TextButton(onClick = {
3004+ showDiscardConfirm = false
3005+ onDiscard()
3006+ }) { Text(stringResource(R.string.discard)) }
3007+ },
3008+ dismissButton = {
3009+ androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3010+ Text(stringResource(R.string.cancel))
3011+ }
3012+ },
3013+ )
3014+ }
3015+}
3016+
3017+/** Prompt for a one-off shell command to run in the session's worktree. */
3018+@Composable
3019+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3020+ var command by rememberSaveable { mutableStateOf("") }
3021+ AlertDialog(
3022+ onDismissRequest = onDismiss,
3023+ title = { Text(stringResource(R.string.run_shell_command)) },
3024+ text = {
3025+ OutlinedTextField(
3026+ value = command,
3027+ onValueChange = { command = it },
3028+ modifier = Modifier.fillMaxWidth(),
3029+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3030+ label = { Text(stringResource(R.string.shell_command_label)) },
3031+ singleLine = true,
3032+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3033+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3034+ )
3035+ },
3036+ confirmButton = {
3037+ TextButton(
3038+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3039+ enabled = command.isNotBlank(),
3040+ ) { Text(stringResource(R.string.run)) }
3041+ },
3042+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3043+ )
3044+}
3045+
3046+/**
3047+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3048+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3049+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
3050+ */
3051+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3052+
3053+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3054+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3055+ * streaming, not just plain assistant text. O(1). */
3056+private fun streamingContentLength(part: Part?): Int = when (part) {
3057+ is TextPart -> part.text.length
3058+ is ReasoningPart -> part.text.length
3059+ is ToolPart -> when (val st = part.state) {
3060+ is ToolCompleted -> st.output?.length ?: 0
3061+ is ToolError -> st.error?.length ?: 0
3062+ is ToolRunning -> st.title?.length ?: 0
3063+ else -> 0
3064+ }
3065+ else -> 0
3066+}
3067+
3068+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3069+ * dialog but lives in the chat screen so the user can rename without backing out to
3070+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
3071+@Composable
3072+private fun RenameSessionChatDialog(
3073+ initialTitle: String,
3074+ onDismiss: () -> Unit,
3075+ onConfirm: (String) -> Unit,
3076+) {
3077+ // Seed the field once (no key input) so a later external title change — e.g. opencode
3078+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3079+ // doesn't re-initialize the box and discard the user's in-progress edit.
3080+ var title by rememberSaveable { mutableStateOf(initialTitle) }
3081+ AlertDialog(
3082+ onDismissRequest = onDismiss,
3083+ title = { Text(stringResource(R.string.rename_session_chat)) },
3084+ text = {
3085+ OutlinedTextField(
3086+ value = title,
3087+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3088+ modifier = Modifier.fillMaxWidth(),
3089+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
3090+ label = { Text(stringResource(R.string.rename_session_chat)) },
3091+ singleLine = true,
3092+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3093+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3094+ )
3095+ },
3096+ confirmButton = {
3097+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3098+ Text(stringResource(R.string.save))
3099+ }
3100+ },
3101+ dismissButton = {
3102+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3103+ },
3104+ )
3105+}
3106+
3107+/**
3108+ * A single item in the chat message list — either a [Message] bubble or a day
3109+ * [Separator] inserted before the first message of a new day. The separator shifts
3110+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3111+ * the [List] of these items (not `messages.size`/`lastIndex`).
3112+ */
3113+private sealed interface MessageListItem {
3114+ val key: Any
3115+ val contentType: Any
3116+
3117+ data class Message(
3118+ val message: MessageWithParts,
3119+ override val key: Any,
3120+ // Whether this is the first message in a consecutive run of the same speaker (role).
3121+ // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3122+ // reducing visual noise in tool-heavy conversations where many assistant messages
3123+ // appear back-to-back. A separator or a role change resets the flag.
3124+ val isFirstOfSpeaker: Boolean,
3125+ ) : MessageListItem {
3126+ override val contentType: Any get() = message.info::class
3127+ }
3128+
3129+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3130+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3131+ // can share a label (e.g. an untimestamped message — empty label — between two
3132+ // same-day messages, or two untimestamped groups), and a label-only key would
3133+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3134+ // stable for a given message ordering so slots aren't needlessly recreated.
3135+ override val key: Any get() = "sep_${ordinal}_$label"
3136+ // Separators share a contentType so the LazyColumn can recycle their slots.
3137+ override val contentType: Any get() = "separator"
3138+ }
3139+}
3140+
3141+/**
3142+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3143+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3144+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3145+ * Messages with no timestamp are grouped under an empty-label separator only if they
3146+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
3147+ *
3148+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3149+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3150+ * labels; older days fall back to a locale-stable medium-date format.
3151+ */
3152+private fun buildMessageListItems(
3153+ messages: List<MessageWithParts>,
3154+ todayLabel: String,
3155+ yesterdayLabel: String,
3156+): List<MessageListItem> {
3157+ if (messages.isEmpty()) return emptyList()
3158+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3159+ val dateFmt = mediumDateFormat()
3160+ val result = ArrayList<MessageListItem>(messages.size + 4)
3161+ val seenKeys = HashSet<String>(messages.size * 2)
3162+ var lastDayKey: String? = null
3163+ var sepOrdinal = 0
3164+ var emptyIdOrdinal = 0
3165+ var first = true
3166+ // Track the previous message's role to detect consecutive same-speaker runs, so the
3167+ // avatar/header can be suppressed on follow-up messages in the same run. A null means
3168+ // "no previous message or a separator just interrupted the run", both of which make the
3169+ // next message the first of its group.
3170+ var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3171+ for (message in messages) {
3172+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3173+ val dayKey = ts?.let { dayKey(it) } ?: ""
3174+ // Emit a separator before the very first message (so a leading un-timestamped message
3175+ // still gets the first divider, empty label and all), and thereafter only when crossing
3176+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3177+ // neither emits its own separator nor resets the day — otherwise a following same-day
3178+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3179+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3180+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3181+ // A date separator visually breaks a speaker run, so the next message is treated
3182+ // as the first of its group (even if the same role continues across the day break).
3183+ prevRoleClass = null
3184+ }
3185+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
3186+ first = false
3187+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3188+ // empty id — and the reducer intentionally keeps several such messages as distinct
3189+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
3190+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3191+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3192+ if (!seenKeys.add(key)) {
3193+ var suffix = 1
3194+ while (!seenKeys.add("$key#$suffix")) suffix++
3195+ key = "$key#$suffix"
3196+ }
3197+ val roleClass = message.info::class
3198+ val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3199+ result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3200+ prevRoleClass = roleClass
3201+ }
3202+ return result
3203+}
3204+
3205+/**
3206+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3207+ *
3208+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3209+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
3210+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3211+ * every message on every token. Message timestamps are immutable once assigned, so we
3212+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3213+ * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3214+ *
3215+ * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3216+ * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3217+ * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3218+ * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3219+ * reads, so the common case (a hit) is a single volatile read + hash probe. The bound
3220+ * is enforced via [removeEldestEntry] is not available on ConcurrentHashMap, so we cap
3221+ * via `compute`-guarded size checks; in practice the cache size is bounded by the number
3222+ * of distinct message timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]).
3223+ */
3224+private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3225+
3226+private fun dayKey(epochMillis: Long): String = dayKeyCache.getOrPut(epochMillis) {
3227+ java.time.Instant.ofEpochMilli(epochMillis)
3228+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3229+}
3230+
3231+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3232+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3233+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3234+private var cachedDateFmt: java.text.DateFormat? = null
3235+private var cachedDateFmtLocale: java.util.Locale? = null
3236+
3237+private fun mediumDateFormat(): java.text.DateFormat {
3238+ val locale = java.util.Locale.getDefault()
3239+ val existing = cachedDateFmt
3240+ if (existing != null && cachedDateFmtLocale == locale) return existing
3241+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3242+ cachedDateFmt = it
3243+ cachedDateFmtLocale = locale
3244+ }
3245+}
3246+
3247+/**
3248+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3249+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3250+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3251+ * messages.
3252+ */
3253+private fun dayLabel(
3254+ dayKey: String,
3255+ ts: Long,
3256+ today: java.time.LocalDate,
3257+ todayLabel: String,
3258+ yesterdayLabel: String,
3259+ dateFmt: java.text.DateFormat,
3260+): String {
3261+ if (dayKey.isEmpty()) return ""
3262+ val epochDay = dayKey.toLongOrNull() ?: return ""
3263+ val date = java.time.LocalDate.ofEpochDay(epochDay)
3264+ return when {
3265+ date == today -> todayLabel
3266+ date == today.minusDays(1) -> yesterdayLabel
3267+ else -> dateFmt.format(java.util.Date(ts))
3268+ }
3269+}
3270+
3271+/**
3272+ * A centered day divider in the message list. Renders nothing for an empty label
3273+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3274+ */
3275+@Composable
3276+private fun DateSeparator(label: String) {
3277+ if (label.isBlank()) return
3278+ Row(
3279+ modifier = Modifier.fillMaxWidth(),
3280+ horizontalArrangement = Arrangement.Center,
3281+ ) {
3282+ Surface(
3283+ color = MaterialTheme.colorScheme.surfaceVariant,
3284+ shape = MaterialTheme.shapes.small,
3285+ // Marked as a heading so TalkBack users can navigate day-by-day with the
3286+ // heading-skip gesture — the canonical affordance for date dividers in a list.
3287+ modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3288+ ) {
3289+ Text(
3290+ label,
3291+ style = MaterialTheme.typography.labelSmall,
3292+ color = MaterialTheme.colorScheme.onSurfaceVariant,
3293+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3294+ )
3295+ }
3296+ }
3297+}
3298+
3299+/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3300+ * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3301+ * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3302+ * [BoxScope] extension so it can align itself to the top center of its host box. */
3303+@Composable
3304+private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3305+ val loadingLabel = stringResource(R.string.loading)
3306+ val reducedMotion = LocalReducedMotion.current
3307+ val transition = rememberInfiniteTransition(label = "skeleton")
3308+ val pulse by transition.animateFloat(
3309+ initialValue = 0.35f,
3310+ targetValue = 0.7f,
3311+ animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3312+ label = "skeletonAlpha",
3313+ )
3314+ val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3315+ val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3316+ @Composable
3317+ fun bar(widthFraction: Float) {
3318+ Box(
3319+ Modifier
3320+ .fillMaxWidth(widthFraction)
3321+ .height(14.dp)
3322+ .clip(RoundedCornerShape(4.dp))
3323+ .background(skeletonColor)
3324+ .alpha(skeletonAlpha),
3325+ )
3326+ }
3327+ Column(
3328+ modifier = Modifier
3329+ .align(Alignment.TopCenter)
3330+ .padding(top = topPad)
3331+ .padding(16.dp)
3332+ .fillMaxWidth()
3333+ .semantics { contentDescription = loadingLabel },
3334+ verticalArrangement = Arrangement.spacedBy(14.dp),
3335+ ) {
3336+ repeat(4) { i ->
3337+ val left = i % 2 == 0
3338+ Row(
3339+ modifier = Modifier.fillMaxWidth(),
3340+ horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3341+ ) {
3342+ Column(
3343+ modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3344+ verticalArrangement = Arrangement.spacedBy(6.dp),
3345+ ) {
3346+ bar(1f)
3347+ bar(0.8f)
3348+ }
3349+ }
3350+ }
3351+ }
3352+}