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