@@ -0,0 +1,3452 @@
1+@file:Suppress("TooManyFunctions")
3+package soy.iko.opencode.ui.chat
5+import android.app.Activity
6+import android.content.Intent
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
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
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)
202+ container: AppContainer,
205+ onOpenFile: ((String) -> Unit)? = null,
206+ onOpenSession: ((String) -> Unit)? = null,
207+ focusMessageId: String? = null,
208+ onEditProfile: ((String) -> Unit)? = null,
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) {
259+ append(selectedModel?.modelLabel ?: defaultModelLabel)
260+ selectedAgent?.let { append(" · $it") }
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()
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) }
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))
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) }
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,
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 })
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 }
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)
365+ snackbar.showSnackbar(event.message)
367+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
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()
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.
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) }
408+ val dismisser = launch {
409+ delay(NetworkConfig.undoDeleteDelayMs)
410+ snackbar.currentSnackbarData?.dismiss()
412+ val result = snackbar.showSnackbar(
413+ message = sessionDeletedLabel,
414+ actionLabel = undoLabel,
415+ duration = SnackbarDuration.Indefinite,
418+ if (result == SnackbarResult.ActionPerformed) {
419+ vm.cancelSessionDelete(id)
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)
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()
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)
449+ val photoPicker = rememberLauncherForActivityResult(
450+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
451+ ) { uris -> stageUris(uris) }
453+ val filePicker = rememberLauncherForActivityResult(
454+ ActivityResultContracts.GetMultipleContents(),
455+ ) { uris -> stageUris(uris) }
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(),
462+ val uri = pendingCaptureUri
463+ pendingCaptureUri = null
464+ if (success && uri != null) stageUris(listOf(uri))
467+ val voiceLauncher = rememberLauncherForActivityResult(
468+ ActivityResultContracts.StartActivityForResult(),
470+ if (result.resultCode == Activity.RESULT_OK) {
471+ val spoken = result.data
472+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
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))
485+ fun launchCamera() {
486+ val uri = newCameraCaptureUri(appContext)
488+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
491+ pendingCaptureUri = uri
492+ runCatching { cameraLauncher.launch(uri) }
493+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
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)
501+ runCatching { voiceLauncher.launch(intent) }
502+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
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)
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)
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) })
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)
550+ // The in-conversation search bar is an AnimatedVisibility overlay (not a Dialog/Dropdown),
551+ // so it has no built-in back handling. Close it first on back press, before the exit
552+ // confirmation or navigation-away can fire — standard Android "back closes the topmost
553+ // overlay" behavior. Declared before the exit-confirm BackHandler so it takes precedence
554+ // when both could be active (search open + a run in progress).
555+ BackHandler(enabled = searchActive) {
556+ searchActive = false
560+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker && !searchActive) { showExitConfirm = true }
563+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
564+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
565+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
566+ // typing (and the composer's own Enter-to-send handling) is untouched.
567+ modifier = Modifier.onPreviewKeyEvent { ev ->
568+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
570+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
571+ // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
572+ // the field so the user can type immediately.
573+ ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
574+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
575+ ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
576+ ev.key == Key.Escape && running && !showExitConfirm -> {
585+ val changeLabel = stringResource(R.string.change_model_agent)
586+ // The subtitle reads "model · agent", so tapping the title offers *both*
587+ // — a small menu picks which picker to open. Previously the tap went
588+ // straight to the model picker, leaving the agent changeable only via
589+ // the overflow menu despite the title implying otherwise.
592+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
593+ // node; the click label rides on `clickable` (onClickLabel) instead of
594+ // an explicit contentDescription, which would have SUPPRESSED the child
595+ // Texts and announced only "Change model and agent".
599+ onClickLabel = changeLabel,
600+ ) { showTitleMenu = true }
601+ .semantics(mergeDescendants = true) {},
602+ verticalAlignment = Alignment.CenterVertically,
604+ Column(modifier = Modifier.weight(1f, fill = false)) {
605+ // maxLines=1 + Ellipsis so a long session title can't wrap and
606+ // push the top bar to multiple lines, shifting the whole layout.
608+ sessionTitle ?: sessionLabel,
610+ overflow = TextOverflow.Ellipsis,
614+ style = MaterialTheme.typography.labelSmall,
615+ color = MaterialTheme.colorScheme.onSurfaceVariant,
617+ overflow = TextOverflow.Ellipsis,
620+ // Always show the affordance so the title reads as tappable even when
621+ // the model catalog failed to load (models empty). Without it the title
622+ // is indistinguishable from plain text and the pickers are effectively
623+ // undiscoverable — and the dropdown items already disable themselves
624+ // while a catalog is loading or unavailable.
626+ Icons.Filled.KeyboardArrowDown,
627+ contentDescription = null,
628+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
629+ modifier = Modifier.size(20.dp),
632+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
634+ text = { Text(stringResource(R.string.palette_switch_model)) },
635+ enabled = !modelsLoading || models.isNotEmpty(),
636+ onClick = { showTitleMenu = false; showModelPicker = true },
639+ text = { Text(stringResource(R.string.palette_choose_agent)) },
640+ enabled = !agentsLoading || agents.isNotEmpty(),
641+ onClick = { showTitleMenu = false; showAgentPicker = true },
647+ IconButton(onClick = {
648+ if (running) showExitConfirm = true else onBack()
650+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
654+ // At-a-glance run status in the top bar. When the user is scrolled
655+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
656+ // trailing "working…" row are off-screen, so a top-bar spinner is the
657+ // only signal the agent is still working.
659+ val workingLabel = stringResource(R.string.working)
660+ CircularProgressIndicator(
661+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
665+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
666+ // from REST. A recovery path when the stream silently drops and the
667+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
668+ // immediate tap feedback — the SSE reconnect may not visibly change
669+ // the connection state when already Connected, so without it the tap
670+ // appears to do nothing. Disabled while a run is active: a mid-run
671+ // refresh forces a reconnect that can interrupt the streaming reply,
672+ // and the working spinner already signals "wait" — the recovery path
673+ // is only needed when nothing is actively streaming.
674+ val refreshLabel = stringResource(R.string.refresh)
676+ onClick = { vm.refreshMessages() },
677+ enabled = activeConnection != null && !refreshing && !running,
680+ CircularProgressIndicator(
681+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
685+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
688+ // Overflow menu consolidates the less-frequent actions (share,
689+ // commands, agent, model, rename, delete) so the top bar stays
690+ // scannable on narrow phones — previously 5 icons crowded the bar
691+ // alongside the back button and tappable title. Catalog-loading
692+ // spinners stay inline (next to the overflow) so a load state is
693+ // visible without opening the menu.
694+ val moreLabel = stringResource(R.string.more)
695+ val loadingLabel = stringResource(R.string.loading)
696+ val shareLabel = stringResource(R.string.share_conversation)
697+ val copyAsMarkdownLabel = stringResource(R.string.copy_as_markdown)
698+ val shareAsJsonLabel = stringResource(R.string.share_as_json)
699+ val copyAsJsonLabel = stringResource(R.string.copy_as_json)
700+ val commandsLabel = stringResource(R.string.commands)
701+ val renameLabel = stringResource(R.string.rename_session_chat)
702+ val deleteLabel = stringResource(R.string.delete_session_chat)
703+ val createShareLabel = stringResource(R.string.create_share_link)
704+ val copyShareLabel = stringResource(R.string.copy_share_link)
705+ val stopShareLabel = stringResource(R.string.stop_sharing)
706+ val summarizeLabel = stringResource(R.string.summarize_conversation)
707+ val initLabel = stringResource(R.string.generate_agents_md)
708+ val shellLabel = stringResource(R.string.run_shell_command)
710+ IconButton(onClick = { showOverflowMenu = true }) {
711+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
714+ expanded = showOverflowMenu,
715+ onDismissRequest = { showOverflowMenu = false },
718+ text = { Text(shareLabel) },
719+ enabled = hasMessages,
721+ showOverflowMenu = false
723+ val md = withContext(Dispatchers.Default) {
724+ buildConversationMarkdown(vm.messages.value, sessionTitle)
726+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
727+ type = "text/markdown"
728+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
729+ putExtra(android.content.Intent.EXTRA_TEXT, md)
731+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
732+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
736+ // Copy the whole conversation as Markdown to the clipboard, so a
737+ // user can paste into another app without the share-sheet round-trip.
739+ text = { Text(copyAsMarkdownLabel) },
740+ enabled = hasMessages,
742+ showOverflowMenu = false
744+ val md = withContext(Dispatchers.Default) {
745+ buildConversationMarkdown(vm.messages.value, sessionTitle)
747+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
751+ // Lossless JSON share: the full List<MessageWithParts> serialized with
752+ // the shared OpencodeJson, so tool outputs, file sources, and reasoning
753+ // survive verbatim (the Markdown export truncates/summarizes them).
755+ text = { Text(shareAsJsonLabel) },
756+ enabled = hasMessages,
758+ showOverflowMenu = false
760+ val json = withContext(Dispatchers.Default) {
761+ buildConversationJson(vm.messages.value)
763+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
764+ type = "application/json"
765+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
766+ putExtra(android.content.Intent.EXTRA_TEXT, json)
768+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
769+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
774+ text = { Text(copyAsJsonLabel) },
775+ enabled = hasMessages,
777+ showOverflowMenu = false
779+ val json = withContext(Dispatchers.Default) {
780+ buildConversationJson(vm.messages.value)
782+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
787+ text = { Text(commandsLabel) },
788+ enabled = !commandsLoading || commands.isNotEmpty(),
789+ onClick = { showOverflowMenu = false; showCommandPicker = true },
792+ text = { Text(stringResource(R.string.keyboard_shortcuts)) },
793+ onClick = { showOverflowMenu = false; showShortcutsDialog = true },
796+ text = { Text(stringResource(R.string.find_in_conversation)) },
798+ showOverflowMenu = false
800+ // Focus is requested by the LaunchedEffect(searchActive)
801+ // below, which waits for the search field to be composed
802+ // before requesting focus (calling requestFocus here would
803+ // target a field that isn't in the composition yet).
806+ androidx.compose.material3.HorizontalDivider()
807+ // Session sharing: create a public link, copy an existing one, or revoke it.
808+ if (shareUrl == null) {
810+ text = { Text(createShareLabel) },
811+ enabled = hasMessages,
812+ onClick = { showOverflowMenu = false; vm.shareSession() },
816+ text = { Text(copyShareLabel) },
818+ showOverflowMenu = false
820+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
821+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
826+ text = { Text(stopShareLabel) },
827+ onClick = { showOverflowMenu = false; vm.unshareSession() },
831+ text = { Text(summarizeLabel) },
832+ enabled = hasMessages && !running,
833+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
836+ text = { Text(initLabel) },
838+ onClick = { showOverflowMenu = false; showInitConfirm = true },
841+ text = { Text(shellLabel) },
843+ onClick = { showOverflowMenu = false; showShellDialog = true },
845+ androidx.compose.material3.HorizontalDivider()
847+ text = { Text(renameLabel) },
848+ onClick = { showOverflowMenu = false; showRenameDialog = true },
851+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
852+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
855+ // While a catalog is initially loading (empty list + loading flag),
856+ // show a tiny inline spinner beside the overflow so the user can see
857+ // a load is in progress without opening the menu. Once loaded the
858+ // spinner disappears; the menu items are always enabled (tapping a
859+ // picker with no items shows the "no models/agents/commands" state).
860+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
861+ (agentsLoading && agents.isEmpty()) ||
862+ (modelsLoading && models.isEmpty())
863+ if (catalogLoading) {
864+ CircularProgressIndicator(
866+ .align(Alignment.TopEnd)
868+ .semantics { contentDescription = loadingLabel },
876+ snackbarHost = { SnackbarHost(snackbar) },
878+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
879+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
880+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
881+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
883+ // Pinned above the composer so the agent's plan and progress stay visible
884+ // while scrolled up mid-run; renders nothing when there's no plan.
885+ TodoPlanBar(todoPlan)
886+ val bannerMotion = rememberVisibilityTransitions()
889+ enter = bannerMotion.enter,
890+ exit = bannerMotion.exit,
894+ isEditing = editing,
895+ onUndo = { vm.unrevert() },
899+ visible = queuedOffline.isNotEmpty(),
900+ enter = bannerMotion.enter,
901+ exit = bannerMotion.exit,
904+ count = queuedOffline.size,
905+ sending = outboxSending,
906+ onFlush = { vm.flushQueued() },
907+ onDiscard = { vm.discardAllQueued() },
911+ visible = pendingQuote != null,
912+ enter = bannerMotion.enter,
913+ exit = bannerMotion.exit,
915+ pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
919+ onValueChange = vm::updateDraft,
921+ aborting = aborting,
922+ enabled = activeConnection != null,
923+ sendOnEnter = sendOnEnter,
925+ onAbort = { vm.abort() },
926+ queuedFollowUp = queuedFollowUp,
927+ onQueueFollowUp = vm::queueFollowUp,
928+ onCancelQueue = { vm.queueFollowUp("") },
929+ focusRequester = inputFocusRequester,
930+ attachments = attachments,
931+ staging = stagingCount > 0,
932+ stagingFileCount = stagingFileTotal,
933+ onRemoveAttachment = vm::removeAttachment,
936+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
939+ onPickFile = { filePicker.launch("*/*") },
940+ onCamera = { launchCamera() },
941+ onVoice = { launchVoice() },
942+ onPasteImage = { stageUris(it) },
943+ commands = commands,
944+ onRunCommand = { cmd ->
946+ // Clear the draft so the typed /prefix doesn't linger after the
947+ // command fires (the command picker confirmation, if any, is
948+ // handled inside runCommand).
955+ // Collect messages inside the content lambda so streaming token updates
956+ // recompose only this subtree, not the top bar / input bar / 20+ other
957+ // state reads in the ChatScreen body.
958+ val messages by vm.messages.collectAsStateWithLifecycle()
959+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
960+ val listState = rememberLazyListState()
961+ val contentScope = rememberCoroutineScope()
962+ val timeTick = rememberRelativeTimeTick()
963+ // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
964+ // chat affordance for reading while the IME is open. Watching isScrollInProgress via
965+ // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
966+ val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
967+ androidx.compose.runtime.LaunchedEffect(listState) {
968+ androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
969+ .distinctUntilChanged()
970+ .collect { scrolling -> if (scrolling) keyboardController?.hide() }
971+ } // Group messages by day and interleave date separators so a long conversation
972+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
973+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
974+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
975+ // the same list the LazyColumn renders (separators shift the indices vs. the
976+ // raw messages list, so scroll targets must be in listItems space).
977+ val todayLabel = stringResource(R.string.today)
978+ val yesterdayLabel = stringResource(R.string.yesterday)
979+ // In-conversation search: when active, narrow to messages whose text contains the query.
980+ // Computed on the filtered set so day separators still align with the visible messages.
981+ // Debounced + off-main-thread so a keystroke-by-keystroke filter walk over a long
982+ // conversation (with many tool parts whose state stringification is non-trivial)
983+ // doesn't jank the UI. produceState yields the empty list immediately and publishes
984+ // the filtered result once the debounce settles.
985+ val searchQuery = chatSearch.trim()
986+ // When no search is active, skip the produceState indirection entirely and use the
987+ // messages list directly. produceState keyed on (messages, searchQuery) re-launches
988+ // its coroutine on every messages emission (every streamed token) even when the
989+ // query is empty — the body just re-assigns `value = messages`, but the coroutine
990+ // churn (launch + cancel + state write) ~20x/sec is pure overhead. Using `messages`
991+ // directly when there's no search avoids that, and `buildMessageListItems` keys its
992+ // own remember on the resulting list identity either way.
993+ val searchMessages: List<MessageWithParts> = if (searchQuery.isEmpty()) {
996+ // Capture the messages list via rememberUpdatedState so the latest list is read
997+ // when the debounce completes, WITHOUT re-launching the produceState coroutine on
998+ // every messages emission. Keying produceState on `messages` restarts the debounce
999+ // delay from zero on every streamed token (~20×/sec); if tokens arrive faster than
1000+ // the debounce interval the filter never runs and search shows "no matches" for the
1001+ // entire run. Keying only on `searchQuery` lets the debounce settle once per query
1002+ // while still filtering against the most recent list.
1003+ val currentMessages by rememberUpdatedState(messages)
1004+ val filtered by produceState(
1005+ initialValue = emptyList(),
1008+ // Debounce: wait for the user to stop typing before running the filter,
1009+ // so each keystroke doesn't kick off a fresh scan.
1010+ kotlinx.coroutines.delay(NetworkConfig.chatSearchDebounceMs)
1011+ // Run the filter off the main thread — the walk stringifies tool state
1012+ // and scans every part of every message, which is non-trivial work for a
1013+ // long conversation.
1014+ value = withContext(Dispatchers.Default) {
1015+ currentMessages.filter { m ->
1018+ is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
1019+ is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
1021+ // Match the tool name plus its running/completed/error text and the
1022+ // stringified input, so searching for an error string or a file the
1023+ // tool touched actually finds the message it appeared in.
1024+ p.tool.contains(searchQuery, ignoreCase = true) ||
1025+ (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
1026+ (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
1027+ p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
1028+ (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
1029+ p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
1031+ is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
1032+ p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
1041+ // Keep the focused-match index in range as the query (and thus the match set) changes.
1042+ // A new query resets to the first match (keyed on searchQuery alone so any change —
1043+ // even one that still yields enough matches — jumps to index 0 rather than carrying
1044+ // the old index over to a semantically unrelated message). A shrunk set clamps to
1045+ // the last valid index (keyed on size so a content refresh that shrinks the matches
1046+ // without a query change doesn't leave searchPos out of range).
1047+ LaunchedEffect(searchQuery) {
1050+ LaunchedEffect(searchMessages.size) {
1051+ if (searchPos >= searchMessages.size) searchPos = 0
1053+ val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1054+ buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1056+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1057+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1058+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1059+ // would capture the first composition's list — which is empty, since `messages`
1060+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1061+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1062+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1063+ // whose value tracks the latest list.
1064+ val currentListItems by rememberUpdatedState(listItems)
1066+ // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1067+ // while the user was scrolled away from the bottom, cleared once they return. A count
1068+ // (vs. a bare dot) tells the user how much they missed at a glance.
1069+ // rememberSaveable (not plain remember) so the badge count survives rotation: plain
1070+ // remember resets to 0 on recreation, hiding the "new content" signal even though new
1071+ // messages are still arriving. Int is Bundle-savable.
1072+ var newContentCount by rememberSaveable { mutableIntStateOf(0) }
1074+ val isPinnedToBottom by remember {
1076+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1077+ // When a run is active, the LazyColumn has one trailing "__typing"
1078+ // item after the last list item. Account for it so "pinned to bottom"
1079+ // includes the working indicator — otherwise the pin check targets
1080+ // listItems.lastIndex, the typing row sits just below the viewport,
1081+ // and the user never sees the progress indicator even when pinned.
1082+ val items = currentListItems
1083+ val effectiveLast = if (running) items.size else items.lastIndex
1084+ lastVisible >= effectiveLast || items.isEmpty()
1088+ // Jump to the newest message once, when the conversation first loads. Guarded by a
1089+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1090+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1091+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1092+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1093+ LaunchedEffect(listItems.isNotEmpty()) {
1094+ if (listItems.isNotEmpty() && !didInitialScroll) {
1095+ // When a run is active the LazyColumn has a trailing "__typing" row at
1096+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1097+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
1098+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1099+ didInitialScroll = true
1103+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1104+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1105+ // isPinnedToBottom check flips to false the instant you send — freezing
1106+ // auto-scroll. If the user was pinned to the last item just before the run
1107+ // began, bring the typing row into view so the pin (and streaming follow) is
1108+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1109+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
1110+ LaunchedEffect(running) {
1111+ if (running && listItems.isNotEmpty()) {
1112+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1113+ if (lastVisible >= listItems.lastIndex) {
1114+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1119+ // Scroll the focused search match into view whenever the user steps through results with
1120+ // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1121+ // includes date separators) and animates there.
1123+ // Keyed ONLY on searchPos and searchQuery (not listItems): a bare listItems key re-keys
1124+ // on every streamed token (the list is rebuilt per snapshot), which re-fires this effect
1125+ // ~20×/sec during an active stream — re-scrolling to the focused match on every token
1126+ // and making it impossible to browse other matches with the up/down arrows while content
1127+ // is streaming. snapshotFlow (reading currentListItems, a rememberUpdatedState) waits for
1128+ // the target to appear without re-keying the effect on every list change, mirroring the
1129+ // focusedMessageId pattern below.
1130+ LaunchedEffect(searchPos, searchQuery) {
1131+ if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1132+ val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1133+ val targetId = target.info.id
1134+ val index = snapshotFlow {
1135+ currentListItems.indexOfFirst {
1136+ it is MessageListItem.Message && it.message.info.id == targetId
1138+ }.first { it >= 0 }
1139+ runCatchingCancellable { listState.animateScrollToItem(index) }
1142+ // Global-search deep link: scroll to and briefly highlight the matched message. The
1143+ // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1144+ // clears itself after a short delay so the user can re-read the surrounding context
1145+ // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1147+ // Keyed ONLY on focusedMessageId (not listItems): a bare listItems key re-keys on every
1148+ // streamed token (the list is rebuilt per snapshot), which cancels the 2.5s delay before
1149+ // it can clear the highlight — re-scrolling to the focus on every token and making an
1150+ // actively-streaming chat unreadable. snapshotFlow waits for the message to appear in the
1151+ // list (it may not be present on the first composition while messages load) without
1152+ // re-keying the effect on every list change.
1153+ // rememberSaveable (not plain remember) so the cleared null survives rotation:
1154+ // plain remember keyed on focusMessageId re-seeds the non-null nav arg on every
1155+ // recreation, re-firing this effect and yanking scroll back to the focus after the
1156+ // user already dismissed the highlight. String? is Bundle-savable.
1157+ var focusedMessageId by rememberSaveable(focusMessageId) { mutableStateOf(focusMessageId) }
1158+ val currentListItemsForFocus by rememberUpdatedState(listItems)
1159+ LaunchedEffect(focusedMessageId) {
1160+ val focus = focusedMessageId ?: return@LaunchedEffect
1161+ // Wait for the focused message to appear in the list, then resolve its index. A
1162+ // first-composition empty list (messages still loading) will populate as the seed
1163+ // arrives; snapshotFlow re-evaluates on each list change until the match is found.
1164+ val index = snapshotFlow {
1165+ currentListItemsForFocus.indexOfFirst {
1166+ it is MessageListItem.Message && it.message.info.id == focus
1168+ }.first { it >= 0 }
1169+ runCatchingCancellable { listState.animateScrollToItem(index) }
1170+ kotlinx.coroutines.delay(2500)
1171+ focusedMessageId = null
1174+ // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1175+ // latest reply stays visible as the composer rises. Without this the IME can obscure the
1176+ // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1177+ // @Composable property, so we read it inside a snapshotFlow registered in the composable
1178+ // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1179+ val density = androidx.compose.ui.platform.LocalDensity.current
1180+ var wasImeOpen by remember { mutableStateOf(false) }
1181+ val imeBottomPx = WindowInsets.ime.getBottom(density)
1182+ androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1183+ if (listItems.isEmpty()) return@LaunchedEffect
1184+ val imeOpen = imeBottomPx > 0
1185+ // Scroll to bottom only on the open transition (not close) and only when the user
1186+ // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1187+ val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1188+ if (shouldScroll) {
1189+ runCatchingCancellable {
1190+ listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1193+ wasImeOpen = imeOpen
1196+ LaunchedEffect(Unit) {
1200+ // Track list size + the streaming length of the last part so we auto-scroll
1201+ // as content arrives, plus the pinned flag. A small data class with primitive
1202+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1203+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1204+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1205+ // and tool output — not just TextPart — keeps a pinned view following a long
1206+ // reasoning/tool block while it streams (previously it stalled at 0).
1207+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1208+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1209+ }.collect { signal ->
1210+ if (signal.pinned) {
1211+ // Back at the bottom: clear the new-content badge.
1212+ newContentCount = 0
1213+ if (signal.size > 0) {
1214+ // Scroll to the effective last index, including the trailing
1215+ // "__typing" row when a run is active so the working indicator
1216+ // is brought into view (not just the last message).
1217+ val items = currentListItems
1218+ val target = if (running) items.size else items.lastIndex
1219+ listState.scrollToItem(target)
1221+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1222+ // Content arrived while scrolled up — increment the jump-to-latest badge.
1223+ // Only count whole new items (not per-token growth) so the number reflects
1224+ // new messages, not a token count.
1225+ if (signal.size > prevSize) newContentCount += signal.size - prevSize
1226+ else if (newContentCount == 0) newContentCount = 1
1228+ prevSize = signal.size
1229+ prevLen = signal.lastTextLength
1233+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1234+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1235+ // content padding accounts for the bottomBar's raised height, so the message
1236+ // list is already above the keyboard. Adding imePadding here would double-apply
1237+ // the IME inset and push messages too far up.
1239+ // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1240+ // message list on wide screens instead of floating at the screen edges — on a
1241+ // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1242+ // The horizontal margin below is applied to the FAB/search containers so they
1243+ // track the list's left/right edges.
1244+ androidx.compose.foundation.layout.BoxWithConstraints(
1245+ modifier = Modifier.fillMaxSize().padding(padding),
1247+ val screenMaxWidth = maxWidth
1248+ val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1249+ // Horizontal margin between the capped list's edge and the screen edge (0 on
1250+ // screens narrower than the cap). Applied as start/end padding so the FABs and
1251+ // search bar sit at the list's edges, not the screen's.
1252+ val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1253+ if (activeConnection == null) {
1255+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
1256+ horizontalAlignment = Alignment.CenterHorizontally,
1259+ stringResource(R.string.not_connected),
1260+ color = MaterialTheme.colorScheme.error,
1262+ Spacer(Modifier.size(12.dp))
1263+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1264+ if (reconnecting) {
1265+ CircularProgressIndicator(
1266+ Modifier.size(20.dp),
1267+ color = MaterialTheme.colorScheme.onPrimary,
1268+ strokeWidth = 2.dp,
1271+ Text(stringResource(R.string.reconnect))
1276+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1277+ // Measure the banner's actual height instead of hardcoding 44dp. At large
1278+ // accessibility font scales the banner's labelMedium text + spinner + Retry
1279+ // button exceed 44dp, so a fixed inset lets the first message hide behind it
1280+ // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1281+ // fires while the banner is composed (visible), so gate the inset on
1282+ // bannerVisible and fall back to 44dp until the first measurement arrives.
1283+ var bannerHeightPx by remember { mutableIntStateOf(0) }
1284+ // Track the search bar height so the list's top padding can grow when search
1285+ // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1286+ // the floating search bar (the "scroll-under-the-search-bar" bug).
1287+ var searchbarHeightPx by remember { mutableIntStateOf(0) }
1288+ val density = LocalDensity.current
1289+ val topPad = if (bannerVisible) {
1290+ if (bannerHeightPx > 0) {
1291+ with(density) { bannerHeightPx.toDp() } + 4.dp
1297+ } + if (searchActive && searchbarHeightPx > 0) {
1298+ with(density) { searchbarHeightPx.toDp() } + 4.dp
1303+ state = connectionState,
1304+ modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1305+ isOnline = isOnline,
1306+ // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1307+ // re-seeds from REST). refreshMessages is the right recovery path
1308+ // when the connection is present but the stream died; reconnect()
1309+ // is the path when the whole connection is gone (handled by the
1310+ // separate "Not connected" state below).
1311+ onRetry = { vm.refreshMessages() },
1312+ // On an auth failure (401/403), retrying with the same bad credentials
1313+ // is futile — offer a one-tap path to edit the active profile's
1314+ // credentials instead of making the user hunt for the server list.
1315+ onEditCredentials = {
1316+ val profileId = activeConnection?.profile?.id
1317+ if (profileId != null) onEditProfile?.invoke(profileId)
1319+ reconnectAttempts = reconnectAttempts,
1321+ // Persistent inline error banner for a mid-conversation load failure.
1322+ // Unlike the one-shot snackbar (which fires once per streak then goes
1323+ // silent), this stays visible until the stream recovers, so a persistent
1324+ // outage doesn't read as "everything is fine" after the snackbar dismisses.
1325+ // Anchored at the top, below the connection banner, so it doesn't overlap
1326+ // the message list.
1327+ if (loadErrorInline && hasMessages) {
1329+ color = MaterialTheme.colorScheme.errorContainer,
1330+ shape = MaterialTheme.shapes.small,
1331+ modifier = Modifier
1332+ .align(Alignment.TopCenter)
1333+ .padding(top = if (bannerVisible) topPad else 8.dp)
1334+ .padding(horizontal = 16.dp)
1335+ .semantics { liveRegion = LiveRegionMode.Polite },
1338+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1339+ verticalAlignment = Alignment.CenterVertically,
1340+ horizontalArrangement = Arrangement.spacedBy(8.dp),
1343+ Icons.Filled.ErrorOutline,
1344+ contentDescription = null,
1345+ modifier = Modifier.size(16.dp),
1346+ tint = MaterialTheme.colorScheme.onErrorContainer,
1349+ stringResource(R.string.load_error_persistent),
1350+ style = MaterialTheme.typography.labelMedium,
1351+ color = MaterialTheme.colorScheme.onErrorContainer,
1352+ modifier = Modifier.weight(1f),
1355+ onClick = { vm.refreshMessages() },
1356+ contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1358+ Text(stringResource(R.string.retry))
1363+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1364+ // recovery is a swipe away everywhere — not just when the message list is
1365+ // populated. Previously PTR was only around the populated list, leaving the
1366+ // error/loading states reachable only via a button tap.
1368+ isRefreshing = refreshing,
1369+ // Suppress the refresh action while a run is active: a mid-stream
1370+ // refresh forces an SSE reconnect that can interrupt the actively
1371+ // streaming reply (matching the top-bar refresh button, which is
1372+ // also disabled while running). The pull gesture still responds, but
1373+ // the release no-ops instead of triggering a disruptive re-seed.
1374+ onRefresh = { if (!running) vm.refreshMessages() },
1375+ // Cap width and center on large screens for readability — full-width
1376+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1377+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1378+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1380+ // Reserve top space when the banner is visible so it doesn't overlap the
1381+ // first message / state content. (topPad computed above.)
1382+ if (loading && messages.isEmpty()) {
1383+ // Skeleton bubbles pre-structure the layout so the perceived load is faster
1384+ // than a bare centered spinner and the first real messages pop into an
1385+ // already-shaped list instead of a blank-then-pop.
1386+ ChatSkeleton(topPad = topPad)
1387+ } else if (loadError && messages.isEmpty()) {
1388+ // A failed load with nothing to show. Distinct from the empty
1389+ // conversation state below — the conversation isn't empty, it
1390+ // failed to load, and offering "Start a conversation" here is
1391+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
1393+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1394+ horizontalAlignment = Alignment.CenterHorizontally,
1397+ stringResource(R.string.load_messages_failed),
1398+ color = MaterialTheme.colorScheme.error,
1400+ Spacer(Modifier.size(12.dp))
1401+ Button(onClick = { vm.refreshMessages() }) {
1402+ Text(stringResource(R.string.retry))
1404+ // When the VM's retryWhen loop is actively retrying (loading is true
1405+ // on top of the error state), surface a small "retrying…" indicator so
1406+ // the user knows the system is working — without it, the static error
1407+ // + Retry button reads as "broken, tap to fix", and the user may not
1408+ // realize an automatic retry is already in progress.
1410+ Spacer(Modifier.size(12.dp))
1411+ val retryingLabel = stringResource(R.string.retrying_ellipsis)
1412+ Row(verticalAlignment = Alignment.CenterVertically) {
1413+ CircularProgressIndicator(
1414+ Modifier.size(14.dp),
1415+ strokeWidth = 2.dp,
1419+ style = MaterialTheme.typography.labelSmall,
1420+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1421+ modifier = Modifier.padding(start = 6.dp),
1426+ } else if (messages.isEmpty() && running) {
1427+ // A run just started but no parts have arrived yet — the empty list with
1428+ // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1429+ // from the initial-load branch so the perceived start latency is lower and
1430+ // the first real assistant part pops into an already-shaped list.
1431+ ChatSkeleton(topPad = topPad)
1432+ } else if (messages.isEmpty()) {
1436+ // Focus the input so the user can edit the suggestion before
1437+ // sending, instead of having to manually tap the field.
1438+ runCatching { inputFocusRequester.requestFocus() }
1440+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1443+ val lastMessageId = messages.lastOrNull()?.info?.id
1444+ // Text-to-speech for reading assistant replies aloud; shuts down when the
1445+ // message list leaves composition.
1446+ val tts = rememberTtsController()
1447+ val speakingMessageId by tts.speakingId
1448+ val ttsState by tts.state
1449+ // Provide the in-conversation search query to the markdown renderer so matching
1450+ // text spans are highlighted in-place (in addition to the focused-row highlight
1451+ // above). Scoped to the list so cleared search stops highlighting immediately.
1452+ val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1453+ CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1456+ modifier = Modifier.fillMaxSize(),
1457+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
1458+ // never floats over the last message. Top padding grows when the
1459+ // connection banner is visible so it doesn't overlap the first message.
1460+ contentPadding = PaddingValues(
1464+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1466+ // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1467+ // more conversation on screen without scrolling as much.
1468+ verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1473+ contentType = { it.contentType },
1475+ // When in-conversation search is stepping through matches, highlight the
1476+ // focused one's row so the user can spot it at a glance among the filtered
1477+ // results (full in-text term highlighting would require threading the query
1478+ // through the markdown renderer; the row highlight + scroll-to-match covers
1479+ // the navigation use case desktop chat apps solve with next/prev).
1480+ val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1481+ searchMessages.getOrNull(searchPos)?.info?.id
1483+ val isFocusedMatch = focusedMatchId != null &&
1484+ item is MessageListItem.Message &&
1485+ item.message.info.id == focusedMatchId
1486+ // No animateItem() here. It is backed by SizeAnimationModifierNode, which
1487+ // forces a draw-phase remeasure (the display-list rebuild triggered by
1488+ // AndroidComposeView.dispatchDraw) when its target's size changes. That
1489+ // remeasure runs inside the draw pass and reads Placeable.getWidth()/
1490+ // getHeight() of a child whose measured size hasn't been committed yet —
1491+ // an NPE in PaddingValuesModifier.measure / FillNode.measure (the R8 map
1492+ // marks both sites with a throws(NullPointerException) rewriteFrame).
1494+ // This is the same crash class previously fixed for the markdown library's
1495+ // animateContentSize and MessageBubble's send-status AnimatedContent. An
1496+ // earlier fix kept animateItem() but skipped it for the actively-streaming
1497+ // row; that was insufficient because the crash also fires when OPENING a
1498+ // chat (running = false, so every row kept animateItem()): historical rows
1499+ // with async-loading content (DiffView's produceState starts empty and
1500+ // fills a frame later; RemoteImage loading; large markdown) change size
1501+ // after mount and trigger the same draw-phase remeasure. animateItem() is
1502+ // fundamentally unsafe on any chat row whose size can change post-mount,
1503+ // so it is removed entirely. The glide-in animation it provided is
1504+ // decorative (the list already auto-scrolls to new messages) and is not
1505+ // worth a 4th round of this crash.
1509+ if (isFocusedMatch) {
1510+ Modifier.background(
1511+ MaterialTheme.colorScheme.secondaryContainer,
1512+ MaterialTheme.shapes.medium,
1520+ is MessageListItem.Separator -> DateSeparator(item.label)
1521+ is MessageListItem.Message -> {
1522+ val message = item.message
1523+ val messageId = message.info.id
1524+ // Only the last (streaming) message needs isRunning — it drives the
1525+ // reasoning-block spinner. Passing the live flag to every bubble
1526+ // makes all visible messages recompose whenever a run starts or stops.
1527+ val modelLabel = remember(message.info, models) {
1528+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1529+ ?.let { resolveModelLabel(it, models) }
1531+ // Key agentLabel/quoteText on the message id (not message.parts) so
1532+ // the streaming message — whose `parts` list is replaced on every
1533+ // token — doesn't re-run filterIsInstance per token for these two
1534+ // derived labels. For a non-streaming message, `message.parts` is
1535+ // reference-stable anyway, so this is equivalent. For the streaming
1536+ // message the label updates as parts change via the message.info/
1537+ // parts reference change below — keyed on messageId + a parts-hash
1538+ // is overkill; agentLabel/quoteText only need to reflect the latest
1539+ // parts, and `remember(messageId, message.parts)` would re-key per
1540+ // token. Instead key on `messageId` alone and accept that the label
1541+ // lags by one recomposition for the streaming bubble (it stabilizes
1542+ // once the stream finishes). This is invisible in practice: agent
1543+ // label is set on the first part, quote text grows with text parts
1544+ // but is only consumed on a swipe (user-initiated, post-stream).
1545+ val agentLabel = remember(messageId) {
1547+ .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1548+ .firstOrNull { it.name.isNotBlank() }?.name
1550+ // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1551+ // image/code-only messages, which then opt out of the swipe gesture.
1552+ val quoteText = remember(messageId) {
1554+ .filterIsInstance<TextPart>()
1555+ .joinToString("\n\n") { it.text }
1557+ .takeIf { it.isNotEmpty() }
1559+ // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1560+ // snapping back (the message isn't dismissed — the quote fills the composer).
1561+ // Enabled for non-text messages too (image/tool-only), but the confirm
1562+ // callback gives a haptic without triggering reply — so the user gets a
1563+ // perceptible "can't quote this" signal instead of a silently dead gesture.
1564+ val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1565+ val undoLabel = stringResource(R.string.undo)
1566+ val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1567+ // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1568+ // so it's stable across recompositions (a fresh lambda would force the
1569+ // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1570+ // derived value that's stable for non-streaming messages.
1571+ val swipeState = rememberSwipeToDismissBoxState(
1572+ confirmValueChange = remember(messageId, quoteText) {
1574+ val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1575+ SwipeToDismissBoxValue.EndToStart
1577+ SwipeToDismissBoxValue.StartToEnd
1579+ if (value == replyValue) {
1580+ if (quoteText != null) {
1581+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1582+ vm.quoteReply(quoteText)
1583+ runCatching { inputFocusRequester.requestFocus() }
1585+ val res = snackbar.showSnackbar(
1586+ message = quoteReplyLabel,
1587+ actionLabel = undoLabel,
1589+ if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1590+ vm.cancelQuoteReply()
1594+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1595+ scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1602+ // In RTL locales, mirror the swipe direction so the reply
1603+ // gesture reads naturally (swipe from the trailing edge
1604+ // toward the leading edge), matching how LTR users swipe
1605+ // left-to-right. Without this, RTL users had no reply swipe.
1606+ val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1607+ // Memoize every MessageBubble lambda on the message id so a recomposition
1608+ // triggered by a sibling (e.g. the streaming message's parts changing,
1609+ // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1610+ // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1611+ // many `(() -> Unit)?` params, which Compose treats as unstable), so
1612+ // without memoization every visible bubble recomposes on every token,
1613+ // defeating the @Immutable MessageWithParts reference-stability the
1614+ // reducer's Holder cache provides. This mirrors the SessionListScreen
1615+ // per-card lambda memoization pattern.
1616+ val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1617+ val onEdit = remember(messageId) {
1619+ // editMessage reverts to before this message (hiding it and
1620+ // everything after); the revert banner surfaces the rewind
1621+ // with an Undo. Focus + scroll the composer into view like the
1622+ // Quote action so the prefilled draft isn't off-screen.
1623+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1624+ vm.editMessage(messageId, text)
1625+ runCatching { inputFocusRequester.requestFocus() }
1626+ contentScope.launch {
1627+ runCatchingCancellable {
1628+ listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1634+ val onSpeak = remember(messageId) {
1636+ if (!tts.toggle(messageId, text)) {
1637+ scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1642+ val onPause = remember { { tts.pause() } }
1643+ val onResume = remember { { tts.resume() } }
1644+ val onStop = remember { { tts.stop() } }
1645+ val onQuote = remember(messageId) {
1647+ vm.quoteReply(text)
1648+ runCatching { inputFocusRequester.requestFocus() }
1652+ val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1653+ // Regenerate is only meaningful for a finished assistant reply
1654+ // (not the actively-streaming one), so gate it on !running.
1655+ val onRegenerate = if (!running) {
1656+ remember(messageId) { { vm.regenerate(messageId) } }
1660+ // Continue: resume a partial reply. Shown only for
1661+ // incomplete assistant messages (a partial reply that
1662+ // was aborted) and not while a run is active.
1663+ val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1664+ val onContinue = if (canContinue) {
1665+ remember(messageId) { { vm.continueRun(messageId) } }
1669+ val messageFailed = optimisticStatuses[messageId] == true
1670+ val onRetry = if (messageFailed) {
1671+ remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1675+ val onDismiss = if (messageFailed) {
1676+ remember(messageId) { { vm.dismissOptimistic(messageId) } }
1680+ val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1682+ // Per-message share: build a single-message Markdown
1683+ // transcript off-thread and fire ACTION_SEND, mirroring the
1684+ // whole-conversation share but scoped to just this message.
1686+ val md = withContext(Dispatchers.Default) {
1687+ buildMessageMarkdown(message)
1689+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1690+ type = "text/markdown"
1691+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1692+ putExtra(android.content.Intent.EXTRA_TEXT, md)
1694+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1695+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1701+ state = swipeState,
1702+ enableDismissFromEndToStart = !replyFromStartToEnd,
1703+ enableDismissFromStartToEnd = replyFromStartToEnd,
1704+ backgroundContent = {
1706+ Modifier.fillMaxSize().padding(horizontal = 16.dp),
1707+ contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1710+ Icons.AutoMirrored.Filled.Reply,
1711+ contentDescription = null,
1712+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1719+ isRunning = running && messageId == lastMessageId,
1720+ imageContext = imageContext,
1721+ modelLabel = modelLabel,
1722+ agentLabel = agentLabel,
1723+ onOpenFile = onOpenFile,
1724+ onRevert = onRevert,
1727+ isSpeaking = messageId == speakingMessageId,
1728+ ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1730+ onResume = onResume,
1733+ onBranch = onBranch,
1734+ onRegenerate = onRegenerate,
1735+ onContinue = onContinue,
1736+ sendStatus = optimisticStatuses[messageId]?.let { failed ->
1737+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1738+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1740+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1742+ onDismiss = onDismiss,
1744+ isFirstOfSpeaker = item.isFirstOfSpeaker,
1745+ highlighted = focusedMessageId != null && messageId == focusedMessageId,
1753+ item(key = "__typing") {
1754+ val workingText = stringResource(R.string.working)
1755+ // When the SSE stream dropped mid-run, show a "reconnecting" label
1756+ // instead of the plain "working" text so the user understands the
1757+ // run is still active but the stream is reconnecting (not finished).
1758+ val reconnectingText = stringResource(R.string.reconnecting)
1759+ val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1760+ // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1761+ // survives LazyColumn recycling — a local remember reset to 0:00 when
1762+ // the row was disposed and scrolled back into view. The VM stamps the
1763+ // start on the real false→true transition (send/run/init), not on
1764+ // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1765+ // once per second; the value is decorative (the a11y label is the row's).
1766+ // The clock freezes when an abort is confirmed (aborting = true) so the
1767+ // user can see how long the run lasted before they stopped it, rather
1768+ // than the clock continuing to tick until SessionIdle clears _running.
1769+ val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1770+ // Seed the initial value synchronously from startMs so the timer
1771+ // doesn't flash 0:00 when the __typing row is recycled by LazyColumn
1772+ // (scrolled out then back in): produceState's coroutine is cancelled on
1773+ // disposal and re-launched on re-entry, and a 0L initialValue would
1774+ // briefly show "0:00" before the producer's first iteration runs.
1775+ val elapsedMs by produceState(
1776+ initialValue = if (startMs > 0L) (System.currentTimeMillis() - startMs).coerceAtLeast(0L) else 0L,
1779+ if (startMs == 0L) return@produceState
1781+ // Freeze at the last-computed value: one final snapshot then stop.
1782+ value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1783+ return@produceState
1786+ value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1790+ val elapsedText = remember(elapsedMs) {
1791+ val total = elapsedMs / 1000
1792+ // Locale.US for stable digit formatting: on locales with
1793+ // non-ASCII digits (ar-/fa-) the default locale would render
1794+ // localized digits inside the Monospace block, breaking the
1795+ // fixed-width alignment the monospace family was chosen for.
1796+ String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1799+ verticalAlignment = Alignment.CenterVertically,
1800+ // No animateItem() here for the same reason as the message rows
1801+ // above: the __typing row's size changes (the elapsed-time Text
1802+ // grows from "0:00" to "M:SS" and the spinner mounts on first
1803+ // frame), and animateItem()'s SizeAnimationModifierNode forces a
1804+ // draw-phase remeasure that NPEs on Placeable.getWidth(). The
1805+ // working row is mounted/unmounted as a whole item (key="__typing")
1806+ // by LazyColumn, which already crossfades the appearance; the
1807+ // placement animation is not needed.
1808+ modifier = Modifier
1809+ .padding(vertical = 4.dp),
1811+ // Merge the indicator + label + clock into one TalkBack node so
1812+ // it's announced once (the working label, then the elapsed time)
1813+ // instead of "working… / working… / 0:14" with the label read
1814+ // twice. The Stop IconButton below stays separately focusable.
1816+ verticalAlignment = Alignment.CenterVertically,
1817+ modifier = Modifier.semantics(mergeDescendants = true) {
1818+ contentDescription = "$interruptedLabel $elapsedText"
1821+ // Dim the spinner when interrupted so the row reads as
1822+ // "paused/reconnecting" rather than actively progressing.
1823+ CircularProgressIndicator(
1824+ Modifier.size(16.dp),
1825+ strokeWidth = 2.dp,
1826+ color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1827+ else MaterialTheme.colorScheme.primary,
1829+ Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1830+ Spacer(Modifier.size(8.dp))
1832+ Icons.Filled.Schedule,
1833+ contentDescription = null,
1834+ modifier = Modifier.size(14.dp),
1835+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1839+ style = MaterialTheme.typography.labelMedium,
1840+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1841+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1842+ modifier = Modifier.padding(start = 4.dp),
1845+ // A trailing Stop on the working row so the run can be aborted
1846+ // without scrolling back to the composer (which may be off-screen
1847+ // while the user reads the streaming output up-thread).
1848+ Spacer(Modifier.weight(1f))
1849+ val stopLabel = stringResource(R.string.stop)
1851+ onClick = { vm.abort() },
1852+ modifier = Modifier.semantics { contentDescription = stopLabel },
1854+ Icon(Icons.Filled.Stop, contentDescription = null)
1863+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1864+ val fabMotion = rememberVisibilityTransitions()
1865+ AnimatedVisibility(
1866+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1867+ enter = fabMotion.enter,
1868+ exit = fabMotion.exit,
1869+ // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1870+ // edge instead of floating at the screen edge (visually detached on tablets).
1871+ modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1873+ // Badge the FAB when new content arrived while the user was scrolled up, so
1874+ // they know there's something new to jump to (cleared once back at bottom).
1877+ if (newContentCount > 0) {
1878+ // Merge the count into the badge announcement so TalkBack reads
1879+ // "5 new messages" instead of the bare label and a separate number.
1880+ val newContentLabel = pluralStringResource(
1881+ R.plurals.plurals_new_messages,
1886+ modifier = Modifier.semantics {
1887+ contentDescription = newContentLabel
1888+ // Announce new-content counts as they change so a
1889+ // TalkBack user hears "5 new messages" without having
1890+ // to focus the FAB. Polite so it doesn't interrupt an
1891+ // in-progress utterance (e.g. streaming token reads).
1892+ liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1896+ if (newContentCount > 99) "99+" else newContentCount.toString(),
1897+ modifier = Modifier.semantics { invisibleToUser() },
1902+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1904+ ExtendedFloatingActionButton(
1906+ newContentCount = 0
1907+ if (listItems.isNotEmpty()) {
1908+ // Scroll to the effective last index, including the
1909+ // trailing "__typing" row when a run is active.
1910+ val target = if (running) listItems.size else listItems.lastIndex
1911+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1914+ // contentDescription null: the visible "Latest" text already labels
1915+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1916+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1917+ text = { Text(stringResource(R.string.latest)) },
1921+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1922+ // user has scrolled down past the first few messages. Symmetric to the
1923+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1924+ val scrolledDown by remember {
1925+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1927+ AnimatedVisibility(
1928+ visible = scrolledDown && listItems.size > 4,
1929+ enter = fabMotion.enter,
1930+ exit = fabMotion.exit,
1931+ modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1933+ SmallFloatingActionButton(
1935+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1937+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1940+ Icons.Filled.KeyboardArrowUp,
1941+ contentDescription = stringResource(R.string.scroll_to_top),
1945+ // In-conversation search bar. Overlays the list so typing filters messages in
1946+ // place; the match count + a no-matches note give immediate feedback.
1947+ val searchMotion = rememberVisibilityTransitions()
1948+ AnimatedVisibility(
1949+ visible = searchActive,
1950+ enter = searchMotion.enter,
1951+ exit = searchMotion.exit,
1952+ // Inset by sideMargin on wide screens so the search bar spans the capped
1953+ // list's width, not the full screen width.
1954+ modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1957+ tonalElevation = 3.dp,
1958+ modifier = Modifier
1959+ .padding(horizontal = 12.dp, vertical = 4.dp)
1961+ .onSizeChanged { searchbarHeightPx = it.height },
1963+ // Focus the search field when the bar appears (from the overflow menu's
1964+ // "Find in conversation" or Ctrl+F), so the user can start typing
1965+ // immediately. Runs after the search field enters the composition.
1966+ LaunchedEffect(searchActive) {
1967+ if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1970+ modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1971+ verticalAlignment = Alignment.CenterVertically,
1974+ value = chatSearch,
1975+ onValueChange = { chatSearch = it },
1976+ modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1977+ placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1979+ leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1980+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1982+ // Match counter: "N of M" where N is the focused match (1-based) and
1983+ // M is the total matching messages. Only shown when there's a query.
1984+ val matchCount = searchMessages.size
1986+ if (searchQuery.isNotEmpty() && matchCount > 0) {
1987+ stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1988+ } else if (searchQuery.isNotEmpty()) {
1989+ stringResource(R.string.search_no_matches)
1991+ style = MaterialTheme.typography.labelSmall,
1992+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1993+ modifier = Modifier
1994+ .padding(horizontal = 4.dp)
1995+ // Live region so a TalkBack user hears "3 of 12" / "No
1996+ // matches" announce as they step through results, not just
1997+ // the sighted user seeing the counter update.
1998+ .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
2000+ // Step through matches (Previous / Next), disabled when there are
2001+ // fewer than two to navigate. Wrap around at the ends so repeated
2002+ // taps cycle through every hit.
2003+ val prevLabel = stringResource(R.string.find_previous)
2004+ val nextLabel = stringResource(R.string.find_next)
2007+ if (matchCount > 0) {
2008+ searchPos = (searchPos - 1 + matchCount) % matchCount
2011+ enabled = matchCount > 1,
2013+ Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
2017+ if (matchCount > 0) {
2018+ searchPos = (searchPos + 1) % matchCount
2021+ enabled = matchCount > 1,
2023+ Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
2025+ IconButton(onClick = {
2026+ searchActive = false
2029+ Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
2034+ // When a search yields no matches (but the conversation isn't empty), say so
2035+ // instead of showing a blank list.
2036+ if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
2038+ stringResource(R.string.search_no_matches),
2039+ style = MaterialTheme.typography.bodyMedium,
2040+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2041+ modifier = Modifier.align(Alignment.Center),
2049+ if (showExitConfirm) {
2051+ onDismissRequest = { showExitConfirm = false },
2052+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
2053+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
2055+ TextButton(onClick = {
2056+ showExitConfirm = false
2057+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2060+ }) { Text(stringResource(R.string.stop_and_exit)) }
2063+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
2068+ if (showSummarizeConfirm) {
2070+ onDismissRequest = { showSummarizeConfirm = false },
2071+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
2072+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
2074+ TextButton(onClick = {
2075+ showSummarizeConfirm = false
2077+ }) { Text(stringResource(R.string.action_continue)) }
2080+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
2085+ if (showInitConfirm) {
2087+ onDismissRequest = { showInitConfirm = false },
2088+ title = { Text(stringResource(R.string.init_confirm_title)) },
2089+ text = { Text(stringResource(R.string.init_confirm_text)) },
2091+ TextButton(onClick = {
2092+ showInitConfirm = false
2094+ }) { Text(stringResource(R.string.action_continue)) }
2097+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2102+ if (showRenameDialog) {
2103+ RenameSessionChatDialog(
2104+ initialTitle = sessionTitle ?: "",
2105+ onDismiss = { showRenameDialog = false },
2106+ onConfirm = { newName ->
2107+ showRenameDialog = false
2108+ vm.renameSession(newName)
2113+ if (showDeleteDialog) {
2115+ onDismissRequest = { showDeleteDialog = false },
2116+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
2117+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2119+ TextButton(onClick = {
2120+ showDeleteDialog = false
2121+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2123+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2126+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2131+ if (showShellDialog) {
2132+ ShellCommandDialog(
2133+ onDismiss = { showShellDialog = false },
2135+ showShellDialog = false
2141+ if (showModelPicker) {
2142+ // Resolve persisted recent composite keys to the live ModelOption entries they refer
2143+ // to, dropping any whose model is no longer offered by the server. Ordered by
2144+ // recency (head of the store first).
2145+ val recentOptions = remember(models, recentModelEntries) {
2146+ val byKey = models.associateBy { it.providerID to it.modelID }
2147+ recentModelEntries.mapNotNull { entry ->
2148+ container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2151+ // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2152+ // below isn't @Composable, so stringResource can't be called inside it.
2153+ val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2154+ val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2157+ selected = selectedModel,
2158+ loading = modelsLoading,
2159+ error = modelsError,
2162+ container.recentModelsStore.add(it.providerID, it.modelID)
2164+ onRetry = { vm.reloadModels() },
2165+ onDismiss = { showModelPicker = false },
2166+ preferredModelId = preferredModelId,
2167+ onSetPreferredModel = { id ->
2169+ runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2170+ // Confirm the change with a snackbar so the user sees it took effect —
2171+ // the toggle's label flip can be missed, especially when clearing.
2172+ val msg = if (id.isEmpty()) {
2173+ defaultModelClearedMsg
2175+ val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2176+ defaultModelSetFmt.format(label)
2178+ snackbar.showSnackbar(msg)
2181+ recent = recentOptions,
2185+ if (showAgentPicker) {
2188+ selected = selectedAgent,
2189+ loading = agentsLoading,
2190+ error = agentsError,
2191+ onSelect = { vm.selectAgent(it?.name) },
2192+ onRetry = { vm.reloadAgents() },
2193+ onDismiss = { showAgentPicker = false },
2197+ if (showCommandPicker) {
2198+ CommandPickerSheet(
2199+ commands = commands,
2200+ loading = commandsLoading,
2201+ error = commandsError,
2202+ onSelect = { vm.runCommand(it) },
2203+ onRetry = { vm.reloadCommands() },
2204+ onDismiss = { showCommandPicker = false },
2208+ pendingPermission?.let { permission ->
2210+ permission = permission,
2211+ position = permissionProgress.position,
2212+ total = permissionProgress.total,
2213+ onRespond = { response -> vm.respondPermission(permission, response) },
2214+ // On auto-reject timeout, post a notification so a returning user finds a
2215+ // persistent record of why the run stopped (the dialog itself is gone).
2216+ // Gated by the user's notification setting (notifPermission).
2218+ val conn = activeConnection
2219+ val ctx = appContext
2220+ val title = sessionTitle ?: sessionId
2221+ if (notifPermission) {
2222+ soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2223+ ctx, sessionId, title, conn?.profile?.id,
2231+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2234+ if (showShortcutsDialog) {
2235+ // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2236+ // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2237+ // depends on the "Send on Enter" setting, noted inline.
2239+ onDismissRequest = { showShortcutsDialog = false },
2240+ title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2242+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2243+ ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2244+ ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2245+ ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2246+ ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2247+ ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2251+ TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2258+private fun ShortcutRow(keys: String, desc: String) {
2259+ Row(verticalAlignment = Alignment.CenterVertically) {
2262+ style = MaterialTheme.typography.labelLarge,
2263+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2264+ modifier = Modifier.widthIn(min = 160.dp),
2268+ style = MaterialTheme.typography.bodyMedium,
2269+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2275+ * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2276+ * of matching commands above the composer. Tapping a command fires it immediately.
2277+ * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2278+ * the detekt threshold. Suppressed while running or when the command catalog is empty.
2281+private fun SlashCommandAutocomplete(
2283+ commands: List<Command>,
2285+ onRunCommand: (Command) -> Unit,
2287+ if (running || commands.isEmpty()) return
2288+ val slashQuery = remember(value) {
2289+ if (value.startsWith("/")) value.removePrefix("/") else null
2291+ val matchingCommands = remember(slashQuery, commands) {
2292+ commands.filter { cmd ->
2293+ slashQuery.isEmpty() ||
2294+ cmd.name.contains(slashQuery, ignoreCase = true) ||
2295+ (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2298+ if (matchingCommands.isNotEmpty()) {
2299+ CommandAutocompleteDropdown(
2300+ commands = matchingCommands,
2301+ onPick = onRunCommand,
2307+ * Slash-command autocomplete dropdown shown above the composer when the draft starts
2308+ * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2309+ * user can discover and invoke commands by typing the conventional "/" prefix instead
2310+ * of opening the overflow menu / command palette. Tapping a row fires the command.
2313+private fun CommandAutocompleteDropdown(
2314+ commands: List<Command>,
2315+ onPick: (Command) -> Unit,
2317+ val haptics = LocalHapticFeedback.current
2319+ color = MaterialTheme.colorScheme.surface,
2320+ tonalElevation = 3.dp,
2321+ shape = MaterialTheme.shapes.medium,
2322+ modifier = Modifier
2324+ .padding(horizontal = 8.dp, vertical = 4.dp)
2325+ .heightIn(max = 240.dp),
2329+ count = commands.size,
2330+ key = { commands[it].name },
2332+ val cmd = commands[i]
2334+ modifier = Modifier
2336+ .clickable(role = Role.Button) {
2337+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2340+ .padding(horizontal = 16.dp, vertical = 10.dp),
2341+ verticalAlignment = Alignment.CenterVertically,
2342+ horizontalArrangement = Arrangement.spacedBy(12.dp),
2346+ style = MaterialTheme.typography.labelLarge,
2347+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2348+ color = MaterialTheme.colorScheme.primary,
2350+ cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2353+ style = MaterialTheme.typography.bodySmall,
2354+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2356+ overflow = TextOverflow.Ellipsis,
2365+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2366+@Suppress("CyclomaticComplexMethod")
2368+private fun ChatInputBar(
2370+ onValueChange: (String) -> Unit,
2374+ sendOnEnter: Boolean,
2375+ onSend: () -> Unit,
2376+ onAbort: () -> Unit,
2377+ queuedFollowUp: String?,
2378+ onQueueFollowUp: (String) -> Unit,
2379+ onCancelQueue: () -> Unit,
2380+ focusRequester: androidx.compose.ui.focus.FocusRequester,
2381+ attachments: List<PendingAttachment>,
2383+ stagingFileCount: Int,
2384+ onRemoveAttachment: (String) -> Unit,
2385+ onPickPhoto: () -> Unit,
2386+ onPickFile: () -> Unit,
2387+ onCamera: () -> Unit,
2388+ onVoice: () -> Unit,
2389+ onPasteImage: (List<Uri>) -> Unit,
2390+ commands: List<Command> = emptyList(),
2391+ onRunCommand: (Command) -> Unit = {},
2393+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2394+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2395+ val context = LocalContext.current
2396+ // Full-screen editor state: opened when the user wants more space for a long prompt.
2397+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2398+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2399+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2400+ // A queued follow-up replaces the Stop button with a "queued" chip so the
2401+ // user sees their message will be sent when the run finishes, and can cancel.
2402+ if (queuedFollowUp != null) {
2403+ val editLabel = stringResource(R.string.edit)
2405+ modifier = Modifier
2407+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2408+ verticalAlignment = Alignment.CenterVertically,
2410+ // Tapping the chip reloads the queued text into the draft (and clears the
2411+ // queue) so a typo spotted while queuing can be fixed without retyping.
2413+ modifier = Modifier
2415+ .clip(MaterialTheme.shapes.small)
2416+ .clickable(role = Role.Button, onClickLabel = editLabel) {
2417+ onValueChange(queuedFollowUp)
2420+ .padding(vertical = 4.dp),
2423+ stringResource(R.string.queued),
2424+ style = MaterialTheme.typography.labelSmall,
2425+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2429+ style = MaterialTheme.typography.bodySmall,
2430+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2432+ overflow = TextOverflow.Ellipsis,
2435+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2436+ Text(stringResource(R.string.cancel))
2440+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2441+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2442+ // Slash-command autocomplete: extracted to a helper to keep this function's
2443+ // complexity under the detekt threshold. Returns no-op when the draft doesn't
2444+ // start with "/" or the command catalog is empty.
2445+ SlashCommandAutocomplete(
2447+ commands = commands,
2449+ onRunCommand = onRunCommand,
2452+ modifier = Modifier.fillMaxWidth().padding(8.dp),
2453+ verticalAlignment = Alignment.Bottom,
2455+ // Attach menu: photo picker, camera, or any file.
2456+ var showAttachMenu by remember { mutableStateOf(false) }
2458+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2459+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2461+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2463+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2464+ text = { Text(stringResource(R.string.attach_photo)) },
2465+ onClick = { showAttachMenu = false; onPickPhoto() },
2468+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2469+ text = { Text(stringResource(R.string.attach_camera)) },
2470+ onClick = { showAttachMenu = false; onCamera() },
2473+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2474+ text = { Text(stringResource(R.string.attach_file)) },
2475+ onClick = { showAttachMenu = false; onPickFile() },
2479+ // Voice dictation: appends recognized speech to the draft. Hidden (not just
2480+ // disabled) when the device has no speech-recognition activity, so a user
2481+ // without a voice app doesn't get a button that only fails noisily on tap.
2482+ val voiceAvailable = remember {
2483+ val pm = context.packageManager
2484+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2485+ pm.queryIntentActivities(intent, 0).isNotEmpty()
2487+ if (voiceAvailable) {
2488+ IconButton(onClick = onVoice, enabled = enabled) {
2489+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2492+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2493+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2494+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2498+ onValueChange = { v ->
2499+ // Cap input length so a huge paste can't stall the UI. Shares are
2500+ // capped separately in MainActivity; this guards typed/pasted drafts.
2501+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2503+ modifier = Modifier
2505+ .focusRequester(focusRequester)
2506+ .testTag("chat_input")
2507+ // Intercept image content pasted/dropped into the field (keyboard paste
2508+ // of a copied screenshot, drag from Files, etc.) and route it through the
2509+ // same staging path as the attach menu. Non-image content (text) falls
2510+ // through unchanged so normal typing/paste works.
2513+ androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2514+ val clipData = transferable.clipEntry?.clipData
2515+ if (clipData != null) {
2516+ val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2517+ val item = clipData.getItemAt(i)
2518+ item.uri?.takeIf { uri ->
2519+ item.text == null && uri.toString().let { s ->
2520+ s.startsWith("content:") || s.startsWith("file:")
2524+ if (imageUris.isNotEmpty()) {
2525+ onPasteImage(imageUris)
2532+ .onPreviewKeyEvent { event ->
2533+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2534+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2535+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
2536+ val send = enterShouldSend(
2538+ hasContent = hasContent,
2539+ sendOnEnter = sendOnEnter,
2540+ shift = event.isShiftPressed,
2541+ ctrl = event.isCtrlPressed,
2544+ if (running) onQueueFollowUp(value) else onSend()
2550+ // While a run is active a typed message only queues (sends after the run), so
2551+ // the placeholder says so instead of the plain "Message…".
2553+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2557+ // Show a "N / max" countdown once the draft crosses a high fraction of
2558+ // the cap, so the user knows a paste is about to be truncated instead
2559+ // of being silently cut off. Hidden for normal short prompts to avoid
2560+ // clutter under a typical one-line message.
2562+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2563+ if (value.length >= threshold) {
2566+ R.string.draft_chars_remaining,
2567+ NetworkConfig.maxDraftLengthChars - value.length,
2568+ NetworkConfig.maxDraftLengthChars,
2570+ style = MaterialTheme.typography.labelSmall,
2571+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2572+ else MaterialTheme.colorScheme.onSurfaceVariant,
2574+ } else if (value.lines().size > 6) {
2575+ // The inline field caps at 6 lines; once the draft crosses that,
2576+ // hint that a bigger full-screen editor exists (the Expand icon
2577+ // above is easy to miss among the icon row). A tappable label
2578+ // would be ideal, but a plain hint is enough to draw attention.
2580+ stringResource(R.string.open_full_editor_hint),
2581+ style = MaterialTheme.typography.labelSmall,
2582+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2586+ keyboardOptions = KeyboardOptions(
2587+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
2588+ // keyboard shows a send key — matching the setting's intent and
2589+ // giving touch-only users a keyboard send affordance. When off,
2590+ // ImeAction.Default keeps the enter/newline key for multi-line input.
2591+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2592+ capitalization = KeyboardCapitalization.Sentences,
2594+ keyboardActions = KeyboardActions(
2596+ // Mirror the hardware-Enter handler: during a run the soft-keyboard
2597+ // send key must queue the follow-up, not silently drop it. vm.send()
2598+ // returns false while a run is active (beginRun() rejects), so calling
2599+ // onSend() directly here would lose the typed message with no feedback
2600+ // for touch-only users (no hardware Enter path available).
2601+ if (enabled && hasContent) {
2602+ if (running) onQueueFollowUp(value) else onSend()
2607+ ComposerTrailingButton(
2609+ aborting = aborting,
2610+ canSend = enabled && hasContent,
2611+ canQueue = enabled && value.isNotBlank(),
2614+ onQueue = { onQueueFollowUp(value) },
2618+ if (showFullScreenEditor) {
2621+ onValueChange = onValueChange,
2622+ onDismiss = { showFullScreenEditor = false },
2624+ showFullScreenEditor = false
2625+ // Mirror the inline composer's behavior: while a run is active a send
2626+ // can't go immediately, so queue the follow-up instead of silently
2627+ // dropping it (vm.send() returns false during a run, which previously
2628+ // lost the typed message with no feedback).
2629+ if (running) onQueueFollowUp(value) else onSend()
2631+ canSend = enabled && hasContent,
2633+ sendOnEnter = sendOnEnter,
2634+ attachments = attachments,
2635+ onRemoveAttachment = onRemoveAttachment,
2637+ stagingFileCount = stagingFileCount,
2643+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2644+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2645+@OptIn(ExperimentalMaterial3Api::class)
2647+private fun FullScreenEditor(
2649+ onValueChange: (String) -> Unit,
2650+ onDismiss: () -> Unit,
2651+ onSend: () -> Unit,
2653+ running: Boolean = false,
2654+ sendOnEnter: Boolean = false,
2655+ attachments: List<PendingAttachment> = emptyList(),
2656+ onRemoveAttachment: (String) -> Unit = {},
2657+ staging: Boolean = false,
2658+ stagingFileCount: Int = 0,
2660+ androidx.compose.ui.window.Dialog(
2661+ onDismissRequest = onDismiss,
2662+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2664+ // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2665+ // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2666+ // gives the available width so we can center a capped-width column.
2667+ androidx.compose.foundation.layout.BoxWithConstraints(
2668+ modifier = Modifier.fillMaxSize(),
2669+ contentAlignment = Alignment.Center,
2671+ val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2672+ ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2675+ modifier = Modifier.padding(horizontal = hPad),
2677+ androidx.compose.material3.TopAppBar(
2678+ title = { Text(stringResource(R.string.compose_editor_title)) },
2680+ androidx.compose.material3.TextButton(onClick = onDismiss) {
2681+ Text(stringResource(R.string.collapse_editor))
2687+ Surface(tonalElevation = 3.dp) {
2689+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2690+ horizontalArrangement = Arrangement.End,
2692+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2693+ Text(stringResource(if (running) R.string.queue else R.string.send))
2699+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2700+ // Show staged attachments in the full-screen editor too, so a user who staged
2701+ // images then expanded for a long prompt can still see and remove them without
2702+ // collapsing first (mirrors the inline composer's AttachmentStrip).
2703+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2706+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2707+ modifier = Modifier
2710+ // Honor the "Send on Enter" setting here too, so the full-screen
2711+ // editor matches the inline composer: Enter sends (Shift+Enter
2712+ // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2713+ // when off. Previously this hard-coded ImeAction.Default and had no
2714+ // key handler, so a hardware-keyboard user got a different behaviour
2715+ // from the inline composer depending on which they happened to open.
2716+ .onPreviewKeyEvent { event ->
2717+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2718+ val send = enterShouldSend(
2720+ hasContent = canSend,
2721+ sendOnEnter = sendOnEnter,
2722+ shift = event.isShiftPressed,
2723+ ctrl = event.isCtrlPressed,
2725+ if (send) { onSend(); true } else false
2727+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
2728+ maxLines = Int.MAX_VALUE,
2729+ keyboardOptions = KeyboardOptions(
2730+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2731+ capitalization = KeyboardCapitalization.Sentences,
2733+ keyboardActions = KeyboardActions(
2734+ onSend = { if (canSend) onSend() },
2743+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2744+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2745+private fun enterShouldSend(
2747+ hasContent: Boolean,
2748+ sendOnEnter: Boolean,
2752+ !enabled || !hasContent -> false
2753+ sendOnEnter -> !shift
2757+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2758+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2759+ * [ChatInputBar] stays under the complexity threshold. */
2761+private fun ComposerTrailingButton(
2766+ onSend: () -> Unit,
2767+ onAbort: () -> Unit,
2768+ onQueue: () -> Unit,
2771+ Row(verticalAlignment = Alignment.CenterVertically) {
2772+ // While a run is active the trailing action is Stop, so the only send affordance is
2773+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2774+ // That leaves a touch-only user with the setting off no way to queue a follow-up
2775+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2776+ // there's typed TEXT so queuing is always reachable, without changing the user's
2777+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2778+ // canSend, which is also true for an attachment-only composer — because queuing "" just
2779+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2780+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2784+ modifier = Modifier.testTag("queue_button"),
2786+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2787+ // icon (which can be read as "snooze" or "later"), and isn't confused with
2788+ // the Send action sitting right beside the Stop button.
2790+ Icons.AutoMirrored.Filled.PlaylistAdd,
2791+ contentDescription = stringResource(R.string.queue_followup),
2795+ // Show a spinner while the abort REST call is in flight so the user sees the stop
2796+ // was sent, and disable to prevent a double-tap.
2799+ enabled = !aborting,
2800+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2803+ val stopLabel = stringResource(R.string.stop)
2804+ CircularProgressIndicator(
2805+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2806+ strokeWidth = 2.dp,
2809+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2817+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2819+ // Tint the send icon with primary when there's content to send so the commit action
2820+ // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2822+ Icons.AutoMirrored.Filled.Send,
2823+ contentDescription = stringResource(R.string.send),
2824+ tint = if (canSend) MaterialTheme.colorScheme.primary
2825+ else MaterialTheme.colorScheme.onSurfaceVariant,
2831+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2833+private fun EmptyConversation(
2834+ onSuggestion: (String) -> Unit,
2835+ modifier: Modifier = Modifier,
2837+ // A few example prompts so a first-time user has a one-tap path to their first
2838+ // message instead of staring at a blank input. Tapping a chip fills the draft
2839+ // (without sending) so the user can edit it before sending.
2840+ val suggestions = remember {
2842+ R.string.empty_chat_suggest_1,
2843+ R.string.empty_chat_suggest_2,
2844+ R.string.empty_chat_suggest_3,
2848+ modifier = modifier.padding(32.dp),
2849+ horizontalAlignment = Alignment.CenterHorizontally,
2852+ Icons.Filled.AutoAwesome,
2853+ contentDescription = null,
2854+ modifier = Modifier.size(48.dp),
2855+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
2857+ Spacer(Modifier.size(16.dp))
2859+ stringResource(R.string.empty_chat_title),
2860+ style = MaterialTheme.typography.titleMedium,
2862+ Spacer(Modifier.size(8.dp))
2864+ stringResource(R.string.empty_chat_hint),
2865+ style = MaterialTheme.typography.bodyMedium,
2866+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2868+ Spacer(Modifier.size(20.dp))
2869+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2870+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
2872+ modifier = Modifier.fillMaxWidth(),
2873+ horizontalArrangement = Arrangement.spacedBy(8.dp),
2874+ verticalArrangement = Arrangement.spacedBy(8.dp),
2876+ suggestions.forEach { resId ->
2877+ val text = stringResource(resId)
2878+ androidx.compose.material3.AssistChip(
2879+ onClick = { onSuggestion(text) },
2880+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2887+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2888+ * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2889+ * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2891+private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2892+ val haptics = LocalHapticFeedback.current
2893+ var showDiff by rememberSaveable { mutableStateOf(false) }
2894+ val expandMotion = rememberVisibilityTransitions()
2896+ color = MaterialTheme.colorScheme.tertiaryContainer,
2897+ tonalElevation = 2.dp,
2898+ modifier = Modifier.fillMaxWidth(),
2902+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2903+ verticalAlignment = Alignment.CenterVertically,
2904+ horizontalArrangement = Arrangement.SpaceBetween,
2906+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2908+ if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2909+ contentDescription = null,
2910+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
2911+ modifier = Modifier.size(18.dp),
2914+ stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2915+ style = MaterialTheme.typography.bodySmall,
2916+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2917+ modifier = Modifier.padding(start = 8.dp),
2919+ // "Show what changed" toggle, shown only when the server provided a diff.
2920+ // Collapsible so the banner stays compact by default; a user curious about
2921+ // what the revert rolled back can expand it inline without leaving the chat.
2922+ if (!diff.isNullOrBlank()) {
2925+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2926+ showDiff = !showDiff
2928+ contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2931+ if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2932+ contentDescription = null,
2933+ modifier = Modifier.size(16.dp),
2936+ stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2937+ style = MaterialTheme.typography.labelSmall,
2938+ modifier = Modifier.padding(start = 4.dp),
2943+ TextButton(onClick = {
2944+ // Haptic on undo to match the other destructive/important confirmations: a
2945+ // revert restores potentially hundreds of hidden messages.
2946+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2948+ }) { Text(stringResource(R.string.undo)) }
2950+ // The diff render lives inside the banner's Surface so it inherits the tertiary
2951+ // tonal container and reads as part of the banner, not a floating panel.
2952+ if (!diff.isNullOrBlank()) {
2953+ AnimatedVisibility(
2954+ visible = showDiff,
2955+ enter = expandMotion.enter,
2956+ exit = expandMotion.exit,
2958+ Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2960+ stringResource(R.string.revert_diff_header),
2961+ style = MaterialTheme.typography.labelSmall,
2962+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2963+ modifier = Modifier.padding(bottom = 4.dp),
2965+ DiffView(diff, saveKey = "revertDiff")
2973+/** A dismissible preview card shown above the composer when the user quote-replied to a
2974+ * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2975+ * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2976+ * the Discord/Slack quote-preview pattern. */
2978+private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2979+ val haptics = LocalHapticFeedback.current
2981+ color = MaterialTheme.colorScheme.secondaryContainer,
2982+ tonalElevation = 2.dp,
2983+ modifier = Modifier.fillMaxWidth(),
2986+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2987+ verticalAlignment = Alignment.Top,
2990+ Icons.Filled.FormatQuote,
2991+ contentDescription = null,
2992+ tint = MaterialTheme.colorScheme.onSecondaryContainer,
2993+ modifier = Modifier.size(18.dp).padding(top = 2.dp),
2995+ Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2997+ stringResource(R.string.quote_reply_banner),
2998+ style = MaterialTheme.typography.labelSmall,
2999+ color = MaterialTheme.colorScheme.onSecondaryContainer,
3003+ style = MaterialTheme.typography.bodySmall,
3004+ color = MaterialTheme.colorScheme.onSecondaryContainer,
3006+ overflow = TextOverflow.Ellipsis,
3009+ IconButton(onClick = {
3010+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
3014+ Icons.Filled.Close,
3015+ contentDescription = stringResource(R.string.cancel_quote_reply),
3016+ tint = MaterialTheme.colorScheme.onSecondaryContainer,
3017+ modifier = Modifier.size(18.dp),
3024+/** A banner shown while messages composed offline are queued in the outbox, with a
3025+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
3027+private fun OutboxBanner(
3030+ onFlush: () -> Unit,
3031+ onDiscard: () -> Unit,
3033+ var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
3035+ color = MaterialTheme.colorScheme.secondaryContainer,
3036+ tonalElevation = 2.dp,
3037+ modifier = Modifier.fillMaxWidth(),
3040+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
3041+ verticalAlignment = Alignment.CenterVertically,
3042+ horizontalArrangement = Arrangement.SpaceBetween,
3044+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
3046+ CircularProgressIndicator(
3047+ Modifier.size(16.dp),
3048+ strokeWidth = 2.dp,
3049+ color = MaterialTheme.colorScheme.onSecondaryContainer,
3051+ Spacer(Modifier.size(8.dp))
3055+ stringResource(R.string.outbox_sending)
3057+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
3058+ stringResource(res, count)
3060+ style = MaterialTheme.typography.bodySmall,
3061+ color = MaterialTheme.colorScheme.onSecondaryContainer,
3065+ val haptics = LocalHapticFeedback.current
3066+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
3067+ TextButton(onClick = {
3068+ // Confirm before discarding all queued messages (irreversible), matching
3069+ // the confirmation pattern used by deleteSession and other destructive
3070+ // actions. Previously a single tap dropped every queued message.
3071+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
3072+ showDiscardConfirm = true
3074+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
3079+ if (showDiscardConfirm) {
3080+ androidx.compose.material3.AlertDialog(
3081+ onDismissRequest = { showDiscardConfirm = false },
3082+ title = { Text(stringResource(R.string.discard_queued_title)) },
3083+ text = { Text(stringResource(R.string.discard_queued_text, count)) },
3085+ androidx.compose.material3.TextButton(onClick = {
3086+ showDiscardConfirm = false
3088+ }) { Text(stringResource(R.string.discard)) }
3091+ androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3092+ Text(stringResource(R.string.cancel))
3099+/** Prompt for a one-off shell command to run in the session's worktree. */
3101+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3102+ var command by rememberSaveable { mutableStateOf("") }
3104+ onDismissRequest = onDismiss,
3105+ title = { Text(stringResource(R.string.run_shell_command)) },
3109+ onValueChange = { command = it },
3110+ modifier = Modifier.fillMaxWidth(),
3111+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3112+ label = { Text(stringResource(R.string.shell_command_label)) },
3114+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3115+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3120+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3121+ enabled = command.isNotBlank(),
3122+ ) { Text(stringResource(R.string.run)) }
3124+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3129+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3130+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3131+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
3133+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3135+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3136+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3137+ * streaming, not just plain assistant text. O(1). */
3138+private fun streamingContentLength(part: Part?): Int = when (part) {
3139+ is TextPart -> part.text.length
3140+ is ReasoningPart -> part.text.length
3141+ is ToolPart -> when (val st = part.state) {
3142+ is ToolCompleted -> st.output?.length ?: 0
3143+ is ToolError -> st.error?.length ?: 0
3144+ is ToolRunning -> st.title?.length ?: 0
3150+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3151+ * dialog but lives in the chat screen so the user can rename without backing out to
3152+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
3154+private fun RenameSessionChatDialog(
3155+ initialTitle: String,
3156+ onDismiss: () -> Unit,
3157+ onConfirm: (String) -> Unit,
3159+ // Seed the field once (no key input) so a later external title change — e.g. opencode
3160+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3161+ // doesn't re-initialize the box and discard the user's in-progress edit.
3162+ var title by rememberSaveable { mutableStateOf(initialTitle) }
3164+ onDismissRequest = onDismiss,
3165+ title = { Text(stringResource(R.string.rename_session_chat)) },
3169+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3170+ modifier = Modifier.fillMaxWidth(),
3171+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
3172+ label = { Text(stringResource(R.string.rename_session_chat)) },
3174+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3175+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3179+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3180+ Text(stringResource(R.string.save))
3184+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3190+ * A single item in the chat message list — either a [Message] bubble or a day
3191+ * [Separator] inserted before the first message of a new day. The separator shifts
3192+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3193+ * the [List] of these items (not `messages.size`/`lastIndex`).
3195+private sealed interface MessageListItem {
3197+ val contentType: Any
3199+ data class Message(
3200+ val message: MessageWithParts,
3201+ override val key: Any,
3202+ // Whether this is the first message in a consecutive run of the same speaker (role).
3203+ // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3204+ // reducing visual noise in tool-heavy conversations where many assistant messages
3205+ // appear back-to-back. A separator or a role change resets the flag.
3206+ val isFirstOfSpeaker: Boolean,
3207+ ) : MessageListItem {
3208+ override val contentType: Any get() = message.info::class
3211+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3212+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3213+ // can share a label (e.g. an untimestamped message — empty label — between two
3214+ // same-day messages, or two untimestamped groups), and a label-only key would
3215+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3216+ // stable for a given message ordering so slots aren't needlessly recreated.
3217+ override val key: Any get() = "sep_${ordinal}_$label"
3218+ // Separators share a contentType so the LazyColumn can recycle their slots.
3219+ override val contentType: Any get() = "separator"
3224+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3225+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3226+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3227+ * Messages with no timestamp are grouped under an empty-label separator only if they
3228+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
3230+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3231+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3232+ * labels; older days fall back to a locale-stable medium-date format.
3234+private fun buildMessageListItems(
3235+ messages: List<MessageWithParts>,
3236+ todayLabel: String,
3237+ yesterdayLabel: String,
3238+): List<MessageListItem> {
3239+ if (messages.isEmpty()) return emptyList()
3240+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3241+ val dateFmt = mediumDateFormat()
3242+ val result = ArrayList<MessageListItem>(messages.size + 4)
3243+ val seenKeys = HashSet<String>(messages.size * 2)
3244+ var lastDayKey: String? = null
3246+ var emptyIdOrdinal = 0
3248+ // Track the previous message's role to detect consecutive same-speaker runs, so the
3249+ // avatar/header can be suppressed on follow-up messages in the same run. A null means
3250+ // "no previous message or a separator just interrupted the run", both of which make the
3251+ // next message the first of its group.
3252+ var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3253+ for (message in messages) {
3254+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3255+ val dayKey = ts?.let { dayKey(it) } ?: ""
3256+ // Emit a separator before the very first message (so a leading un-timestamped message
3257+ // still gets the first divider, empty label and all), and thereafter only when crossing
3258+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3259+ // neither emits its own separator nor resets the day — otherwise a following same-day
3260+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3261+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3262+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3263+ // A date separator visually breaks a speaker run, so the next message is treated
3264+ // as the first of its group (even if the same role continues across the day break).
3265+ prevRoleClass = null
3267+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
3269+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3270+ // empty id — and the reducer intentionally keeps several such messages as distinct
3271+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
3272+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3273+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3274+ if (!seenKeys.add(key)) {
3276+ while (!seenKeys.add("$key#$suffix")) suffix++
3277+ key = "$key#$suffix"
3279+ val roleClass = message.info::class
3280+ val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3281+ result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3282+ prevRoleClass = roleClass
3288+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3290+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3291+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
3292+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3293+ * every message on every token. Message timestamps are immutable once assigned, so we
3294+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3295+ * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3297+ * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3298+ * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3299+ * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3300+ * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3301+ * reads, so the common case (a hit) is a single volatile read + hash probe.
3302+ * [removeEldestEntry] is not available on ConcurrentHashMap, so the bound is enforced via
3303+ * a size check in [dayKey]: once the cap ([DAY_KEY_CACHE_MAX]) is reached the cache is
3304+ * cleared; in practice the cache size is bounded by the number of distinct message
3305+ * timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]) and the cap is a
3306+ * safety valve for the process-lifetime cache across many sessions.
3308+private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3310+/** Upper bound on [dayKeyCache] entries. Message timestamps are immutable once assigned, so
3311+ * the natural bound is the number of distinct timestamps in a session (≤
3312+ * [NetworkConfig.maxInMemoryMessages]); this cap is a safety valve for the process-lifetime
3313+ * cache across many sessions, keeping a runaway leak from accumulating unbounded memory. */
3314+private const val DAY_KEY_CACHE_MAX = 1024
3316+private fun dayKey(epochMillis: Long): String {
3317+ val cached = dayKeyCache[epochMillis]
3318+ if (cached != null) return cached
3319+ val value = java.time.Instant.ofEpochMilli(epochMillis)
3320+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3321+ // Guard the size under the cache's concurrency: only the first thread to see the cap
3322+ // exceeded evicts (draining is O(N) but rare and idempotent), so concurrent inserts
3323+ // past the cap don't each pay the scan. computeIfAbsent would hold the segment lock
3324+ // during the (cheap) date computation but can't express the size guard, so use put
3325+ // after the fact; a duplicate put of the same key/value is harmless.
3326+ if (dayKeyCache.size >= DAY_KEY_CACHE_MAX) dayKeyCache.clear()
3327+ dayKeyCache[epochMillis] = value
3331+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3332+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3333+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3334+private var cachedDateFmt: java.text.DateFormat? = null
3335+private var cachedDateFmtLocale: java.util.Locale? = null
3337+private fun mediumDateFormat(): java.text.DateFormat {
3338+ val locale = java.util.Locale.getDefault()
3339+ val existing = cachedDateFmt
3340+ if (existing != null && cachedDateFmtLocale == locale) return existing
3341+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3343+ cachedDateFmtLocale = locale
3348+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3349+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3350+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3353+private fun dayLabel(
3356+ today: java.time.LocalDate,
3357+ todayLabel: String,
3358+ yesterdayLabel: String,
3359+ dateFmt: java.text.DateFormat,
3361+ if (dayKey.isEmpty()) return ""
3362+ val epochDay = dayKey.toLongOrNull() ?: return ""
3363+ val date = java.time.LocalDate.ofEpochDay(epochDay)
3365+ date == today -> todayLabel
3366+ date == today.minusDays(1) -> yesterdayLabel
3367+ else -> dateFmt.format(java.util.Date(ts))
3372+ * A centered day divider in the message list. Renders nothing for an empty label
3373+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3376+private fun DateSeparator(label: String) {
3377+ if (label.isBlank()) return
3379+ modifier = Modifier.fillMaxWidth(),
3380+ horizontalArrangement = Arrangement.Center,
3383+ color = MaterialTheme.colorScheme.surfaceVariant,
3384+ shape = MaterialTheme.shapes.small,
3385+ // Marked as a heading so TalkBack users can navigate day-by-day with the
3386+ // heading-skip gesture — the canonical affordance for date dividers in a list.
3387+ modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3391+ style = MaterialTheme.typography.labelSmall,
3392+ color = MaterialTheme.colorScheme.onSurfaceVariant,
3393+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3399+/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3400+ * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3401+ * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3402+ * [BoxScope] extension so it can align itself to the top center of its host box. */
3404+private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3405+ val loadingLabel = stringResource(R.string.loading)
3406+ val reducedMotion = LocalReducedMotion.current
3407+ val transition = rememberInfiniteTransition(label = "skeleton")
3408+ val pulse by transition.animateFloat(
3409+ initialValue = 0.35f,
3410+ targetValue = 0.7f,
3411+ animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3412+ label = "skeletonAlpha",
3414+ val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3415+ val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3417+ fun bar(widthFraction: Float) {
3420+ .fillMaxWidth(widthFraction)
3422+ .clip(RoundedCornerShape(4.dp))
3423+ .background(skeletonColor)
3424+ .alpha(skeletonAlpha),
3428+ modifier = Modifier
3429+ .align(Alignment.TopCenter)
3430+ .padding(top = topPad)
3433+ .semantics { contentDescription = loadingLabel },
3434+ verticalArrangement = Arrangement.spacedBy(14.dp),
3437+ val left = i % 2 == 0
3439+ modifier = Modifier.fillMaxWidth(),
3440+ horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3443+ modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3444+ verticalArrangement = Arrangement.spacedBy(6.dp),