@@ -0,0 +1,2528 @@
1+@file:Suppress("TooManyFunctions")
2+
3+package soy.iko.opencode.ui.chat
4+
5+import android.app.Activity
6+import android.content.Intent
7+import android.net.Uri
8+import android.speech.RecognizerIntent
9+import androidx.activity.compose.BackHandler
10+import androidx.activity.compose.rememberLauncherForActivityResult
11+import androidx.activity.result.PickVisualMediaRequest
12+import androidx.activity.result.contract.ActivityResultContracts
13+import androidx.compose.animation.AnimatedVisibility
14+import androidx.compose.animation.core.RepeatMode
15+import androidx.compose.animation.core.animateFloat
16+import androidx.compose.animation.core.infiniteRepeatable
17+import androidx.compose.animation.core.rememberInfiniteTransition
18+import androidx.compose.animation.core.tween
19+import androidx.compose.foundation.background
20+import androidx.compose.foundation.clickable
21+import androidx.compose.foundation.content.contentReceiver
22+import androidx.compose.foundation.layout.Arrangement
23+import androidx.compose.foundation.layout.Box
24+import androidx.compose.foundation.layout.Column
25+import androidx.compose.foundation.layout.FlowRow
26+import androidx.compose.foundation.layout.PaddingValues
27+import androidx.compose.foundation.layout.Row
28+import androidx.compose.foundation.layout.Spacer
29+import androidx.compose.foundation.layout.WindowInsets
30+import androidx.compose.foundation.layout.fillMaxSize
31+import androidx.compose.foundation.layout.fillMaxWidth
32+import androidx.compose.foundation.layout.height
33+import androidx.compose.foundation.layout.imePadding
34+import androidx.compose.foundation.layout.navigationBars
35+import androidx.compose.foundation.layout.padding
36+import androidx.compose.foundation.layout.size
37+import androidx.compose.foundation.layout.union
38+import androidx.compose.foundation.layout.widthIn
39+import androidx.compose.foundation.layout.windowInsetsPadding
40+import androidx.compose.foundation.layout.wrapContentWidth
41+import androidx.compose.foundation.lazy.LazyColumn
42+import androidx.compose.foundation.lazy.items
43+import androidx.compose.foundation.lazy.rememberLazyListState
44+import androidx.compose.foundation.shape.RoundedCornerShape
45+import androidx.compose.material.icons.Icons
46+import androidx.compose.material.icons.automirrored.filled.ArrowBack
47+import androidx.compose.material.icons.automirrored.filled.Send
48+import androidx.compose.material.icons.filled.Add
49+import androidx.compose.material.icons.filled.AutoAwesome
50+import androidx.compose.material.icons.filled.Delete
51+import androidx.compose.material.icons.filled.Description
52+import androidx.compose.material.icons.filled.Close
53+import androidx.compose.material.icons.filled.Edit
54+import androidx.compose.material.icons.filled.Expand
55+import androidx.compose.material.icons.filled.Search
56+import androidx.compose.material.icons.filled.KeyboardArrowDown
57+import androidx.compose.material.icons.filled.KeyboardArrowUp
58+import androidx.compose.material.icons.filled.Mic
59+import androidx.compose.material.icons.filled.MoreVert
60+import androidx.compose.material.icons.filled.PhotoCamera
61+import androidx.compose.material.icons.filled.PhotoLibrary
62+import androidx.compose.material.icons.filled.Refresh
63+import androidx.compose.material.icons.filled.Restore
64+import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
65+import androidx.compose.material.icons.automirrored.filled.Reply
66+import androidx.compose.material.icons.filled.Schedule
67+import androidx.compose.material.icons.filled.Stop
68+import androidx.compose.material3.AlertDialog
69+import androidx.compose.material3.Badge
70+import androidx.compose.material3.BadgedBox
71+import androidx.compose.material3.Button
72+import androidx.compose.material3.CircularProgressIndicator
73+import androidx.compose.material3.SmallFloatingActionButton
74+import androidx.compose.material3.DropdownMenu
75+import androidx.compose.material3.DropdownMenuItem
76+import androidx.compose.material3.ExperimentalMaterial3Api
77+import androidx.compose.material3.ExtendedFloatingActionButton
78+import androidx.compose.material3.FloatingActionButton
79+import androidx.compose.material3.Icon
80+import androidx.compose.material3.IconButton
81+import androidx.compose.material3.MaterialTheme
82+import androidx.compose.material3.OutlinedTextField
83+import androidx.compose.material3.Scaffold
84+import androidx.compose.material3.SnackbarDuration
85+import androidx.compose.material3.SwipeToDismissBox
86+import androidx.compose.material3.SwipeToDismissBoxValue
87+import androidx.compose.material3.rememberSwipeToDismissBoxState
88+import androidx.compose.material3.SnackbarHost
89+import androidx.compose.material3.SnackbarHostState
90+import androidx.compose.material3.SnackbarResult
91+import androidx.compose.material3.Surface
92+import androidx.compose.material3.Text
93+import androidx.compose.material3.TextButton
94+import androidx.compose.material3.TopAppBar
95+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
96+import androidx.compose.runtime.Composable
97+import androidx.compose.runtime.CompositionLocalProvider
98+import androidx.compose.runtime.DisposableEffect
99+import androidx.compose.runtime.LaunchedEffect
100+import androidx.compose.runtime.derivedStateOf
101+import androidx.compose.runtime.getValue
102+import androidx.compose.runtime.mutableIntStateOf
103+import androidx.compose.runtime.mutableLongStateOf
104+import androidx.compose.runtime.mutableStateOf
105+import androidx.compose.runtime.produceState
106+import androidx.compose.runtime.remember
107+import androidx.compose.runtime.rememberCoroutineScope
108+import androidx.compose.runtime.rememberUpdatedState
109+import androidx.compose.runtime.saveable.rememberSaveable
110+import androidx.compose.runtime.setValue
111+import androidx.compose.runtime.snapshotFlow
112+import androidx.compose.foundation.text.KeyboardActions
113+import androidx.compose.foundation.text.KeyboardOptions
114+import androidx.compose.ui.text.input.KeyboardCapitalization
115+import androidx.compose.ui.Alignment
116+import androidx.compose.ui.Modifier
117+import androidx.compose.ui.draw.alpha
118+import androidx.compose.ui.draw.clip
119+import androidx.compose.ui.focus.focusRequester
120+import androidx.compose.ui.input.key.Key
121+import androidx.compose.ui.input.key.KeyEventType
122+import androidx.compose.ui.input.key.isCtrlPressed
123+import androidx.compose.ui.input.key.isShiftPressed
124+import androidx.compose.ui.input.key.key
125+import androidx.compose.ui.input.key.onPreviewKeyEvent
126+import androidx.compose.ui.input.key.type
127+import androidx.compose.ui.layout.onSizeChanged
128+import androidx.compose.ui.platform.LocalContext
129+import androidx.compose.ui.platform.LocalDensity
130+import androidx.compose.ui.platform.LocalHapticFeedback
131+import androidx.compose.ui.platform.LocalView
132+import androidx.compose.ui.platform.testTag
133+import androidx.compose.ui.res.stringResource
134+import androidx.compose.ui.semantics.Role
135+import androidx.compose.ui.semantics.contentDescription
136+import androidx.compose.ui.semantics.heading
137+import androidx.compose.ui.semantics.semantics
138+import androidx.compose.ui.text.input.ImeAction
139+import androidx.compose.ui.text.style.TextOverflow
140+import androidx.compose.ui.unit.dp
141+import androidx.lifecycle.compose.collectAsStateWithLifecycle
142+import androidx.lifecycle.viewmodel.compose.viewModel
143+import kotlinx.coroutines.Dispatchers
144+import kotlinx.coroutines.coroutineScope
145+import kotlinx.coroutines.delay
146+import kotlinx.coroutines.flow.distinctUntilChanged
147+import kotlinx.coroutines.launch
148+import kotlinx.coroutines.withContext
149+import soy.iko.opencode.data.model.Part
150+import soy.iko.opencode.data.model.MessageWithParts
151+import soy.iko.opencode.data.model.ReasoningPart
152+import soy.iko.opencode.data.model.TextPart
153+import soy.iko.opencode.data.model.ToolCompleted
154+import soy.iko.opencode.data.model.ToolError
155+import soy.iko.opencode.data.model.ToolPart
156+import soy.iko.opencode.data.model.ToolRunning
157+import soy.iko.opencode.data.network.EventStreamClient
158+import soy.iko.opencode.data.network.NetworkConfig
159+import soy.iko.opencode.di.AppContainer
160+import soy.iko.opencode.R
161+import soy.iko.opencode.ui.components.CommandPalette
162+import soy.iko.opencode.ui.components.ConnectionBanner
163+import soy.iko.opencode.ui.components.PaletteAction
164+import soy.iko.opencode.ui.components.LocalReducedMotion
165+import soy.iko.opencode.ui.components.copyToClipboard
166+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
167+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
168+import soy.iko.opencode.ui.components.rememberVisibilityTransitions
169+import soy.iko.opencode.ui.components.showToast
170+import soy.iko.opencode.ui.components.toImageContext
171+import soy.iko.opencode.ui.vmFactory
172+import soy.iko.opencode.util.runCatchingCancellable
173+
174+@OptIn(ExperimentalMaterial3Api::class)
175+@Composable
176+fun ChatScreen(
177+ container: AppContainer,
178+ sessionId: String,
179+ onBack: () -> Unit,
180+ onOpenFile: ((String) -> Unit)? = null,
181+ onOpenSession: ((String) -> Unit)? = null,
182+) {
183+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
184+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
185+ val running by vm.running.collectAsStateWithLifecycle()
186+ val aborting by vm.aborting.collectAsStateWithLifecycle()
187+ val loading by vm.loading.collectAsStateWithLifecycle()
188+ val loadError by vm.loadError.collectAsStateWithLifecycle()
189+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
190+ val models by vm.models.collectAsStateWithLifecycle()
191+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
192+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
193+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
194+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
195+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
196+ val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
197+ val agents by vm.agents.collectAsStateWithLifecycle()
198+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
199+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
200+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
201+ val commands by vm.commands.collectAsStateWithLifecycle()
202+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
203+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
204+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
205+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
206+ val draft by vm.draft.collectAsStateWithLifecycle()
207+ val attachments by vm.attachments.collectAsStateWithLifecycle()
208+ val reverted by vm.reverted.collectAsStateWithLifecycle()
209+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
210+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
211+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
212+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
213+ val haptics = LocalHapticFeedback.current
214+ val scope = rememberCoroutineScope()
215+ val shareContext = LocalContext.current
216+ val defaultShareSubject = stringResource(R.string.share_subject)
217+ val sessionLabel = stringResource(R.string.session)
218+ val defaultModelLabel = stringResource(R.string.default_model)
219+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
220+ buildString {
221+ append(selectedModel?.modelLabel ?: defaultModelLabel)
222+ selectedAgent?.let { append(" · $it") }
223+ }
224+ }
225+
226+ // Connection profile (with auth) for rendering inline image attachments.
227+ // Collect as state so a server switch recomposes the image context.
228+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
229+ val imageContext = remember(activeConnection?.profile) {
230+ activeConnection?.profile?.toImageContext()
231+ }
232+
233+ // Mark this session as read while the user is viewing it; clear on leave so new
234+ // background activity can badge it again.
235+ DisposableEffect(sessionId) {
236+ container.setCurrentSession(sessionId)
237+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
238+ }
239+
240+ // Navigate away when the session is deleted via SSE so the user isn't left
241+ // on a zombie screen showing a conversation that no longer exists. Surface a
242+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
243+ // would be torn down before the user could read it, while a toast survives.
244+ // Covers both SSE-driven deletion (deleted on another device) and a user-
245+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
246+ // sets the same flag on success).
247+ val deletedContext = LocalContext.current
248+ LaunchedEffect(sessionDeleted) {
249+ if (sessionDeleted) {
250+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
251+ onBack()
252+ }
253+ }
254+
255+ val snackbar = remember { SnackbarHostState() }
256+ val retryLabel = stringResource(R.string.retry)
257+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
258+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
259+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
260+ var showTitleMenu by rememberSaveable { mutableStateOf(false) }
261+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
262+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
263+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
264+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
265+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
266+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
267+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
268+ var showPalette by rememberSaveable { mutableStateOf(false) }
269+ var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
270+ var searchActive by rememberSaveable { mutableStateOf(false) }
271+ var chatSearch by rememberSaveable { mutableStateOf("") }
272+ // Index of the currently-focused in-conversation search match (into the filtered list).
273+ // Drives the up/down navigation: the search bar's arrows step through matches and scroll
274+ // the list to each one, mirroring desktop chat apps (the bare filtered list previously
275+ // required reading each message to find the term).
276+ var searchPos by rememberSaveable { mutableIntStateOf(0) }
277+ // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
278+ // a confirmation dialog (from both the overflow menu and the command palette).
279+ var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
280+ var showInitConfirm by rememberSaveable { mutableStateOf(false) }
281+
282+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
283+ // action list doesn't need a Composable context. Actions map to the same handlers the
284+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
285+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
286+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
287+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
288+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
289+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
290+ val paletteShellLabel = stringResource(R.string.run_shell_command)
291+ val paletteActions = remember(
292+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
293+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
294+ ) {
295+ buildList {
296+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
297+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
298+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
299+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
300+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
301+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
302+ }
303+ }
304+
305+ // Keep the screen awake while the agent is working in *this* session. The foreground
306+ // service that holds process priority during a run is managed app-wide off
307+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
308+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
309+ // SSE stream before the completion notification fires.
310+ val currentView = LocalView.current
311+ val appContext = LocalContext.current.applicationContext
312+ DisposableEffect(running) {
313+ currentView.keepScreenOn = running
314+ onDispose { currentView.keepScreenOn = false }
315+ }
316+
317+ LaunchedEffect(Unit) {
318+ vm.errorEvents.collect { event ->
319+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
320+ // message-load failure) would silently re-submit the last prompt on tap.
321+ val result = if (event.retryable) {
322+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
323+ } else {
324+ snackbar.showSnackbar(event.message)
325+ }
326+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
327+ }
328+ }
329+
330+ // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
331+ // window on the container; show the snackbar over the conversation the user is viewing so
332+ // they can cancel without being navigated to the session list first. If the window expires
333+ // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
334+ val undoLabel = stringResource(R.string.undo)
335+ val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
336+ LaunchedEffect(Unit) {
337+ vm.deleteUndoEvents.collect {
338+ coroutineScope {
339+ val dismisser = launch {
340+ delay(NetworkConfig.undoDeleteDelayMs)
341+ snackbar.currentSnackbarData?.dismiss()
342+ }
343+ val result = snackbar.showSnackbar(
344+ message = sessionDeletedLabel,
345+ actionLabel = undoLabel,
346+ duration = SnackbarDuration.Indefinite,
347+ )
348+ dismisser.cancel()
349+ if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
350+ }
351+ }
352+ }
353+
354+ // --- Attachments, voice, and share-link plumbing ---
355+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
356+ val attachFailedMsg = stringResource(R.string.attachment_failed)
357+ val attachLimitMsg = stringResource(R.string.attachment_limit)
358+ val noCameraMsg = stringResource(R.string.no_camera_app)
359+ val noVoiceMsg = stringResource(R.string.no_voice_app)
360+ val voicePrompt = stringResource(R.string.voice_prompt)
361+ val linkCopiedMsg = stringResource(R.string.link_copied)
362+ val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
363+
364+ // Count of picks currently being read + base64-encoded off the main thread, so the
365+ // composer can show a staging placeholder immediately (chips only materialize once done).
366+ var stagingCount by remember { mutableStateOf(0) }
367+
368+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
369+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
370+ fun stageUris(uris: List<Uri>) {
371+ if (uris.isEmpty()) return
372+ scope.launch {
373+ stagingCount++
374+ try {
375+ for (uri in uris) {
376+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
377+ snackbar.showSnackbar(attachLimitMsg)
378+ break
379+ }
380+ when (val result = uri.toAttachmentResult(appContext)) {
381+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
382+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
383+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
384+ }
385+ }
386+ } finally {
387+ stagingCount--
388+ }
389+ }
390+ }
391+
392+ val photoPicker = rememberLauncherForActivityResult(
393+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
394+ ) { uris -> stageUris(uris) }
395+
396+ val filePicker = rememberLauncherForActivityResult(
397+ ActivityResultContracts.GetMultipleContents(),
398+ ) { uris -> stageUris(uris) }
399+
400+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
401+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
402+ val cameraLauncher = rememberLauncherForActivityResult(
403+ ActivityResultContracts.TakePicture(),
404+ ) { success ->
405+ val uri = pendingCaptureUri
406+ pendingCaptureUri = null
407+ if (success && uri != null) stageUris(listOf(uri))
408+ }
409+
410+ val voiceLauncher = rememberLauncherForActivityResult(
411+ ActivityResultContracts.StartActivityForResult(),
412+ ) { result ->
413+ if (result.resultCode == Activity.RESULT_OK) {
414+ val spoken = result.data
415+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
416+ ?.firstOrNull()
417+ ?.takeIf { it.isNotBlank() }
418+ if (spoken != null) {
419+ // Append to the existing draft rather than replacing, so dictation adds to
420+ // whatever the user already typed.
421+ val current = vm.draft.value
422+ val combined = if (current.isBlank()) spoken else "$current $spoken"
423+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
424+ }
425+ }
426+ }
427+
428+ fun launchCamera() {
429+ val uri = newCameraCaptureUri(appContext)
430+ if (uri == null) {
431+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
432+ return
433+ }
434+ pendingCaptureUri = uri
435+ runCatching { cameraLauncher.launch(uri) }
436+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
437+ }
438+
439+ fun launchVoice() {
440+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
441+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
442+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
443+ }
444+ runCatching { voiceLauncher.launch(intent) }
445+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
446+ }
447+
448+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
449+ LaunchedEffect(Unit) {
450+ vm.shareLinkEvents.collect { url ->
451+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
452+ snackbar.showSnackbar(linkCopiedMsg)
453+ }
454+ }
455+
456+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
457+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
458+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
459+ // a dropped branch-navigation event in the gap.
460+ val branchedMsg = stringResource(R.string.branch_created)
461+ LaunchedEffect(Unit) {
462+ vm.branchEvents.collect { newId ->
463+ showToast(shareContext, branchedMsg)
464+ onOpenSession?.invoke(newId)
465+ }
466+ }
467+
468+ // Stage images shared into the app (via the system share sheet) as attachments.
469+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
470+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
471+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
472+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
473+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
474+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
475+ LaunchedEffect(pendingSharedMedia) {
476+ val shared = container.consumePendingSharedMedia()
477+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
478+ }
479+
480+ fun doSend() {
481+ if (vm.send(draft)) {
482+ // TextHandleMove (a light tick) is semantically right for a send commit;
483+ // LongPress is reserved for long-press/swipe gestures.
484+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
485+ }
486+ }
487+
488+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
489+
490+ Scaffold(
491+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
492+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
493+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
494+ // typing (and the composer's own Enter-to-send handling) is untouched.
495+ modifier = Modifier.onPreviewKeyEvent { ev ->
496+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
497+ when {
498+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
499+ // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
500+ // the field so the user can type immediately.
501+ ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
502+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
503+ ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
504+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
505+ showStopConfirm = true; true
506+ }
507+ else -> false
508+ }
509+ },
510+ topBar = {
511+ TopAppBar(
512+ title = {
513+ val changeLabel = stringResource(R.string.change_model_agent)
514+ // The subtitle reads "model · agent", so tapping the title offers *both*
515+ // — a small menu picks which picker to open. Previously the tap went
516+ // straight to the model picker, leaving the agent changeable only via
517+ // the overflow menu despite the title implying otherwise.
518+ Box {
519+ Row(
520+ // mergeDescendants so TalkBack reads the title/subtitle Texts as one
521+ // node; the click label rides on `clickable` (onClickLabel) instead of
522+ // an explicit contentDescription, which would have SUPPRESSED the child
523+ // Texts and announced only "Change model and agent".
524+ modifier = Modifier
525+ .clickable(
526+ role = Role.Button,
527+ onClickLabel = changeLabel,
528+ ) { showTitleMenu = true }
529+ .semantics(mergeDescendants = true) {},
530+ verticalAlignment = Alignment.CenterVertically,
531+ ) {
532+ Column(modifier = Modifier.weight(1f, fill = false)) {
533+ // maxLines=1 + Ellipsis so a long session title can't wrap and
534+ // push the top bar to multiple lines, shifting the whole layout.
535+ Text(
536+ sessionTitle ?: sessionLabel,
537+ maxLines = 1,
538+ overflow = TextOverflow.Ellipsis,
539+ )
540+ Text(
541+ subtitle,
542+ style = MaterialTheme.typography.labelSmall,
543+ color = MaterialTheme.colorScheme.onSurfaceVariant,
544+ maxLines = 1,
545+ overflow = TextOverflow.Ellipsis,
546+ )
547+ }
548+ // Always show the affordance so the title reads as tappable even when
549+ // the model catalog failed to load (models empty). Without it the title
550+ // is indistinguishable from plain text and the pickers are effectively
551+ // undiscoverable — and the dropdown items already disable themselves
552+ // while a catalog is loading or unavailable.
553+ Icon(
554+ Icons.Filled.KeyboardArrowDown,
555+ contentDescription = null,
556+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
557+ modifier = Modifier.size(20.dp),
558+ )
559+ }
560+ DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
561+ DropdownMenuItem(
562+ text = { Text(stringResource(R.string.palette_switch_model)) },
563+ enabled = !modelsLoading || models.isNotEmpty(),
564+ onClick = { showTitleMenu = false; showModelPicker = true },
565+ )
566+ DropdownMenuItem(
567+ text = { Text(stringResource(R.string.palette_choose_agent)) },
568+ enabled = !agentsLoading || agents.isNotEmpty(),
569+ onClick = { showTitleMenu = false; showAgentPicker = true },
570+ )
571+ }
572+ }
573+ },
574+ navigationIcon = {
575+ IconButton(onClick = {
576+ if (running) showExitConfirm = true else onBack()
577+ }) {
578+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
579+ }
580+ },
581+ actions = {
582+ // At-a-glance run status in the top bar. When the user is scrolled
583+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
584+ // trailing "working…" row are off-screen, so a top-bar spinner is the
585+ // only signal the agent is still working.
586+ if (running) {
587+ val workingLabel = stringResource(R.string.working)
588+ CircularProgressIndicator(
589+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
590+ strokeWidth = 2.dp,
591+ )
592+ }
593+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
594+ // from REST. A recovery path when the stream silently drops and the
595+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
596+ // immediate tap feedback — the SSE reconnect may not visibly change
597+ // the connection state when already Connected, so without it the tap
598+ // appears to do nothing.
599+ val refreshLabel = stringResource(R.string.refresh)
600+ IconButton(
601+ onClick = { vm.refreshMessages() },
602+ enabled = activeConnection != null && !refreshing,
603+ ) {
604+ if (refreshing) {
605+ CircularProgressIndicator(
606+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
607+ strokeWidth = 2.dp,
608+ )
609+ } else {
610+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
611+ }
612+ }
613+ // Overflow menu consolidates the less-frequent actions (share,
614+ // commands, agent, model, rename, delete) so the top bar stays
615+ // scannable on narrow phones — previously 5 icons crowded the bar
616+ // alongside the back button and tappable title. Catalog-loading
617+ // spinners stay inline (next to the overflow) so a load state is
618+ // visible without opening the menu.
619+ val moreLabel = stringResource(R.string.more)
620+ val loadingLabel = stringResource(R.string.loading)
621+ val shareLabel = stringResource(R.string.share_conversation)
622+ val commandsLabel = stringResource(R.string.commands)
623+ val renameLabel = stringResource(R.string.rename_session_chat)
624+ val deleteLabel = stringResource(R.string.delete_session_chat)
625+ val createShareLabel = stringResource(R.string.create_share_link)
626+ val copyShareLabel = stringResource(R.string.copy_share_link)
627+ val stopShareLabel = stringResource(R.string.stop_sharing)
628+ val summarizeLabel = stringResource(R.string.summarize_conversation)
629+ val initLabel = stringResource(R.string.generate_agents_md)
630+ val shellLabel = stringResource(R.string.run_shell_command)
631+ Box {
632+ IconButton(onClick = { showOverflowMenu = true }) {
633+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
634+ }
635+ DropdownMenu(
636+ expanded = showOverflowMenu,
637+ onDismissRequest = { showOverflowMenu = false },
638+ ) {
639+ DropdownMenuItem(
640+ text = { Text(shareLabel) },
641+ enabled = hasMessages,
642+ onClick = {
643+ showOverflowMenu = false
644+ scope.launch {
645+ val md = withContext(Dispatchers.Default) {
646+ buildConversationMarkdown(vm.messages.value, sessionTitle)
647+ }
648+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
649+ type = "text/markdown"
650+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
651+ putExtra(android.content.Intent.EXTRA_TEXT, md)
652+ }
653+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
654+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
655+ }
656+ },
657+ )
658+ DropdownMenuItem(
659+ text = { Text(commandsLabel) },
660+ enabled = !commandsLoading || commands.isNotEmpty(),
661+ onClick = { showOverflowMenu = false; showCommandPicker = true },
662+ )
663+ DropdownMenuItem(
664+ text = { Text(stringResource(R.string.keyboard_shortcuts)) },
665+ onClick = { showOverflowMenu = false; showShortcutsDialog = true },
666+ )
667+ DropdownMenuItem(
668+ text = { Text(stringResource(R.string.find_in_conversation)) },
669+ onClick = {
670+ showOverflowMenu = false
671+ searchActive = true
672+ runCatching { inputFocusRequester.requestFocus() }
673+ },
674+ )
675+ androidx.compose.material3.HorizontalDivider()
676+ // Session sharing: create a public link, copy an existing one, or revoke it.
677+ if (shareUrl == null) {
678+ DropdownMenuItem(
679+ text = { Text(createShareLabel) },
680+ enabled = hasMessages,
681+ onClick = { showOverflowMenu = false; vm.shareSession() },
682+ )
683+ } else {
684+ DropdownMenuItem(
685+ text = { Text(copyShareLabel) },
686+ onClick = {
687+ showOverflowMenu = false
688+ shareUrl?.let {
689+ copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
690+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
691+ }
692+ },
693+ )
694+ DropdownMenuItem(
695+ text = { Text(stopShareLabel) },
696+ onClick = { showOverflowMenu = false; vm.unshareSession() },
697+ )
698+ }
699+ DropdownMenuItem(
700+ text = { Text(summarizeLabel) },
701+ enabled = hasMessages && !running,
702+ onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
703+ )
704+ DropdownMenuItem(
705+ text = { Text(initLabel) },
706+ enabled = !running,
707+ onClick = { showOverflowMenu = false; showInitConfirm = true },
708+ )
709+ DropdownMenuItem(
710+ text = { Text(shellLabel) },
711+ enabled = !running,
712+ onClick = { showOverflowMenu = false; showShellDialog = true },
713+ )
714+ androidx.compose.material3.HorizontalDivider()
715+ DropdownMenuItem(
716+ text = { Text(renameLabel) },
717+ onClick = { showOverflowMenu = false; showRenameDialog = true },
718+ )
719+ DropdownMenuItem(
720+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
721+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
722+ )
723+ }
724+ // While a catalog is initially loading (empty list + loading flag),
725+ // show a tiny inline spinner beside the overflow so the user can see
726+ // a load is in progress without opening the menu. Once loaded the
727+ // spinner disappears; the menu items are always enabled (tapping a
728+ // picker with no items shows the "no models/agents/commands" state).
729+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
730+ (agentsLoading && agents.isEmpty()) ||
731+ (modelsLoading && models.isEmpty())
732+ if (catalogLoading) {
733+ CircularProgressIndicator(
734+ Modifier
735+ .align(Alignment.TopEnd)
736+ .size(10.dp)
737+ .semantics { contentDescription = loadingLabel },
738+ strokeWidth = 1.dp,
739+ )
740+ }
741+ }
742+ },
743+ )
744+ },
745+ snackbarHost = { SnackbarHost(snackbar) },
746+ bottomBar = {
747+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
748+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
749+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
750+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
751+ Column {
752+ // Pinned above the composer so the agent's plan and progress stay visible
753+ // while scrolled up mid-run; renders nothing when there's no plan.
754+ TodoPlanBar(todoPlan)
755+ val bannerMotion = rememberVisibilityTransitions()
756+ AnimatedVisibility(
757+ visible = reverted,
758+ enter = bannerMotion.enter,
759+ exit = bannerMotion.exit,
760+ ) {
761+ RevertBanner(onUndo = { vm.unrevert() })
762+ }
763+ AnimatedVisibility(
764+ visible = queuedOffline.isNotEmpty(),
765+ enter = bannerMotion.enter,
766+ exit = bannerMotion.exit,
767+ ) {
768+ OutboxBanner(
769+ count = queuedOffline.size,
770+ sending = outboxSending,
771+ onFlush = { vm.flushQueued() },
772+ onDiscard = { vm.discardAllQueued() },
773+ )
774+ }
775+ ChatInputBar(
776+ value = draft,
777+ onValueChange = vm::updateDraft,
778+ running = running,
779+ aborting = aborting,
780+ enabled = activeConnection != null,
781+ sendOnEnter = sendOnEnter,
782+ onSend = ::doSend,
783+ onAbort = { showStopConfirm = true },
784+ queuedFollowUp = queuedFollowUp,
785+ onQueueFollowUp = vm::queueFollowUp,
786+ onCancelQueue = { vm.queueFollowUp("") },
787+ focusRequester = inputFocusRequester,
788+ attachments = attachments,
789+ staging = stagingCount > 0,
790+ onRemoveAttachment = vm::removeAttachment,
791+ onPickPhoto = {
792+ photoPicker.launch(
793+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
794+ )
795+ },
796+ onPickFile = { filePicker.launch("*/*") },
797+ onCamera = { launchCamera() },
798+ onVoice = { launchVoice() },
799+ onPasteImage = { stageUris(it) },
800+ )
801+ }
802+ },
803+ ) { padding ->
804+ // Collect messages inside the content lambda so streaming token updates
805+ // recompose only this subtree, not the top bar / input bar / 20+ other
806+ // state reads in the ChatScreen body.
807+ val messages by vm.messages.collectAsStateWithLifecycle()
808+ val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
809+ val listState = rememberLazyListState()
810+ val contentScope = rememberCoroutineScope()
811+ val timeTick = rememberRelativeTimeTick()
812+ // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
813+ // chat affordance for reading while the IME is open. Watching isScrollInProgress via
814+ // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
815+ val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
816+ androidx.compose.runtime.LaunchedEffect(listState) {
817+ androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
818+ .distinctUntilChanged()
819+ .collect { scrolling -> if (scrolling) keyboardController?.hide() }
820+ } // Group messages by day and interleave date separators so a long conversation
821+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
822+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
823+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
824+ // the same list the LazyColumn renders (separators shift the indices vs. the
825+ // raw messages list, so scroll targets must be in listItems space).
826+ val todayLabel = stringResource(R.string.today)
827+ val yesterdayLabel = stringResource(R.string.yesterday)
828+ // In-conversation search: when active, narrow to messages whose text contains the query.
829+ // Computed on the filtered set so day separators still align with the visible messages.
830+ val searchQuery = chatSearch.trim()
831+ val searchMessages = remember(messages, searchQuery) {
832+ if (searchQuery.isEmpty()) messages
833+ else messages.filter { m ->
834+ m.parts.any { p -> (p as? TextPart)?.text?.contains(searchQuery, ignoreCase = true) == true }
835+ }
836+ }
837+ // Keep the focused-match index in range as the query (and thus the match set) changes.
838+ // A new query resets to the first match; a shrunk set clamps to the last valid index.
839+ LaunchedEffect(searchQuery, searchMessages.size) {
840+ if (searchPos >= searchMessages.size) searchPos = 0
841+ }
842+ val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
843+ buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
844+ }
845+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
846+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
847+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
848+ // would capture the first composition's list — which is empty, since `messages`
849+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
850+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
851+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
852+ // whose value tracks the latest list.
853+ val currentListItems by rememberUpdatedState(listItems)
854+
855+ // New-content signal for the jump-to-latest FAB: counts how many new items arrived
856+ // while the user was scrolled away from the bottom, cleared once they return. A count
857+ // (vs. a bare dot) tells the user how much they missed at a glance.
858+ var newContentCount by remember { mutableIntStateOf(0) }
859+
860+ val isPinnedToBottom by remember {
861+ derivedStateOf {
862+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
863+ // When a run is active, the LazyColumn has one trailing "__typing"
864+ // item after the last list item. Account for it so "pinned to bottom"
865+ // includes the working indicator — otherwise the pin check targets
866+ // listItems.lastIndex, the typing row sits just below the viewport,
867+ // and the user never sees the progress indicator even when pinned.
868+ val items = currentListItems
869+ val effectiveLast = if (running) items.size else items.lastIndex
870+ lastVisible >= effectiveLast || items.isEmpty()
871+ }
872+ }
873+
874+ // Jump to the newest message once, when the conversation first loads. Guarded by a
875+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
876+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
877+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
878+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
879+ LaunchedEffect(listItems.isNotEmpty()) {
880+ if (listItems.isNotEmpty() && !didInitialScroll) {
881+ // When a run is active the LazyColumn has a trailing "__typing" row at
882+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
883+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
884+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
885+ didInitialScroll = true
886+ }
887+ }
888+
889+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
890+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
891+ // isPinnedToBottom check flips to false the instant you send — freezing
892+ // auto-scroll. If the user was pinned to the last item just before the run
893+ // began, bring the typing row into view so the pin (and streaming follow) is
894+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
895+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
896+ LaunchedEffect(running) {
897+ if (running && listItems.isNotEmpty()) {
898+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
899+ if (lastVisible >= listItems.lastIndex) {
900+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
901+ }
902+ }
903+ }
904+
905+ // Scroll the focused search match into view whenever the user steps through results with
906+ // the up/down arrows. Resolves the filtered message to its slot in listItems (which
907+ // includes date separators) and animates there.
908+ LaunchedEffect(searchPos, searchQuery, listItems) {
909+ if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
910+ val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
911+ val index = listItems.indexOfFirst {
912+ it is MessageListItem.Message && it.message.info.id == target.info.id
913+ }
914+ if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
915+ }
916+
917+ LaunchedEffect(Unit) {
918+ var prevSize = 0
919+ var prevLen = 0
920+ snapshotFlow {
921+ // Track list size + the streaming length of the last part so we auto-scroll
922+ // as content arrives, plus the pinned flag. A small data class with primitive
923+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
924+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
925+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
926+ // and tool output — not just TextPart — keeps a pinned view following a long
927+ // reasoning/tool block while it streams (previously it stalled at 0).
928+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
929+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
930+ }.collect { signal ->
931+ if (signal.pinned) {
932+ // Back at the bottom: clear the new-content badge.
933+ newContentCount = 0
934+ if (signal.size > 0) {
935+ // Scroll to the effective last index, including the trailing
936+ // "__typing" row when a run is active so the working indicator
937+ // is brought into view (not just the last message).
938+ val items = currentListItems
939+ val target = if (running) items.size else items.lastIndex
940+ listState.scrollToItem(target)
941+ }
942+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
943+ // Content arrived while scrolled up — increment the jump-to-latest badge.
944+ // Only count whole new items (not per-token growth) so the number reflects
945+ // new messages, not a token count.
946+ if (signal.size > prevSize) newContentCount += signal.size - prevSize
947+ else if (newContentCount == 0) newContentCount = 1
948+ }
949+ prevSize = signal.size
950+ prevLen = signal.lastTextLength
951+ }
952+ }
953+
954+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
955+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
956+ // content padding accounts for the bottomBar's raised height, so the message
957+ // list is already above the keyboard. Adding imePadding here would double-apply
958+ // the IME inset and push messages too far up.
959+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
960+ if (activeConnection == null) {
961+ Column(
962+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
963+ horizontalAlignment = Alignment.CenterHorizontally,
964+ ) {
965+ Text(
966+ stringResource(R.string.not_connected),
967+ color = MaterialTheme.colorScheme.error,
968+ )
969+ Spacer(Modifier.size(12.dp))
970+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
971+ if (reconnecting) {
972+ CircularProgressIndicator(
973+ Modifier.size(20.dp),
974+ color = MaterialTheme.colorScheme.onPrimary,
975+ strokeWidth = 2.dp,
976+ )
977+ } else {
978+ Text(stringResource(R.string.reconnect))
979+ }
980+ }
981+ }
982+ } else {
983+ val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
984+ // Measure the banner's actual height instead of hardcoding 44dp. At large
985+ // accessibility font scales the banner's labelMedium text + spinner + Retry
986+ // button exceed 44dp, so a fixed inset lets the first message hide behind it
987+ // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
988+ // fires while the banner is composed (visible), so gate the inset on
989+ // bannerVisible and fall back to 44dp until the first measurement arrives.
990+ var bannerHeightPx by remember { mutableIntStateOf(0) }
991+ val density = LocalDensity.current
992+ val topPad = if (bannerVisible) {
993+ if (bannerHeightPx > 0) {
994+ with(density) { bannerHeightPx.toDp() } + 4.dp
995+ } else {
996+ 44.dp
997+ }
998+ } else {
999+ 16.dp
1000+ }
1001+ ConnectionBanner(
1002+ state = connectionState,
1003+ modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1004+ isOnline = isOnline,
1005+ // On a hard failure, retry by forcing an SSE reconnect (which
1006+ // re-seeds from REST). refreshMessages is the right recovery path
1007+ // when the connection is present but the stream died; reconnect()
1008+ // is the path when the whole connection is gone (handled by the
1009+ // separate "Not connected" state below).
1010+ onRetry = { vm.refreshMessages() },
1011+ )
1012+ // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1013+ // recovery is a swipe away everywhere — not just when the message list is
1014+ // populated. Previously PTR was only around the populated list, leaving the
1015+ // error/loading states reachable only via a button tap.
1016+ PullToRefreshBox(
1017+ isRefreshing = refreshing,
1018+ onRefresh = { vm.refreshMessages() },
1019+ // Cap width and center on large screens for readability — full-width
1020+ // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1021+ modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1022+ .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1023+ ) {
1024+ // Reserve top space when the banner is visible so it doesn't overlap the
1025+ // first message / state content. (topPad computed above.)
1026+ if (loading && messages.isEmpty()) {
1027+ val loadingLabel = stringResource(R.string.loading)
1028+ // Skeleton bubbles pre-structure the layout so the perceived load is faster
1029+ // than a bare centered spinner and the first real messages pop into an
1030+ // already-shaped list instead of a blank-then-pop. Alpha pulses (gated by
1031+ // reduced-motion) to convey ongoing work; the column carries the a11y label.
1032+ val reducedMotion = LocalReducedMotion.current
1033+ val transition = rememberInfiniteTransition(label = "skeleton")
1034+ val pulse by transition.animateFloat(
1035+ initialValue = 0.35f,
1036+ targetValue = 0.7f,
1037+ animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
1038+ label = "skeletonAlpha",
1039+ )
1040+ val skeletonAlpha = if (reducedMotion) 0.5f else pulse
1041+ val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
1042+ @Composable
1043+ fun bar(widthFraction: Float) {
1044+ Box(
1045+ Modifier
1046+ .fillMaxWidth(widthFraction)
1047+ .height(14.dp)
1048+ .clip(RoundedCornerShape(4.dp))
1049+ .background(skeletonColor)
1050+ .alpha(skeletonAlpha),
1051+ )
1052+ }
1053+ Column(
1054+ modifier = Modifier
1055+ .align(Alignment.TopCenter)
1056+ .padding(top = topPad)
1057+ .padding(16.dp)
1058+ .fillMaxWidth()
1059+ .semantics { contentDescription = loadingLabel },
1060+ verticalArrangement = Arrangement.spacedBy(14.dp),
1061+ ) {
1062+ repeat(4) { i ->
1063+ val left = i % 2 == 0
1064+ Row(
1065+ modifier = Modifier.fillMaxWidth(),
1066+ horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
1067+ ) {
1068+ Column(
1069+ modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
1070+ verticalArrangement = Arrangement.spacedBy(6.dp),
1071+ ) {
1072+ bar(1f)
1073+ bar(0.8f)
1074+ }
1075+ }
1076+ }
1077+ }
1078+ } else if (loadError && messages.isEmpty()) {
1079+ // A failed load with nothing to show. Distinct from the empty
1080+ // conversation state below — the conversation isn't empty, it
1081+ // failed to load, and offering "Start a conversation" here is
1082+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
1083+ Column(
1084+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1085+ horizontalAlignment = Alignment.CenterHorizontally,
1086+ ) {
1087+ Text(
1088+ stringResource(R.string.load_messages_failed),
1089+ color = MaterialTheme.colorScheme.error,
1090+ )
1091+ Spacer(Modifier.size(12.dp))
1092+ Button(onClick = { vm.refreshMessages() }) {
1093+ Text(stringResource(R.string.retry))
1094+ }
1095+ }
1096+ } else if (messages.isEmpty() && running) {
1097+ // A run just started but no parts have arrived yet — the empty
1098+ // list with only the trailing "working…" row looks broken, so
1099+ // surface a clear starting state until the first part streams in.
1100+ val workingText = stringResource(R.string.working)
1101+ Column(
1102+ modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1103+ horizontalAlignment = Alignment.CenterHorizontally,
1104+ ) {
1105+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
1106+ Spacer(Modifier.size(12.dp))
1107+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
1108+ }
1109+ } else if (messages.isEmpty()) {
1110+ EmptyConversation(
1111+ onSuggestion = {
1112+ vm.updateDraft(it)
1113+ // Focus the input so the user can edit the suggestion before
1114+ // sending, instead of having to manually tap the field.
1115+ runCatching { inputFocusRequester.requestFocus() }
1116+ },
1117+ modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1118+ )
1119+ } else {
1120+ val lastMessageId = messages.lastOrNull()?.info?.id
1121+ // Text-to-speech for reading assistant replies aloud; shuts down when the
1122+ // message list leaves composition.
1123+ val tts = rememberTtsController()
1124+ val speakingMessageId by tts.speakingId
1125+ LazyColumn(
1126+ state = listState,
1127+ modifier = Modifier.fillMaxSize(),
1128+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
1129+ // never floats over the last message. Top padding grows when the
1130+ // connection banner is visible so it doesn't overlap the first message.
1131+ contentPadding = PaddingValues(
1132+ start = 16.dp,
1133+ top = topPad,
1134+ end = 16.dp,
1135+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1136+ ),
1137+ verticalArrangement = Arrangement.spacedBy(16.dp),
1138+ ) {
1139+ items(
1140+ items = listItems,
1141+ key = { it.key },
1142+ contentType = { it.contentType },
1143+ ) { item ->
1144+ // When in-conversation search is stepping through matches, highlight the
1145+ // focused one's row so the user can spot it at a glance among the filtered
1146+ // results (full in-text term highlighting would require threading the query
1147+ // through the markdown renderer; the row highlight + scroll-to-match covers
1148+ // the navigation use case desktop chat apps solve with next/prev).
1149+ val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1150+ searchMessages.getOrNull(searchPos)?.info?.id
1151+ } else null
1152+ val isFocusedMatch = focusedMatchId != null &&
1153+ item is MessageListItem.Message &&
1154+ item.message.info.id == focusedMatchId
1155+ // Default placement animation so inserted/moved rows glide in. Skipped
1156+ // entirely under reduced motion so a streaming message growing in place
1157+ // doesn't animate on every token (and respects the a11y preference).
1158+ Box(
1159+ Modifier
1160+ .then(if (LocalReducedMotion.current) Modifier else Modifier.animateItem())
1161+ .then(
1162+ if (isFocusedMatch) {
1163+ Modifier.background(
1164+ MaterialTheme.colorScheme.secondaryContainer,
1165+ MaterialTheme.shapes.medium,
1166+ )
1167+ } else {
1168+ Modifier
1169+ },
1170+ ),
1171+ ) {
1172+ when (item) {
1173+ is MessageListItem.Separator -> DateSeparator(item.label)
1174+ is MessageListItem.Message -> {
1175+ val message = item.message
1176+ // Only the last (streaming) message needs isRunning — it drives the
1177+ // reasoning-block spinner. Passing the live flag to every bubble
1178+ // makes all visible messages recompose whenever a run starts or stops.
1179+ val modelLabel = remember(message.info, models) {
1180+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1181+ ?.let { resolveModelLabel(it, models) }
1182+ }
1183+ // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1184+ // image/code-only messages, which then opt out of the swipe gesture.
1185+ val quoteText = remember(message.parts) {
1186+ message.parts
1187+ .filterIsInstance<TextPart>()
1188+ .joinToString("\n\n") { it.text }
1189+ .trim()
1190+ .takeIf { it.isNotEmpty() }
1191+ }
1192+ // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1193+ // snapping back (the message isn't dismissed — the quote fills the composer).
1194+ // Only enabled when there's text to quote, so non-text messages don't
1195+ // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1196+ val swipeState = rememberSwipeToDismissBoxState(
1197+ confirmValueChange = { value ->
1198+ if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1199+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1200+ vm.quoteReply(quoteText)
1201+ runCatching { inputFocusRequester.requestFocus() }
1202+ }
1203+ false
1204+ },
1205+ )
1206+ SwipeToDismissBox(
1207+ state = swipeState,
1208+ enableDismissFromEndToStart = false,
1209+ enableDismissFromStartToEnd = quoteText != null,
1210+ backgroundContent = {
1211+ Box(
1212+ Modifier.fillMaxSize().padding(horizontal = 16.dp),
1213+ contentAlignment = Alignment.CenterStart,
1214+ ) {
1215+ Icon(
1216+ Icons.AutoMirrored.Filled.Reply,
1217+ contentDescription = null,
1218+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1219+ )
1220+ }
1221+ },
1222+ ) {
1223+ MessageBubble(
1224+ message,
1225+ isRunning = running && message.info.id == lastMessageId,
1226+ imageContext = imageContext,
1227+ modelLabel = modelLabel,
1228+ onOpenFile = onOpenFile,
1229+ onRevert = { vm.revertTo(message.info.id) },
1230+ onEdit = { text ->
1231+ // editMessage reverts to before this message (hiding it and
1232+ // everything after); the revert banner surfaces the rewind
1233+ // with an Undo. Focus + scroll the composer into view like the
1234+ // Quote action so the prefilled draft isn't off-screen.
1235+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1236+ vm.editMessage(message.info.id, text)
1237+ runCatching { inputFocusRequester.requestFocus() }
1238+ contentScope.launch {
1239+ runCatchingCancellable {
1240+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1241+ }
1242+ }
1243+ },
1244+ onSpeak = { text ->
1245+ if (!tts.toggle(message.info.id, text)) {
1246+ // TTS engine unavailable (init failed / not yet ready
1247+ // / blank text): surface feedback so the button doesn't
1248+ // appear dead. Throttled so a rapid double-tap (stop
1249+ // then immediate re-tap before ready) doesn't spam.
1250+ scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1251+ }
1252+ },
1253+ isSpeaking = message.info.id == speakingMessageId,
1254+ onQuote = { text ->
1255+ vm.quoteReply(text)
1256+ runCatching { inputFocusRequester.requestFocus() }
1257+ },
1258+ onBranch = { text -> vm.branchFrom(text) },
1259+ // Regenerate is only meaningful for a finished assistant reply
1260+ // (not the actively-streaming one), so gate it on !running.
1261+ onRegenerate = if (!running) {
1262+ { vm.regenerate(message.info.id) }
1263+ } else null,
1264+ sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1265+ if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1266+ else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1267+ },
1268+ isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1269+ onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1270+ if (failed) {
1271+ { vm.retryOptimisticMessage(message.info.id) }
1272+ } else {
1273+ null
1274+ }
1275+ },
1276+ onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1277+ if (failed) {
1278+ { vm.dismissOptimistic(message.info.id) }
1279+ } else {
1280+ null
1281+ }
1282+ },
1283+ )
1284+ }
1285+ }
1286+ }
1287+ }
1288+ }
1289+ if (running) {
1290+ item(key = "__typing") {
1291+ val workingText = stringResource(R.string.working)
1292+ // Elapsed-since-run chip: the typing row only composes while a run is
1293+ // active, so anchoring the timer to first composition approximates the
1294+ // run start and gives the user a sense of how long the agent has been
1295+ // working — distinguishing a healthy long run from a hung one. Updates
1296+ // once per second; the value is decorative (the a11y label is the row's).
1297+ var startMs by remember { mutableLongStateOf(0L) }
1298+ LaunchedEffect(Unit) { startMs = System.currentTimeMillis() }
1299+ val elapsedMs by produceState(0L, startMs) {
1300+ if (startMs == 0L) return@produceState
1301+ while (true) {
1302+ value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1303+ delay(1000)
1304+ }
1305+ }
1306+ val elapsedText = remember(elapsedMs) {
1307+ val total = elapsedMs / 1000
1308+ // Locale.US for stable digit formatting: on locales with
1309+ // non-ASCII digits (ar-/fa-) the default locale would render
1310+ // localized digits inside the Monospace block, breaking the
1311+ // fixed-width alignment the monospace family was chosen for.
1312+ String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1313+ }
1314+ Row(
1315+ verticalAlignment = Alignment.CenterVertically,
1316+ // Animate this slot in/out so the working row doesn't pop in and
1317+ // jolt the message list when a run starts/stops — matching the
1318+ // AnimatedVisibility used by every other transient banner/FAB here.
1319+ modifier = Modifier
1320+ .animateItem()
1321+ .padding(vertical = 4.dp),
1322+ ) {
1323+ // Merge the indicator + label + clock into one TalkBack node so
1324+ // it's announced once (the working label, then the elapsed time)
1325+ // instead of "working… / working… / 0:14" with the label read
1326+ // twice. The Stop IconButton below stays separately focusable.
1327+ Row(
1328+ verticalAlignment = Alignment.CenterVertically,
1329+ modifier = Modifier.semantics(mergeDescendants = true) {
1330+ contentDescription = "$workingText $elapsedText"
1331+ },
1332+ ) {
1333+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1334+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1335+ Spacer(Modifier.size(8.dp))
1336+ Icon(
1337+ Icons.Filled.Schedule,
1338+ contentDescription = null,
1339+ modifier = Modifier.size(14.dp),
1340+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1341+ )
1342+ Text(
1343+ elapsedText,
1344+ style = MaterialTheme.typography.labelMedium,
1345+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1346+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1347+ modifier = Modifier.padding(start = 4.dp),
1348+ )
1349+ }
1350+ // A trailing Stop on the working row so the run can be aborted
1351+ // without scrolling back to the composer (which may be off-screen
1352+ // while the user reads the streaming output up-thread).
1353+ Spacer(Modifier.weight(1f))
1354+ val stopLabel = stringResource(R.string.stop)
1355+ IconButton(
1356+ onClick = { showStopConfirm = true },
1357+ modifier = Modifier.semantics { contentDescription = stopLabel },
1358+ ) {
1359+ Icon(Icons.Filled.Stop, contentDescription = null)
1360+ }
1361+ }
1362+ }
1363+ }
1364+ }
1365+ }
1366+ }
1367+ // Jump-to-latest affordance when the user has scrolled away during a stream.
1368+ val fabMotion = rememberVisibilityTransitions()
1369+ AnimatedVisibility(
1370+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
1371+ enter = fabMotion.enter,
1372+ exit = fabMotion.exit,
1373+ modifier = Modifier.align(Alignment.BottomEnd),
1374+ ) {
1375+ // Badge the FAB when new content arrived while the user was scrolled up, so
1376+ // they know there's something new to jump to (cleared once back at bottom).
1377+ BadgedBox(
1378+ badge = {
1379+ if (newContentCount > 0) {
1380+ val newContentLabel = stringResource(R.string.new_messages)
1381+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel }) {
1382+ Text(if (newContentCount > 99) "99+" else newContentCount.toString())
1383+ }
1384+ }
1385+ },
1386+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1387+ ) {
1388+ ExtendedFloatingActionButton(
1389+ onClick = {
1390+ newContentCount = 0
1391+ if (listItems.isNotEmpty()) {
1392+ // Scroll to the effective last index, including the
1393+ // trailing "__typing" row when a run is active.
1394+ val target = if (running) listItems.size else listItems.lastIndex
1395+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1396+ }
1397+ },
1398+ // contentDescription null: the visible "Latest" text already labels
1399+ // the FAB, so a description here makes TalkBack announce "Latest" twice.
1400+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1401+ text = { Text(stringResource(R.string.latest)) },
1402+ )
1403+ }
1404+ }
1405+ // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1406+ // user has scrolled down past the first few messages. Symmetric to the
1407+ // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1408+ val scrolledDown by remember {
1409+ derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1410+ }
1411+ AnimatedVisibility(
1412+ visible = scrolledDown && listItems.size > 4,
1413+ enter = fabMotion.enter,
1414+ exit = fabMotion.exit,
1415+ modifier = Modifier.align(Alignment.BottomStart),
1416+ ) {
1417+ SmallFloatingActionButton(
1418+ onClick = {
1419+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1420+ },
1421+ modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1422+ ) {
1423+ Icon(
1424+ Icons.Filled.KeyboardArrowUp,
1425+ contentDescription = stringResource(R.string.scroll_to_top),
1426+ )
1427+ }
1428+ }
1429+ // In-conversation search bar. Overlays the list so typing filters messages in
1430+ // place; the match count + a no-matches note give immediate feedback.
1431+ val searchMotion = rememberVisibilityTransitions()
1432+ AnimatedVisibility(
1433+ visible = searchActive,
1434+ enter = searchMotion.enter,
1435+ exit = searchMotion.exit,
1436+ modifier = Modifier.align(Alignment.TopCenter),
1437+ ) {
1438+ Surface(
1439+ tonalElevation = 3.dp,
1440+ modifier = Modifier
1441+ .padding(horizontal = 12.dp, vertical = 4.dp)
1442+ .fillMaxWidth(),
1443+ ) {
1444+ Row(
1445+ modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1446+ verticalAlignment = Alignment.CenterVertically,
1447+ ) {
1448+ OutlinedTextField(
1449+ value = chatSearch,
1450+ onValueChange = { chatSearch = it },
1451+ modifier = Modifier.weight(1f),
1452+ placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1453+ singleLine = true,
1454+ leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1455+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1456+ )
1457+ // Match counter: "N of M" where N is the focused match (1-based) and
1458+ // M is the total matching messages. Only shown when there's a query.
1459+ val matchCount = searchMessages.size
1460+ Text(
1461+ if (searchQuery.isNotEmpty() && matchCount > 0) {
1462+ stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1463+ } else if (searchQuery.isNotEmpty()) {
1464+ stringResource(R.string.search_match_count, 0, messages.size)
1465+ } else "",
1466+ style = MaterialTheme.typography.labelSmall,
1467+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1468+ modifier = Modifier.padding(horizontal = 4.dp),
1469+ )
1470+ // Step through matches (Previous / Next), disabled when there are
1471+ // fewer than two to navigate. Wrap around at the ends so repeated
1472+ // taps cycle through every hit.
1473+ val prevLabel = stringResource(R.string.find_previous)
1474+ val nextLabel = stringResource(R.string.find_next)
1475+ IconButton(
1476+ onClick = {
1477+ if (matchCount > 0) {
1478+ searchPos = (searchPos - 1 + matchCount) % matchCount
1479+ }
1480+ },
1481+ enabled = matchCount > 1,
1482+ ) {
1483+ Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1484+ }
1485+ IconButton(
1486+ onClick = {
1487+ if (matchCount > 0) {
1488+ searchPos = (searchPos + 1) % matchCount
1489+ }
1490+ },
1491+ enabled = matchCount > 1,
1492+ ) {
1493+ Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1494+ }
1495+ IconButton(onClick = {
1496+ searchActive = false
1497+ chatSearch = ""
1498+ }) {
1499+ Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1500+ }
1501+ }
1502+ }
1503+ }
1504+ // When a search yields no matches (but the conversation isn't empty), say so
1505+ // instead of showing a blank list.
1506+ if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1507+ Text(
1508+ stringResource(R.string.search_no_matches),
1509+ style = MaterialTheme.typography.bodyMedium,
1510+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1511+ modifier = Modifier.align(Alignment.Center),
1512+ )
1513+ }
1514+ }
1515+ }
1516+ }
1517+ }
1518+
1519+ if (showExitConfirm) {
1520+ AlertDialog(
1521+ onDismissRequest = { showExitConfirm = false },
1522+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1523+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1524+ confirmButton = {
1525+ TextButton(onClick = {
1526+ showExitConfirm = false
1527+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1528+ vm.abort()
1529+ onBack()
1530+ }) { Text(stringResource(R.string.stop_and_exit)) }
1531+ },
1532+ dismissButton = {
1533+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1534+ },
1535+ )
1536+ }
1537+
1538+ if (showStopConfirm) {
1539+ AlertDialog(
1540+ onDismissRequest = { showStopConfirm = false },
1541+ title = { Text(stringResource(R.string.stop_run_title)) },
1542+ text = { Text(stringResource(R.string.stop_run_text)) },
1543+ confirmButton = {
1544+ TextButton(onClick = {
1545+ showStopConfirm = false
1546+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1547+ vm.abort()
1548+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1549+ },
1550+ dismissButton = {
1551+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1552+ },
1553+ )
1554+ }
1555+
1556+ if (showSummarizeConfirm) {
1557+ AlertDialog(
1558+ onDismissRequest = { showSummarizeConfirm = false },
1559+ title = { Text(stringResource(R.string.summarize_confirm_title)) },
1560+ text = { Text(stringResource(R.string.summarize_confirm_text)) },
1561+ confirmButton = {
1562+ TextButton(onClick = {
1563+ showSummarizeConfirm = false
1564+ vm.summarize()
1565+ }) { Text(stringResource(R.string.action_continue)) }
1566+ },
1567+ dismissButton = {
1568+ TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1569+ },
1570+ )
1571+ }
1572+
1573+ if (showInitConfirm) {
1574+ AlertDialog(
1575+ onDismissRequest = { showInitConfirm = false },
1576+ title = { Text(stringResource(R.string.init_confirm_title)) },
1577+ text = { Text(stringResource(R.string.init_confirm_text)) },
1578+ confirmButton = {
1579+ TextButton(onClick = {
1580+ showInitConfirm = false
1581+ vm.initProject()
1582+ }) { Text(stringResource(R.string.action_continue)) }
1583+ },
1584+ dismissButton = {
1585+ TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1586+ },
1587+ )
1588+ }
1589+
1590+ if (showRenameDialog) {
1591+ RenameSessionChatDialog(
1592+ initialTitle = sessionTitle ?: "",
1593+ onDismiss = { showRenameDialog = false },
1594+ onConfirm = { newName ->
1595+ showRenameDialog = false
1596+ vm.renameSession(newName)
1597+ },
1598+ )
1599+ }
1600+
1601+ if (showDeleteDialog) {
1602+ AlertDialog(
1603+ onDismissRequest = { showDeleteDialog = false },
1604+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1605+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1606+ confirmButton = {
1607+ TextButton(onClick = {
1608+ showDeleteDialog = false
1609+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1610+ vm.deleteSession()
1611+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1612+ },
1613+ dismissButton = {
1614+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1615+ },
1616+ )
1617+ }
1618+
1619+ if (showShellDialog) {
1620+ ShellCommandDialog(
1621+ onDismiss = { showShellDialog = false },
1622+ onRun = { cmd ->
1623+ showShellDialog = false
1624+ vm.runShell(cmd)
1625+ },
1626+ )
1627+ }
1628+
1629+ if (showModelPicker) {
1630+ ModelPickerSheet(
1631+ options = models,
1632+ selected = selectedModel,
1633+ loading = modelsLoading,
1634+ error = modelsError,
1635+ onSelect = { vm.selectModel(it) },
1636+ onRetry = { vm.reloadModels() },
1637+ onDismiss = { showModelPicker = false },
1638+ )
1639+ }
1640+
1641+ if (showAgentPicker) {
1642+ AgentPickerSheet(
1643+ agents = agents,
1644+ selected = selectedAgent,
1645+ loading = agentsLoading,
1646+ error = agentsError,
1647+ onSelect = { vm.selectAgent(it?.name) },
1648+ onRetry = { vm.reloadAgents() },
1649+ onDismiss = { showAgentPicker = false },
1650+ )
1651+ }
1652+
1653+ if (showCommandPicker) {
1654+ CommandPickerSheet(
1655+ commands = commands,
1656+ loading = commandsLoading,
1657+ error = commandsError,
1658+ onSelect = { vm.runCommand(it) },
1659+ onRetry = { vm.reloadCommands() },
1660+ onDismiss = { showCommandPicker = false },
1661+ )
1662+ }
1663+
1664+ pendingPermission?.let { permission ->
1665+ PermissionDialog(
1666+ permission = permission,
1667+ position = permissionProgress.position,
1668+ total = permissionProgress.total,
1669+ onRespond = { response -> vm.respondPermission(permission, response) },
1670+ )
1671+ }
1672+
1673+ if (showPalette) {
1674+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1675+ }
1676+
1677+ if (showShortcutsDialog) {
1678+ // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
1679+ // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
1680+ // depends on the "Send on Enter" setting, noted inline.
1681+ AlertDialog(
1682+ onDismissRequest = { showShortcutsDialog = false },
1683+ title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
1684+ text = {
1685+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
1686+ ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
1687+ ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
1688+ ShortcutRow("Esc", stringResource(R.string.shortcut_close))
1689+ ShortcutRow("Enter", stringResource(R.string.shortcut_send))
1690+ ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
1691+ }
1692+ },
1693+ confirmButton = {
1694+ TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
1695+ },
1696+ )
1697+ }
1698+}
1699+
1700+@Composable
1701+private fun ShortcutRow(keys: String, desc: String) {
1702+ Row(verticalAlignment = Alignment.CenterVertically) {
1703+ Text(
1704+ keys,
1705+ style = MaterialTheme.typography.labelLarge,
1706+ fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1707+ modifier = Modifier.widthIn(min = 160.dp),
1708+ )
1709+ Text(
1710+ desc,
1711+ style = MaterialTheme.typography.bodyMedium,
1712+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1713+ )
1714+ }
1715+}
1716+
1717+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
1718+@Composable
1719+private fun ChatInputBar(
1720+ value: String,
1721+ onValueChange: (String) -> Unit,
1722+ running: Boolean,
1723+ aborting: Boolean,
1724+ enabled: Boolean,
1725+ sendOnEnter: Boolean,
1726+ onSend: () -> Unit,
1727+ onAbort: () -> Unit,
1728+ queuedFollowUp: String?,
1729+ onQueueFollowUp: (String) -> Unit,
1730+ onCancelQueue: () -> Unit,
1731+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1732+ attachments: List<PendingAttachment>,
1733+ staging: Boolean,
1734+ onRemoveAttachment: (String) -> Unit,
1735+ onPickPhoto: () -> Unit,
1736+ onPickFile: () -> Unit,
1737+ onCamera: () -> Unit,
1738+ onVoice: () -> Unit,
1739+ onPasteImage: (List<Uri>) -> Unit,
1740+) {
1741+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1742+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1743+ // Full-screen editor state: opened when the user wants more space for a long prompt.
1744+ var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1745+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1746+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1747+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1748+ // user sees their message will be sent when the run finishes, and can cancel.
1749+ if (queuedFollowUp != null) {
1750+ val editLabel = stringResource(R.string.edit)
1751+ Row(
1752+ modifier = Modifier
1753+ .fillMaxWidth()
1754+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1755+ verticalAlignment = Alignment.CenterVertically,
1756+ ) {
1757+ // Tapping the chip reloads the queued text into the draft (and clears the
1758+ // queue) so a typo spotted while queuing can be fixed without retyping.
1759+ Column(
1760+ modifier = Modifier
1761+ .weight(1f)
1762+ .clip(MaterialTheme.shapes.small)
1763+ .clickable(role = Role.Button, onClickLabel = editLabel) {
1764+ onValueChange(queuedFollowUp)
1765+ onCancelQueue()
1766+ }
1767+ .padding(vertical = 4.dp),
1768+ ) {
1769+ Text(
1770+ stringResource(R.string.queued),
1771+ style = MaterialTheme.typography.labelSmall,
1772+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1773+ )
1774+ Text(
1775+ queuedFollowUp,
1776+ style = MaterialTheme.typography.bodySmall,
1777+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1778+ maxLines = 1,
1779+ overflow = TextOverflow.Ellipsis,
1780+ )
1781+ }
1782+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1783+ Text(stringResource(R.string.cancel))
1784+ }
1785+ }
1786+ }
1787+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1788+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1789+ Row(
1790+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1791+ verticalAlignment = Alignment.Bottom,
1792+ ) {
1793+ // Attach menu: photo picker, camera, or any file.
1794+ var showAttachMenu by remember { mutableStateOf(false) }
1795+ Box {
1796+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1797+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1798+ }
1799+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1800+ DropdownMenuItem(
1801+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1802+ text = { Text(stringResource(R.string.attach_photo)) },
1803+ onClick = { showAttachMenu = false; onPickPhoto() },
1804+ )
1805+ DropdownMenuItem(
1806+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1807+ text = { Text(stringResource(R.string.attach_camera)) },
1808+ onClick = { showAttachMenu = false; onCamera() },
1809+ )
1810+ DropdownMenuItem(
1811+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1812+ text = { Text(stringResource(R.string.attach_file)) },
1813+ onClick = { showAttachMenu = false; onPickFile() },
1814+ )
1815+ }
1816+ }
1817+ // Voice dictation: appends recognized speech to the draft.
1818+ IconButton(onClick = onVoice, enabled = enabled) {
1819+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1820+ }
1821+ // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1822+ IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1823+ Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1824+ }
1825+ OutlinedTextField(
1826+ value = value,
1827+ onValueChange = { v ->
1828+ // Cap input length so a huge paste can't stall the UI. Shares are
1829+ // capped separately in MainActivity; this guards typed/pasted drafts.
1830+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1831+ },
1832+ modifier = Modifier
1833+ .weight(1f)
1834+ .focusRequester(focusRequester)
1835+ .testTag("chat_input")
1836+ // Intercept image content pasted/dropped into the field (keyboard paste
1837+ // of a copied screenshot, drag from Files, etc.) and route it through the
1838+ // same staging path as the attach menu. Non-image content (text) falls
1839+ // through unchanged so normal typing/paste works.
1840+ .contentReceiver(
1841+ remember {
1842+ androidx.compose.foundation.content.ReceiveContentListener { transferable ->
1843+ val clipData = transferable.clipEntry?.clipData
1844+ if (clipData != null) {
1845+ val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
1846+ val item = clipData.getItemAt(i)
1847+ item.uri?.takeIf { uri ->
1848+ item.text == null && uri.toString().let { s ->
1849+ s.startsWith("content:") || s.startsWith("file:")
1850+ }
1851+ }
1852+ }
1853+ if (imageUris.isNotEmpty()) {
1854+ onPasteImage(imageUris)
1855+ }
1856+ }
1857+ transferable
1858+ }
1859+ },
1860+ )
1861+ .onPreviewKeyEvent { event ->
1862+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1863+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1864+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1865+ val send = enterShouldSend(
1866+ enabled = enabled,
1867+ hasContent = hasContent,
1868+ sendOnEnter = sendOnEnter,
1869+ shift = event.isShiftPressed,
1870+ ctrl = event.isCtrlPressed,
1871+ )
1872+ if (send) {
1873+ if (running) onQueueFollowUp(value) else onSend()
1874+ true
1875+ } else {
1876+ false
1877+ }
1878+ },
1879+ // While a run is active a typed message only queues (sends after the run), so
1880+ // the placeholder says so instead of the plain "Message…".
1881+ placeholder = {
1882+ Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1883+ },
1884+ enabled = enabled,
1885+ maxLines = 6,
1886+ // Show a "N / max" countdown once the draft crosses a high fraction of
1887+ // the cap, so the user knows a paste is about to be truncated instead
1888+ // of being silently cut off. Hidden for normal short prompts to avoid
1889+ // clutter under a typical one-line message.
1890+ supportingText = {
1891+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1892+ if (value.length >= threshold) {
1893+ Text(
1894+ stringResource(
1895+ R.string.draft_chars_remaining,
1896+ NetworkConfig.maxDraftLengthChars - value.length,
1897+ NetworkConfig.maxDraftLengthChars,
1898+ ),
1899+ style = MaterialTheme.typography.labelSmall,
1900+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1901+ else MaterialTheme.colorScheme.onSurfaceVariant,
1902+ )
1903+ }
1904+ },
1905+ keyboardOptions = KeyboardOptions(
1906+ // When "Send on Enter" is on, expose ImeAction.Send so the soft
1907+ // keyboard shows a send key — matching the setting's intent and
1908+ // giving touch-only users a keyboard send affordance. When off,
1909+ // ImeAction.Default keeps the enter/newline key for multi-line input.
1910+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1911+ capitalization = KeyboardCapitalization.Sentences,
1912+ ),
1913+ keyboardActions = KeyboardActions(
1914+ onSend = {
1915+ if (enabled && hasContent) onSend()
1916+ },
1917+ ),
1918+ )
1919+ ComposerTrailingButton(
1920+ running = running,
1921+ aborting = aborting,
1922+ canSend = enabled && hasContent,
1923+ canQueue = enabled && value.isNotBlank(),
1924+ onSend = onSend,
1925+ onAbort = onAbort,
1926+ onQueue = { onQueueFollowUp(value) },
1927+ )
1928+ }
1929+ }
1930+ if (showFullScreenEditor) {
1931+ FullScreenEditor(
1932+ value = value,
1933+ onValueChange = onValueChange,
1934+ onDismiss = { showFullScreenEditor = false },
1935+ onSend = {
1936+ showFullScreenEditor = false
1937+ // Mirror the inline composer's behavior: while a run is active a send
1938+ // can't go immediately, so queue the follow-up instead of silently
1939+ // dropping it (vm.send() returns false during a run, which previously
1940+ // lost the typed message with no feedback).
1941+ if (running) onQueueFollowUp(value) else onSend()
1942+ },
1943+ canSend = enabled && hasContent,
1944+ running = running,
1945+ sendOnEnter = sendOnEnter,
1946+ attachments = attachments,
1947+ onRemoveAttachment = onRemoveAttachment,
1948+ staging = staging,
1949+ )
1950+ }
1951+ }
1952+}
1953+
1954+/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1955+ * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1956+@OptIn(ExperimentalMaterial3Api::class)
1957+@Composable
1958+private fun FullScreenEditor(
1959+ value: String,
1960+ onValueChange: (String) -> Unit,
1961+ onDismiss: () -> Unit,
1962+ onSend: () -> Unit,
1963+ canSend: Boolean,
1964+ running: Boolean = false,
1965+ sendOnEnter: Boolean = false,
1966+ attachments: List<PendingAttachment> = emptyList(),
1967+ onRemoveAttachment: (String) -> Unit = {},
1968+ staging: Boolean = false,
1969+) {
1970+ androidx.compose.ui.window.Dialog(
1971+ onDismissRequest = onDismiss,
1972+ properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1973+ ) {
1974+ Scaffold(
1975+ topBar = {
1976+ androidx.compose.material3.TopAppBar(
1977+ title = { Text(stringResource(R.string.message_placeholder)) },
1978+ navigationIcon = {
1979+ androidx.compose.material3.TextButton(onClick = onDismiss) {
1980+ Text(stringResource(R.string.collapse_editor))
1981+ }
1982+ },
1983+ )
1984+ },
1985+ bottomBar = {
1986+ Surface(tonalElevation = 3.dp) {
1987+ Row(
1988+ modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1989+ horizontalArrangement = Arrangement.End,
1990+ ) {
1991+ androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1992+ Text(stringResource(if (running) R.string.queue else R.string.send))
1993+ }
1994+ }
1995+ }
1996+ },
1997+ ) { padding ->
1998+ Column(modifier = Modifier.fillMaxSize().padding(padding)) {
1999+ // Show staged attachments in the full-screen editor too, so a user who staged
2000+ // images then expanded for a long prompt can still see and remove them without
2001+ // collapsing first (mirrors the inline composer's AttachmentStrip).
2002+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
2003+ OutlinedTextField(
2004+ value = value,
2005+ onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2006+ modifier = Modifier
2007+ .fillMaxSize()
2008+ .weight(1f)
2009+ // Honor the "Send on Enter" setting here too, so the full-screen
2010+ // editor matches the inline composer: Enter sends (Shift+Enter
2011+ // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2012+ // when off. Previously this hard-coded ImeAction.Default and had no
2013+ // key handler, so a hardware-keyboard user got a different behaviour
2014+ // from the inline composer depending on which they happened to open.
2015+ .onPreviewKeyEvent { event ->
2016+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2017+ val send = enterShouldSend(
2018+ enabled = canSend,
2019+ hasContent = canSend,
2020+ sendOnEnter = sendOnEnter,
2021+ shift = event.isShiftPressed,
2022+ ctrl = event.isCtrlPressed,
2023+ )
2024+ if (send) { onSend(); true } else false
2025+ },
2026+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
2027+ maxLines = Int.MAX_VALUE,
2028+ keyboardOptions = KeyboardOptions(
2029+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2030+ capitalization = KeyboardCapitalization.Sentences,
2031+ ),
2032+ keyboardActions = KeyboardActions(
2033+ onSend = { if (canSend) onSend() },
2034+ ),
2035+ )
2036+ }
2037+ }
2038+ }
2039+}
2040+
2041+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2042+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2043+private fun enterShouldSend(
2044+ enabled: Boolean,
2045+ hasContent: Boolean,
2046+ sendOnEnter: Boolean,
2047+ shift: Boolean,
2048+ ctrl: Boolean,
2049+): Boolean = when {
2050+ !enabled || !hasContent -> false
2051+ sendOnEnter -> !shift
2052+ else -> ctrl
2053+}
2054+
2055+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2056+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2057+ * [ChatInputBar] stays under the complexity threshold. */
2058+@Composable
2059+private fun ComposerTrailingButton(
2060+ running: Boolean,
2061+ aborting: Boolean,
2062+ canSend: Boolean,
2063+ canQueue: Boolean,
2064+ onSend: () -> Unit,
2065+ onAbort: () -> Unit,
2066+ onQueue: () -> Unit,
2067+) {
2068+ if (running) {
2069+ Row(verticalAlignment = Alignment.CenterVertically) {
2070+ // While a run is active the trailing action is Stop, so the only send affordance is
2071+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2072+ // That leaves a touch-only user with the setting off no way to queue a follow-up
2073+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2074+ // there's typed TEXT so queuing is always reachable, without changing the user's
2075+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2076+ // canSend, which is also true for an attachment-only composer — because queuing "" just
2077+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2078+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2079+ if (canQueue) {
2080+ IconButton(
2081+ onClick = onQueue,
2082+ modifier = Modifier.testTag("queue_button"),
2083+ ) {
2084+ // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2085+ // icon (which can be read as "snooze" or "later"), and isn't confused with
2086+ // the Send action sitting right beside the Stop button.
2087+ Icon(
2088+ Icons.AutoMirrored.Filled.PlaylistAdd,
2089+ contentDescription = stringResource(R.string.queue_followup),
2090+ )
2091+ }
2092+ }
2093+ // Show a spinner while the abort REST call is in flight so the user sees the stop
2094+ // was sent, and disable to prevent a double-tap.
2095+ IconButton(
2096+ onClick = onAbort,
2097+ enabled = !aborting,
2098+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2099+ ) {
2100+ if (aborting) {
2101+ val stopLabel = stringResource(R.string.stop)
2102+ CircularProgressIndicator(
2103+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2104+ strokeWidth = 2.dp,
2105+ )
2106+ } else {
2107+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2108+ }
2109+ }
2110+ }
2111+ } else {
2112+ IconButton(
2113+ onClick = onSend,
2114+ enabled = canSend,
2115+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2116+ ) {
2117+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
2118+ }
2119+ }
2120+}
2121+
2122+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2123+@Composable
2124+private fun EmptyConversation(
2125+ onSuggestion: (String) -> Unit,
2126+ modifier: Modifier = Modifier,
2127+) {
2128+ // A few example prompts so a first-time user has a one-tap path to their first
2129+ // message instead of staring at a blank input. Tapping a chip fills the draft
2130+ // (without sending) so the user can edit it before sending.
2131+ val suggestions = remember {
2132+ listOf(
2133+ R.string.empty_chat_suggest_1,
2134+ R.string.empty_chat_suggest_2,
2135+ R.string.empty_chat_suggest_3,
2136+ )
2137+ }
2138+ Column(
2139+ modifier = modifier.padding(32.dp),
2140+ horizontalAlignment = Alignment.CenterHorizontally,
2141+ ) {
2142+ Icon(
2143+ Icons.Filled.AutoAwesome,
2144+ contentDescription = null,
2145+ modifier = Modifier.size(48.dp),
2146+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
2147+ )
2148+ Spacer(Modifier.size(16.dp))
2149+ Text(
2150+ stringResource(R.string.empty_chat_title),
2151+ style = MaterialTheme.typography.titleMedium,
2152+ )
2153+ Spacer(Modifier.size(8.dp))
2154+ Text(
2155+ stringResource(R.string.empty_chat_hint),
2156+ style = MaterialTheme.typography.bodyMedium,
2157+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2158+ )
2159+ Spacer(Modifier.size(20.dp))
2160+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2161+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
2162+ FlowRow(
2163+ modifier = Modifier.fillMaxWidth(),
2164+ horizontalArrangement = Arrangement.spacedBy(8.dp),
2165+ verticalArrangement = Arrangement.spacedBy(8.dp),
2166+ ) {
2167+ suggestions.forEach { resId ->
2168+ val text = stringResource(resId)
2169+ androidx.compose.material3.AssistChip(
2170+ onClick = { onSuggestion(text) },
2171+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2172+ )
2173+ }
2174+ }
2175+ }
2176+}
2177+
2178+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
2179+@Composable
2180+private fun RevertBanner(onUndo: () -> Unit) {
2181+ val haptics = LocalHapticFeedback.current
2182+ Surface(
2183+ color = MaterialTheme.colorScheme.tertiaryContainer,
2184+ tonalElevation = 2.dp,
2185+ modifier = Modifier.fillMaxWidth(),
2186+ ) {
2187+ Row(
2188+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2189+ verticalAlignment = Alignment.CenterVertically,
2190+ horizontalArrangement = Arrangement.SpaceBetween,
2191+ ) {
2192+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2193+ Icon(
2194+ Icons.Filled.Restore,
2195+ contentDescription = null,
2196+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
2197+ modifier = Modifier.size(18.dp),
2198+ )
2199+ Text(
2200+ stringResource(R.string.reverted_banner),
2201+ style = MaterialTheme.typography.bodySmall,
2202+ color = MaterialTheme.colorScheme.onTertiaryContainer,
2203+ modifier = Modifier.padding(start = 8.dp),
2204+ )
2205+ }
2206+ TextButton(onClick = {
2207+ // Haptic on undo to match the other destructive/important confirmations: a
2208+ // revert restores potentially hundreds of hidden messages.
2209+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2210+ onUndo()
2211+ }) { Text(stringResource(R.string.undo)) }
2212+ }
2213+ }
2214+}
2215+
2216+/** A banner shown while messages composed offline are queued in the outbox, with a
2217+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2218+@Composable
2219+private fun OutboxBanner(
2220+ count: Int,
2221+ sending: Boolean,
2222+ onFlush: () -> Unit,
2223+ onDiscard: () -> Unit,
2224+) {
2225+ Surface(
2226+ color = MaterialTheme.colorScheme.secondaryContainer,
2227+ tonalElevation = 2.dp,
2228+ modifier = Modifier.fillMaxWidth(),
2229+ ) {
2230+ Row(
2231+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2232+ verticalAlignment = Alignment.CenterVertically,
2233+ horizontalArrangement = Arrangement.SpaceBetween,
2234+ ) {
2235+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2236+ if (sending) {
2237+ CircularProgressIndicator(
2238+ Modifier.size(16.dp),
2239+ strokeWidth = 2.dp,
2240+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2241+ )
2242+ Spacer(Modifier.size(8.dp))
2243+ }
2244+ Text(
2245+ if (sending) {
2246+ stringResource(R.string.outbox_sending)
2247+ } else {
2248+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2249+ stringResource(res, count)
2250+ },
2251+ style = MaterialTheme.typography.bodySmall,
2252+ color = MaterialTheme.colorScheme.onSecondaryContainer,
2253+ )
2254+ }
2255+ if (!sending) {
2256+ val haptics = LocalHapticFeedback.current
2257+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2258+ TextButton(onClick = {
2259+ // Haptic on the irreversible "Discard queued" (drops every queued message
2260+ // for this session), matching the error-colored destructive actions.
2261+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2262+ onDiscard()
2263+ }) {
2264+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2265+ }
2266+ }
2267+ }
2268+ }
2269+}
2270+
2271+/** Prompt for a one-off shell command to run in the session's worktree. */
2272+@Composable
2273+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
2274+ var command by rememberSaveable { mutableStateOf("") }
2275+ AlertDialog(
2276+ onDismissRequest = onDismiss,
2277+ title = { Text(stringResource(R.string.run_shell_command)) },
2278+ text = {
2279+ OutlinedTextField(
2280+ value = command,
2281+ onValueChange = { command = it },
2282+ modifier = Modifier.fillMaxWidth(),
2283+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
2284+ label = { Text(stringResource(R.string.shell_command_label)) },
2285+ singleLine = true,
2286+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2287+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
2288+ )
2289+ },
2290+ confirmButton = {
2291+ TextButton(
2292+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
2293+ enabled = command.isNotBlank(),
2294+ ) { Text(stringResource(R.string.run)) }
2295+ },
2296+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
2297+ )
2298+}
2299+
2300+/**
2301+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
2302+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
2303+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
2304+ */
2305+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
2306+
2307+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
2308+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
2309+ * streaming, not just plain assistant text. O(1). */
2310+private fun streamingContentLength(part: Part?): Int = when (part) {
2311+ is TextPart -> part.text.length
2312+ is ReasoningPart -> part.text.length
2313+ is ToolPart -> when (val st = part.state) {
2314+ is ToolCompleted -> st.output?.length ?: 0
2315+ is ToolError -> st.error?.length ?: 0
2316+ is ToolRunning -> st.title?.length ?: 0
2317+ else -> 0
2318+ }
2319+ else -> 0
2320+}
2321+
2322+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
2323+ * dialog but lives in the chat screen so the user can rename without backing out to
2324+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
2325+@Composable
2326+private fun RenameSessionChatDialog(
2327+ initialTitle: String,
2328+ onDismiss: () -> Unit,
2329+ onConfirm: (String) -> Unit,
2330+) {
2331+ // Seed the field once (no key input) so a later external title change — e.g. opencode
2332+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
2333+ // doesn't re-initialize the box and discard the user's in-progress edit.
2334+ var title by rememberSaveable { mutableStateOf(initialTitle) }
2335+ AlertDialog(
2336+ onDismissRequest = onDismiss,
2337+ title = { Text(stringResource(R.string.rename_session_chat)) },
2338+ text = {
2339+ OutlinedTextField(
2340+ value = title,
2341+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
2342+ modifier = Modifier.fillMaxWidth(),
2343+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
2344+ label = { Text(stringResource(R.string.rename_session_chat)) },
2345+ singleLine = true,
2346+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2347+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
2348+ )
2349+ },
2350+ confirmButton = {
2351+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
2352+ Text(stringResource(R.string.save))
2353+ }
2354+ },
2355+ dismissButton = {
2356+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
2357+ },
2358+ )
2359+}
2360+
2361+/**
2362+ * A single item in the chat message list — either a [Message] bubble or a day
2363+ * [Separator] inserted before the first message of a new day. The separator shifts
2364+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
2365+ * the [List] of these items (not `messages.size`/`lastIndex`).
2366+ */
2367+private sealed interface MessageListItem {
2368+ val key: Any
2369+ val contentType: Any
2370+
2371+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
2372+ override val contentType: Any get() = message.info::class
2373+ }
2374+
2375+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
2376+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
2377+ // can share a label (e.g. an untimestamped message — empty label — between two
2378+ // same-day messages, or two untimestamped groups), and a label-only key would
2379+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
2380+ // stable for a given message ordering so slots aren't needlessly recreated.
2381+ override val key: Any get() = "sep_${ordinal}_$label"
2382+ // Separators share a contentType so the LazyColumn can recycle their slots.
2383+ override val contentType: Any get() = "separator"
2384+ }
2385+}
2386+
2387+/**
2388+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
2389+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
2390+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
2391+ * Messages with no timestamp are grouped under an empty-label separator only if they
2392+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
2393+ *
2394+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
2395+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
2396+ * labels; older days fall back to a locale-stable medium-date format.
2397+ */
2398+private fun buildMessageListItems(
2399+ messages: List<MessageWithParts>,
2400+ todayLabel: String,
2401+ yesterdayLabel: String,
2402+): List<MessageListItem> {
2403+ if (messages.isEmpty()) return emptyList()
2404+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
2405+ val dateFmt = mediumDateFormat()
2406+ val result = ArrayList<MessageListItem>(messages.size + 4)
2407+ val seenKeys = HashSet<String>(messages.size * 2)
2408+ var lastDayKey: String? = null
2409+ var sepOrdinal = 0
2410+ var emptyIdOrdinal = 0
2411+ var first = true
2412+ for (message in messages) {
2413+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
2414+ val dayKey = ts?.let { dayKey(it) } ?: ""
2415+ // Emit a separator before the very first message (so a leading un-timestamped message
2416+ // still gets the first divider, empty label and all), and thereafter only when crossing
2417+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
2418+ // neither emits its own separator nor resets the day — otherwise a following same-day
2419+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
2420+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
2421+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
2422+ }
2423+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
2424+ first = false
2425+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
2426+ // empty id — and the reducer intentionally keeps several such messages as distinct
2427+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
2428+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
2429+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
2430+ if (!seenKeys.add(key)) {
2431+ var suffix = 1
2432+ while (!seenKeys.add("$key#$suffix")) suffix++
2433+ key = "$key#$suffix"
2434+ }
2435+ result.add(MessageListItem.Message(message, key))
2436+ }
2437+ return result
2438+}
2439+
2440+/**
2441+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2442+ *
2443+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2444+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
2445+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2446+ * every message on every token. Message timestamps are immutable once assigned, so we
2447+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2448+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2449+ * thread during composition, so the coarse lock is uncontended.
2450+ */
2451+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2452+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2453+}
2454+
2455+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2456+ dayKeyCache.getOrPut(epochMillis) {
2457+ java.time.Instant.ofEpochMilli(epochMillis)
2458+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2459+ }
2460+}
2461+
2462+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2463+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2464+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2465+private var cachedDateFmt: java.text.DateFormat? = null
2466+private var cachedDateFmtLocale: java.util.Locale? = null
2467+
2468+private fun mediumDateFormat(): java.text.DateFormat {
2469+ val locale = java.util.Locale.getDefault()
2470+ val existing = cachedDateFmt
2471+ if (existing != null && cachedDateFmtLocale == locale) return existing
2472+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2473+ cachedDateFmt = it
2474+ cachedDateFmtLocale = locale
2475+ }
2476+}
2477+
2478+/**
2479+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2480+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2481+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2482+ * messages.
2483+ */
2484+private fun dayLabel(
2485+ dayKey: String,
2486+ ts: Long,
2487+ today: java.time.LocalDate,
2488+ todayLabel: String,
2489+ yesterdayLabel: String,
2490+ dateFmt: java.text.DateFormat,
2491+): String {
2492+ if (dayKey.isEmpty()) return ""
2493+ val epochDay = dayKey.toLongOrNull() ?: return ""
2494+ val date = java.time.LocalDate.ofEpochDay(epochDay)
2495+ return when {
2496+ date == today -> todayLabel
2497+ date == today.minusDays(1) -> yesterdayLabel
2498+ else -> dateFmt.format(java.util.Date(ts))
2499+ }
2500+}
2501+
2502+/**
2503+ * A centered day divider in the message list. Renders nothing for an empty label
2504+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2505+ */
2506+@Composable
2507+private fun DateSeparator(label: String) {
2508+ if (label.isBlank()) return
2509+ Row(
2510+ modifier = Modifier.fillMaxWidth(),
2511+ horizontalArrangement = Arrangement.Center,
2512+ ) {
2513+ Surface(
2514+ color = MaterialTheme.colorScheme.surfaceVariant,
2515+ shape = MaterialTheme.shapes.small,
2516+ // Marked as a heading so TalkBack users can navigate day-by-day with the
2517+ // heading-skip gesture — the canonical affordance for date dividers in a list.
2518+ modifier = Modifier.semantics(mergeDescendants = true) { heading() },
2519+ ) {
2520+ Text(
2521+ label,
2522+ style = MaterialTheme.typography.labelSmall,
2523+ color = MaterialTheme.colorScheme.onSurfaceVariant,
2524+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
2525+ )
2526+ }
2527+ }
2528+}