@@ -0,0 +1,1783 @@
1+package soy.iko.opencode.ui.chat
2+
3+import android.app.Activity
4+import android.content.Intent
5+import android.net.Uri
6+import android.speech.RecognizerIntent
7+import androidx.activity.compose.BackHandler
8+import androidx.activity.compose.rememberLauncherForActivityResult
9+import androidx.activity.result.PickVisualMediaRequest
10+import androidx.activity.result.contract.ActivityResultContracts
11+import androidx.compose.animation.AnimatedVisibility
12+import androidx.compose.foundation.clickable
13+import androidx.compose.foundation.layout.Arrangement
14+import androidx.compose.foundation.layout.Box
15+import androidx.compose.foundation.layout.Column
16+import androidx.compose.foundation.layout.FlowRow
17+import androidx.compose.foundation.layout.PaddingValues
18+import androidx.compose.foundation.layout.Row
19+import androidx.compose.foundation.layout.Spacer
20+import androidx.compose.foundation.layout.WindowInsets
21+import androidx.compose.foundation.layout.fillMaxSize
22+import androidx.compose.foundation.layout.fillMaxWidth
23+import androidx.compose.foundation.layout.imePadding
24+import androidx.compose.foundation.layout.navigationBars
25+import androidx.compose.foundation.layout.padding
26+import androidx.compose.foundation.layout.size
27+import androidx.compose.foundation.layout.union
28+import androidx.compose.foundation.layout.windowInsetsPadding
29+import androidx.compose.foundation.lazy.LazyColumn
30+import androidx.compose.foundation.lazy.items
31+import androidx.compose.foundation.lazy.rememberLazyListState
32+import androidx.compose.material.icons.Icons
33+import androidx.compose.material.icons.automirrored.filled.ArrowBack
34+import androidx.compose.material.icons.automirrored.filled.Send
35+import androidx.compose.material.icons.filled.Add
36+import androidx.compose.material.icons.filled.AutoAwesome
37+import androidx.compose.material.icons.filled.Delete
38+import androidx.compose.material.icons.filled.Description
39+import androidx.compose.material.icons.filled.Edit
40+import androidx.compose.material.icons.filled.KeyboardArrowDown
41+import androidx.compose.material.icons.filled.Mic
42+import androidx.compose.material.icons.filled.MoreVert
43+import androidx.compose.material.icons.filled.PhotoCamera
44+import androidx.compose.material.icons.filled.PhotoLibrary
45+import androidx.compose.material.icons.filled.Refresh
46+import androidx.compose.material.icons.filled.Restore
47+import androidx.compose.material.icons.filled.Stop
48+import androidx.compose.material3.AlertDialog
49+import androidx.compose.material3.Badge
50+import androidx.compose.material3.BadgedBox
51+import androidx.compose.material3.Button
52+import androidx.compose.material3.CircularProgressIndicator
53+import androidx.compose.material3.DropdownMenu
54+import androidx.compose.material3.DropdownMenuItem
55+import androidx.compose.material3.ExperimentalMaterial3Api
56+import androidx.compose.material3.ExtendedFloatingActionButton
57+import androidx.compose.material3.FloatingActionButton
58+import androidx.compose.material3.Icon
59+import androidx.compose.material3.IconButton
60+import androidx.compose.material3.MaterialTheme
61+import androidx.compose.material3.OutlinedTextField
62+import androidx.compose.material3.Scaffold
63+import androidx.compose.material3.SnackbarHost
64+import androidx.compose.material3.SnackbarHostState
65+import androidx.compose.material3.Surface
66+import androidx.compose.material3.Text
67+import androidx.compose.material3.TextButton
68+import androidx.compose.material3.TopAppBar
69+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
70+import androidx.compose.runtime.Composable
71+import androidx.compose.runtime.CompositionLocalProvider
72+import androidx.compose.runtime.DisposableEffect
73+import androidx.compose.runtime.LaunchedEffect
74+import androidx.compose.runtime.derivedStateOf
75+import androidx.compose.runtime.getValue
76+import androidx.compose.runtime.mutableStateOf
77+import androidx.compose.runtime.remember
78+import androidx.compose.runtime.rememberCoroutineScope
79+import androidx.compose.runtime.rememberUpdatedState
80+import androidx.compose.runtime.saveable.rememberSaveable
81+import androidx.compose.runtime.setValue
82+import androidx.compose.runtime.snapshotFlow
83+import androidx.compose.foundation.text.KeyboardActions
84+import androidx.compose.foundation.text.KeyboardOptions
85+import androidx.compose.ui.text.input.KeyboardCapitalization
86+import androidx.compose.ui.Alignment
87+import androidx.compose.ui.Modifier
88+import androidx.compose.ui.focus.focusRequester
89+import androidx.compose.ui.input.key.Key
90+import androidx.compose.ui.input.key.KeyEventType
91+import androidx.compose.ui.input.key.isCtrlPressed
92+import androidx.compose.ui.input.key.isShiftPressed
93+import androidx.compose.ui.input.key.key
94+import androidx.compose.ui.input.key.onPreviewKeyEvent
95+import androidx.compose.ui.input.key.type
96+import androidx.compose.ui.platform.LocalContext
97+import androidx.compose.ui.platform.LocalHapticFeedback
98+import androidx.compose.ui.platform.LocalView
99+import androidx.compose.ui.platform.testTag
100+import androidx.compose.ui.res.stringResource
101+import androidx.compose.ui.semantics.Role
102+import androidx.compose.ui.semantics.contentDescription
103+import androidx.compose.ui.semantics.semantics
104+import androidx.compose.ui.text.input.ImeAction
105+import androidx.compose.ui.text.style.TextOverflow
106+import androidx.compose.ui.unit.dp
107+import androidx.lifecycle.compose.collectAsStateWithLifecycle
108+import androidx.lifecycle.viewmodel.compose.viewModel
109+import kotlinx.coroutines.Dispatchers
110+import kotlinx.coroutines.launch
111+import kotlinx.coroutines.withContext
112+import soy.iko.opencode.data.model.Part
113+import soy.iko.opencode.data.model.MessageWithParts
114+import soy.iko.opencode.data.model.ReasoningPart
115+import soy.iko.opencode.data.model.TextPart
116+import soy.iko.opencode.data.model.ToolCompleted
117+import soy.iko.opencode.data.model.ToolError
118+import soy.iko.opencode.data.model.ToolPart
119+import soy.iko.opencode.data.model.ToolRunning
120+import soy.iko.opencode.data.network.EventStreamClient
121+import soy.iko.opencode.data.network.NetworkConfig
122+import soy.iko.opencode.di.AppContainer
123+import soy.iko.opencode.R
124+import soy.iko.opencode.ui.components.CommandPalette
125+import soy.iko.opencode.ui.components.ConnectionBanner
126+import soy.iko.opencode.ui.components.PaletteAction
127+import soy.iko.opencode.ui.components.copyToClipboard
128+import soy.iko.opencode.ui.components.LocalRelativeTimeTick
129+import soy.iko.opencode.ui.components.rememberRelativeTimeTick
130+import soy.iko.opencode.ui.components.showToast
131+import soy.iko.opencode.ui.components.toImageContext
132+import soy.iko.opencode.ui.vmFactory
133+import soy.iko.opencode.util.runCatchingCancellable
134+
135+@OptIn(ExperimentalMaterial3Api::class)
136+@Composable
137+fun ChatScreen(
138+ container: AppContainer,
139+ sessionId: String,
140+ onBack: () -> Unit,
141+ onOpenFile: ((String) -> Unit)? = null,
142+ onOpenSession: ((String) -> Unit)? = null,
143+) {
144+ val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
145+ val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
146+ val running by vm.running.collectAsStateWithLifecycle()
147+ val aborting by vm.aborting.collectAsStateWithLifecycle()
148+ val loading by vm.loading.collectAsStateWithLifecycle()
149+ val loadError by vm.loadError.collectAsStateWithLifecycle()
150+ val refreshing by vm.refreshing.collectAsStateWithLifecycle()
151+ val models by vm.models.collectAsStateWithLifecycle()
152+ val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
153+ val modelsError by vm.modelsError.collectAsStateWithLifecycle()
154+ val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
155+ val connectionState by vm.connectionState.collectAsStateWithLifecycle()
156+ val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
157+ val agents by vm.agents.collectAsStateWithLifecycle()
158+ val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
159+ val agentsError by vm.agentsError.collectAsStateWithLifecycle()
160+ val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
161+ val commands by vm.commands.collectAsStateWithLifecycle()
162+ val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
163+ val commandsError by vm.commandsError.collectAsStateWithLifecycle()
164+ val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
165+ val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
166+ val draft by vm.draft.collectAsStateWithLifecycle()
167+ val attachments by vm.attachments.collectAsStateWithLifecycle()
168+ val reverted by vm.reverted.collectAsStateWithLifecycle()
169+ val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
170+ val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
171+ val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
172+ val isOnline by container.isOnline.collectAsStateWithLifecycle()
173+ val haptics = LocalHapticFeedback.current
174+ val scope = rememberCoroutineScope()
175+ val shareContext = LocalContext.current
176+ val defaultShareSubject = stringResource(R.string.share_subject)
177+ val sessionLabel = stringResource(R.string.session)
178+ val defaultModelLabel = stringResource(R.string.default_model)
179+ val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
180+ buildString {
181+ append(selectedModel?.modelLabel ?: defaultModelLabel)
182+ selectedAgent?.let { append(" · $it") }
183+ }
184+ }
185+
186+ // Connection profile (with auth) for rendering inline image attachments.
187+ // Collect as state so a server switch recomposes the image context.
188+ val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
189+ val imageContext = remember(activeConnection?.profile) {
190+ activeConnection?.profile?.toImageContext()
191+ }
192+
193+ // Mark this session as read while the user is viewing it; clear on leave so new
194+ // background activity can badge it again.
195+ DisposableEffect(sessionId) {
196+ container.setCurrentSession(sessionId)
197+ onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
198+ }
199+
200+ // Navigate away when the session is deleted via SSE so the user isn't left
201+ // on a zombie screen showing a conversation that no longer exists. Surface a
202+ // toast (not a snackbar) because the screen is about to be popped — a snackbar
203+ // would be torn down before the user could read it, while a toast survives.
204+ // Covers both SSE-driven deletion (deleted on another device) and a user-
205+ // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
206+ // sets the same flag on success).
207+ val deletedContext = LocalContext.current
208+ LaunchedEffect(sessionDeleted) {
209+ if (sessionDeleted) {
210+ showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
211+ onBack()
212+ }
213+ }
214+
215+ val snackbar = remember { SnackbarHostState() }
216+ val retryLabel = stringResource(R.string.retry)
217+ val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
218+ var showModelPicker by rememberSaveable { mutableStateOf(false) }
219+ var showAgentPicker by rememberSaveable { mutableStateOf(false) }
220+ var showCommandPicker by rememberSaveable { mutableStateOf(false) }
221+ var showExitConfirm by rememberSaveable { mutableStateOf(false) }
222+ var showStopConfirm by rememberSaveable { mutableStateOf(false) }
223+ var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
224+ var showRenameDialog by rememberSaveable { mutableStateOf(false) }
225+ var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
226+ var showShellDialog by rememberSaveable { mutableStateOf(false) }
227+ var showPalette by rememberSaveable { mutableStateOf(false) }
228+
229+ // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
230+ // action list doesn't need a Composable context. Actions map to the same handlers the
231+ // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
232+ val paletteModelLabel = stringResource(R.string.palette_switch_model)
233+ val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
234+ val paletteCommandLabel = stringResource(R.string.palette_run_command)
235+ val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
236+ val paletteRenameLabel = stringResource(R.string.rename_session_chat)
237+ val paletteShellLabel = stringResource(R.string.run_shell_command)
238+ val paletteActions = remember(
239+ paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
240+ paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
241+ ) {
242+ buildList {
243+ add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
244+ add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
245+ add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
246+ if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { vm.summarize() })
247+ if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
248+ add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
249+ }
250+ }
251+
252+ // Keep the screen awake while the agent is working in *this* session. The foreground
253+ // service that holds process priority during a run is managed app-wide off
254+ // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
255+ // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
256+ // SSE stream before the completion notification fires.
257+ val currentView = LocalView.current
258+ val appContext = LocalContext.current.applicationContext
259+ DisposableEffect(running) {
260+ currentView.keepScreenOn = running
261+ onDispose { currentView.keepScreenOn = false }
262+ }
263+
264+ LaunchedEffect(Unit) {
265+ vm.errorEvents.collect { event ->
266+ // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
267+ // message-load failure) would silently re-submit the last prompt on tap.
268+ val result = if (event.retryable) {
269+ snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
270+ } else {
271+ snackbar.showSnackbar(event.message)
272+ }
273+ if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
274+ }
275+ }
276+
277+ // --- Attachments, voice, and share-link plumbing ---
278+ val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
279+ val attachFailedMsg = stringResource(R.string.attachment_failed)
280+ val attachLimitMsg = stringResource(R.string.attachment_limit)
281+ val noCameraMsg = stringResource(R.string.no_camera_app)
282+ val noVoiceMsg = stringResource(R.string.no_voice_app)
283+ val voicePrompt = stringResource(R.string.voice_prompt)
284+ val linkCopiedMsg = stringResource(R.string.link_copied)
285+
286+ // Count of picks currently being read + base64-encoded off the main thread, so the
287+ // composer can show a staging placeholder immediately (chips only materialize once done).
288+ var stagingCount by remember { mutableStateOf(0) }
289+
290+ // Convert each picked Uri to a base64 attachment off the main thread, honoring the
291+ // per-prompt count cap and surfacing per-file errors without aborting the batch.
292+ fun stageUris(uris: List<Uri>) {
293+ if (uris.isEmpty()) return
294+ scope.launch {
295+ stagingCount++
296+ try {
297+ for (uri in uris) {
298+ if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
299+ snackbar.showSnackbar(attachLimitMsg)
300+ break
301+ }
302+ when (val result = uri.toAttachmentResult(appContext)) {
303+ is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
304+ AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
305+ AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
306+ }
307+ }
308+ } finally {
309+ stagingCount--
310+ }
311+ }
312+ }
313+
314+ val photoPicker = rememberLauncherForActivityResult(
315+ ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
316+ ) { uris -> stageUris(uris) }
317+
318+ val filePicker = rememberLauncherForActivityResult(
319+ ActivityResultContracts.GetMultipleContents(),
320+ ) { uris -> stageUris(uris) }
321+
322+ // Uri survives a config change mid-capture so the TakePicture result still resolves.
323+ var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
324+ val cameraLauncher = rememberLauncherForActivityResult(
325+ ActivityResultContracts.TakePicture(),
326+ ) { success ->
327+ val uri = pendingCaptureUri
328+ pendingCaptureUri = null
329+ if (success && uri != null) stageUris(listOf(uri))
330+ }
331+
332+ val voiceLauncher = rememberLauncherForActivityResult(
333+ ActivityResultContracts.StartActivityForResult(),
334+ ) { result ->
335+ if (result.resultCode == Activity.RESULT_OK) {
336+ val spoken = result.data
337+ ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
338+ ?.firstOrNull()
339+ ?.takeIf { it.isNotBlank() }
340+ if (spoken != null) {
341+ // Append to the existing draft rather than replacing, so dictation adds to
342+ // whatever the user already typed.
343+ val current = vm.draft.value
344+ val combined = if (current.isBlank()) spoken else "$current $spoken"
345+ vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
346+ }
347+ }
348+ }
349+
350+ fun launchCamera() {
351+ val uri = newCameraCaptureUri(appContext)
352+ if (uri == null) {
353+ scope.launch { snackbar.showSnackbar(attachFailedMsg) }
354+ return
355+ }
356+ pendingCaptureUri = uri
357+ runCatching { cameraLauncher.launch(uri) }
358+ .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
359+ }
360+
361+ fun launchVoice() {
362+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
363+ putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
364+ putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
365+ }
366+ runCatching { voiceLauncher.launch(intent) }
367+ .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
368+ }
369+
370+ // A freshly-created share link is copied to the clipboard so the user can paste it right away.
371+ LaunchedEffect(Unit) {
372+ vm.shareLinkEvents.collect { url ->
373+ copyToClipboard(shareContext, "share", url)
374+ snackbar.showSnackbar(linkCopiedMsg)
375+ }
376+ }
377+
378+ // Navigate to a session freshly branched from a message (branchFrom), once it's created.
379+ // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
380+ // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
381+ // a dropped branch-navigation event in the gap.
382+ val branchedMsg = stringResource(R.string.branch_created)
383+ LaunchedEffect(Unit) {
384+ vm.branchEvents.collect { newId ->
385+ showToast(shareContext, branchedMsg)
386+ onOpenSession?.invoke(newId)
387+ }
388+ }
389+
390+ // Stage images shared into the app (via the system share sheet) as attachments.
391+ // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
392+ // while this ChatScreen is already composed — which happens in two-pane mode, where the
393+ // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
394+ // only fire on first composition. consumePendingSharedMedia() atomically drains the
395+ // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
396+ val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
397+ LaunchedEffect(pendingSharedMedia) {
398+ val shared = container.consumePendingSharedMedia()
399+ if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
400+ }
401+
402+ fun doSend() {
403+ if (vm.send(draft)) {
404+ // TextHandleMove (a light tick) is semantically right for a send commit;
405+ // LongPress is reserved for long-press/swipe gestures.
406+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
407+ }
408+ }
409+
410+ BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
411+
412+ Scaffold(
413+ // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
414+ // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
415+ // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
416+ // typing (and the composer's own Enter-to-send handling) is untouched.
417+ modifier = Modifier.onPreviewKeyEvent { ev ->
418+ if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
419+ when {
420+ ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
421+ ev.key == Key.Escape && showPalette -> { showPalette = false; true }
422+ ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
423+ showStopConfirm = true; true
424+ }
425+ else -> false
426+ }
427+ },
428+ topBar = {
429+ TopAppBar(
430+ title = {
431+ val changeLabel = stringResource(R.string.change_model_agent)
432+ Row(
433+ modifier = Modifier
434+ .clickable(enabled = models.isNotEmpty(), role = Role.Button) { showModelPicker = true }
435+ .semantics(mergeDescendants = true) { contentDescription = changeLabel },
436+ verticalAlignment = Alignment.CenterVertically,
437+ ) {
438+ Column(modifier = Modifier.weight(1f, fill = false)) {
439+ // maxLines=1 + Ellipsis so a long session title can't wrap and
440+ // push the top bar to multiple lines, shifting the whole layout.
441+ Text(
442+ sessionTitle ?: sessionLabel,
443+ maxLines = 1,
444+ overflow = TextOverflow.Ellipsis,
445+ )
446+ Text(
447+ subtitle,
448+ style = MaterialTheme.typography.labelSmall,
449+ color = MaterialTheme.colorScheme.onSurfaceVariant,
450+ maxLines = 1,
451+ overflow = TextOverflow.Ellipsis,
452+ )
453+ }
454+ // Visual affordance that the title opens the model picker;
455+ // without it the tappable title is indistinguishable from plain
456+ // text and the picker is effectively undiscoverable.
457+ if (models.isNotEmpty()) {
458+ Icon(
459+ Icons.Filled.KeyboardArrowDown,
460+ contentDescription = null,
461+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
462+ modifier = Modifier.size(20.dp),
463+ )
464+ }
465+ }
466+ },
467+ navigationIcon = {
468+ IconButton(onClick = {
469+ if (running) showExitConfirm = true else onBack()
470+ }) {
471+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
472+ }
473+ },
474+ actions = {
475+ // At-a-glance run status in the top bar. When the user is scrolled
476+ // up (jump-to-latest FAB visible), the input-bar Stop button and the
477+ // trailing "working…" row are off-screen, so a top-bar spinner is the
478+ // only signal the agent is still working.
479+ if (running) {
480+ val workingLabel = stringResource(R.string.working)
481+ CircularProgressIndicator(
482+ Modifier.size(18.dp).semantics { contentDescription = workingLabel },
483+ strokeWidth = 2.dp,
484+ )
485+ }
486+ // Manual refresh: forces an SSE reconnect, which re-seeds messages
487+ // from REST. A recovery path when the stream silently drops and the
488+ // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
489+ // immediate tap feedback — the SSE reconnect may not visibly change
490+ // the connection state when already Connected, so without it the tap
491+ // appears to do nothing.
492+ val refreshLabel = stringResource(R.string.refresh)
493+ IconButton(
494+ onClick = { vm.refreshMessages() },
495+ enabled = activeConnection != null && !refreshing,
496+ ) {
497+ if (refreshing) {
498+ CircularProgressIndicator(
499+ Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
500+ strokeWidth = 2.dp,
501+ )
502+ } else {
503+ Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
504+ }
505+ }
506+ // Overflow menu consolidates the less-frequent actions (share,
507+ // commands, agent, model, rename, delete) so the top bar stays
508+ // scannable on narrow phones — previously 5 icons crowded the bar
509+ // alongside the back button and tappable title. Catalog-loading
510+ // spinners stay inline (next to the overflow) so a load state is
511+ // visible without opening the menu.
512+ val moreLabel = stringResource(R.string.more)
513+ val loadingLabel = stringResource(R.string.loading)
514+ val shareLabel = stringResource(R.string.share_conversation)
515+ val commandsLabel = stringResource(R.string.commands)
516+ val agentLabel = stringResource(R.string.choose_agent)
517+ val modelLabel = stringResource(R.string.choose_model)
518+ val renameLabel = stringResource(R.string.rename_session_chat)
519+ val deleteLabel = stringResource(R.string.delete_session_chat)
520+ val createShareLabel = stringResource(R.string.create_share_link)
521+ val copyShareLabel = stringResource(R.string.copy_share_link)
522+ val stopShareLabel = stringResource(R.string.stop_sharing)
523+ val summarizeLabel = stringResource(R.string.summarize_conversation)
524+ val initLabel = stringResource(R.string.generate_agents_md)
525+ val shellLabel = stringResource(R.string.run_shell_command)
526+ Box {
527+ IconButton(onClick = { showOverflowMenu = true }) {
528+ Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
529+ }
530+ DropdownMenu(
531+ expanded = showOverflowMenu,
532+ onDismissRequest = { showOverflowMenu = false },
533+ ) {
534+ DropdownMenuItem(
535+ text = { Text(shareLabel) },
536+ enabled = hasMessages,
537+ onClick = {
538+ showOverflowMenu = false
539+ scope.launch {
540+ val md = withContext(Dispatchers.Default) {
541+ buildConversationMarkdown(vm.messages.value, sessionTitle)
542+ }
543+ val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
544+ type = "text/markdown"
545+ putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
546+ putExtra(android.content.Intent.EXTRA_TEXT, md)
547+ }
548+ runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
549+ .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
550+ }
551+ },
552+ )
553+ DropdownMenuItem(
554+ text = { Text(commandsLabel) },
555+ enabled = !commandsLoading || commands.isNotEmpty(),
556+ onClick = { showOverflowMenu = false; showCommandPicker = true },
557+ )
558+ DropdownMenuItem(
559+ text = { Text(agentLabel) },
560+ enabled = !agentsLoading || agents.isNotEmpty(),
561+ onClick = { showOverflowMenu = false; showAgentPicker = true },
562+ )
563+ DropdownMenuItem(
564+ text = { Text(modelLabel) },
565+ enabled = !modelsLoading || models.isNotEmpty(),
566+ onClick = { showOverflowMenu = false; showModelPicker = true },
567+ )
568+ androidx.compose.material3.HorizontalDivider()
569+ // Session sharing: create a public link, copy an existing one, or revoke it.
570+ if (shareUrl == null) {
571+ DropdownMenuItem(
572+ text = { Text(createShareLabel) },
573+ enabled = hasMessages,
574+ onClick = { showOverflowMenu = false; vm.shareSession() },
575+ )
576+ } else {
577+ DropdownMenuItem(
578+ text = { Text(copyShareLabel) },
579+ onClick = {
580+ showOverflowMenu = false
581+ shareUrl?.let {
582+ copyToClipboard(shareContext, "share", it)
583+ scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
584+ }
585+ },
586+ )
587+ DropdownMenuItem(
588+ text = { Text(stopShareLabel) },
589+ onClick = { showOverflowMenu = false; vm.unshareSession() },
590+ )
591+ }
592+ DropdownMenuItem(
593+ text = { Text(summarizeLabel) },
594+ enabled = hasMessages && !running,
595+ onClick = { showOverflowMenu = false; vm.summarize() },
596+ )
597+ DropdownMenuItem(
598+ text = { Text(initLabel) },
599+ enabled = !running,
600+ onClick = { showOverflowMenu = false; vm.initProject() },
601+ )
602+ DropdownMenuItem(
603+ text = { Text(shellLabel) },
604+ enabled = !running,
605+ onClick = { showOverflowMenu = false; showShellDialog = true },
606+ )
607+ androidx.compose.material3.HorizontalDivider()
608+ DropdownMenuItem(
609+ text = { Text(renameLabel) },
610+ onClick = { showOverflowMenu = false; showRenameDialog = true },
611+ )
612+ DropdownMenuItem(
613+ text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
614+ onClick = { showOverflowMenu = false; showDeleteDialog = true },
615+ )
616+ }
617+ // While a catalog is initially loading (empty list + loading flag),
618+ // show a tiny inline spinner beside the overflow so the user can see
619+ // a load is in progress without opening the menu. Once loaded the
620+ // spinner disappears; the menu items are always enabled (tapping a
621+ // picker with no items shows the "no models/agents/commands" state).
622+ val catalogLoading = (commandsLoading && commands.isEmpty()) ||
623+ (agentsLoading && agents.isEmpty()) ||
624+ (modelsLoading && models.isEmpty())
625+ if (catalogLoading) {
626+ CircularProgressIndicator(
627+ Modifier
628+ .align(Alignment.TopEnd)
629+ .size(10.dp)
630+ .semantics { contentDescription = loadingLabel },
631+ strokeWidth = 1.dp,
632+ )
633+ }
634+ }
635+ },
636+ )
637+ },
638+ snackbarHost = { SnackbarHost(snackbar) },
639+ bottomBar = {
640+ val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
641+ val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
642+ val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
643+ val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
644+ Column {
645+ // Pinned above the composer so the agent's plan and progress stay visible
646+ // while scrolled up mid-run; renders nothing when there's no plan.
647+ TodoPlanBar(todoPlan)
648+ AnimatedVisibility(visible = reverted) {
649+ RevertBanner(onUndo = { vm.unrevert() })
650+ }
651+ AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
652+ OutboxBanner(
653+ count = queuedOffline.size,
654+ sending = outboxSending,
655+ onFlush = { vm.flushQueued() },
656+ onDiscard = { vm.discardAllQueued() },
657+ )
658+ }
659+ ChatInputBar(
660+ value = draft,
661+ onValueChange = vm::updateDraft,
662+ running = running,
663+ aborting = aborting,
664+ enabled = activeConnection != null,
665+ sendOnEnter = sendOnEnter,
666+ onSend = ::doSend,
667+ onAbort = { showStopConfirm = true },
668+ queuedFollowUp = queuedFollowUp,
669+ onQueueFollowUp = vm::queueFollowUp,
670+ onCancelQueue = { vm.queueFollowUp("") },
671+ focusRequester = inputFocusRequester,
672+ attachments = attachments,
673+ staging = stagingCount > 0,
674+ onRemoveAttachment = vm::removeAttachment,
675+ onPickPhoto = {
676+ photoPicker.launch(
677+ PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
678+ )
679+ },
680+ onPickFile = { filePicker.launch("*/*") },
681+ onCamera = { launchCamera() },
682+ onVoice = { launchVoice() },
683+ )
684+ }
685+ },
686+ ) { padding ->
687+ // Collect messages inside the content lambda so streaming token updates
688+ // recompose only this subtree, not the top bar / input bar / 20+ other
689+ // state reads in the ChatScreen body.
690+ val messages by vm.messages.collectAsStateWithLifecycle()
691+ val listState = rememberLazyListState()
692+ val contentScope = rememberCoroutineScope()
693+ val timeTick = rememberRelativeTimeTick()
694+ // Group messages by day and interleave date separators so a long conversation
695+ // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
696+ // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
697+ // outside the PullToRefreshBox so the auto-scroll effects below can reference
698+ // the same list the LazyColumn renders (separators shift the indices vs. the
699+ // raw messages list, so scroll targets must be in listItems space).
700+ val todayLabel = stringResource(R.string.today)
701+ val yesterdayLabel = stringResource(R.string.yesterday)
702+ val listItems = remember(messages, todayLabel, yesterdayLabel) {
703+ buildMessageListItems(messages, todayLabel, yesterdayLabel)
704+ }
705+ // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
706+ // derivedStateOf and snapshotFlow lambdas below are created once (keyless
707+ // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
708+ // would capture the first composition's list — which is empty, since `messages`
709+ // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
710+ // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
711+ // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
712+ // whose value tracks the latest list.
713+ val currentListItems by rememberUpdatedState(listItems)
714+
715+ // New-content signal for the jump-to-latest FAB: set when content grows while the user
716+ // is scrolled away from the bottom, cleared once they return (see the collector below).
717+ var hasNewContent by remember { mutableStateOf(false) }
718+
719+ val isPinnedToBottom by remember {
720+ derivedStateOf {
721+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
722+ // When a run is active, the LazyColumn has one trailing "__typing"
723+ // item after the last list item. Account for it so "pinned to bottom"
724+ // includes the working indicator — otherwise the pin check targets
725+ // listItems.lastIndex, the typing row sits just below the viewport,
726+ // and the user never sees the progress indicator even when pinned.
727+ val items = currentListItems
728+ val effectiveLast = if (running) items.size else items.lastIndex
729+ lastVisible >= effectiveLast || items.isEmpty()
730+ }
731+ }
732+
733+ // Jump to the newest message once, when the conversation first loads. Guarded by a
734+ // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
735+ // (rotation) — rememberLazyListState restores the user's scroll offset, and an
736+ // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
737+ var didInitialScroll by rememberSaveable { mutableStateOf(false) }
738+ LaunchedEffect(listItems.isNotEmpty()) {
739+ if (listItems.isNotEmpty() && !didInitialScroll) {
740+ // When a run is active the LazyColumn has a trailing "__typing" row at
741+ // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
742+ // running session lands truly pinned to bottom and streaming auto-scroll engages.
743+ listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
744+ didInitialScroll = true
745+ }
746+ }
747+
748+ // When a run starts, the LazyColumn gains a trailing "__typing" row, so
749+ // effectiveLast jumps from listItems.lastIndex to listItems.size and the
750+ // isPinnedToBottom check flips to false the instant you send — freezing
751+ // auto-scroll. If the user was pinned to the last item just before the run
752+ // began, bring the typing row into view so the pin (and streaming follow) is
753+ // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
754+ // recomputed to false by now) so we don't scroll when the user had scrolled up.
755+ LaunchedEffect(running) {
756+ if (running && listItems.isNotEmpty()) {
757+ val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
758+ if (lastVisible >= listItems.lastIndex) {
759+ runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
760+ }
761+ }
762+ }
763+
764+ LaunchedEffect(Unit) {
765+ var prevSize = 0
766+ var prevLen = 0
767+ snapshotFlow {
768+ // Track list size + the streaming length of the last part so we auto-scroll
769+ // as content arrives, plus the pinned flag. A small data class with primitive
770+ // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
771+ // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
772+ // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
773+ // and tool output — not just TextPart — keeps a pinned view following a long
774+ // reasoning/tool block while it streams (previously it stalled at 0).
775+ val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
776+ AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
777+ }.collect { signal ->
778+ if (signal.pinned) {
779+ // Back at the bottom: clear the new-content badge.
780+ hasNewContent = false
781+ if (signal.size > 0) {
782+ // Scroll to the effective last index, including the trailing
783+ // "__typing" row when a run is active so the working indicator
784+ // is brought into view (not just the last message).
785+ val items = currentListItems
786+ val target = if (running) items.size else items.lastIndex
787+ listState.scrollToItem(target)
788+ }
789+ } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
790+ // Content arrived while scrolled up — badge the jump-to-latest FAB.
791+ hasNewContent = true
792+ }
793+ prevSize = signal.size
794+ prevLen = signal.lastTextLength
795+ }
796+ }
797+
798+ CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
799+ // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
800+ // content padding accounts for the bottomBar's raised height, so the message
801+ // list is already above the keyboard. Adding imePadding here would double-apply
802+ // the IME inset and push messages too far up.
803+ Box(modifier = Modifier.fillMaxSize().padding(padding)) {
804+ if (activeConnection == null) {
805+ Column(
806+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
807+ horizontalAlignment = Alignment.CenterHorizontally,
808+ ) {
809+ Text(
810+ stringResource(R.string.not_connected),
811+ color = MaterialTheme.colorScheme.error,
812+ )
813+ Spacer(Modifier.size(12.dp))
814+ Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
815+ if (reconnecting) {
816+ CircularProgressIndicator(
817+ Modifier.size(20.dp),
818+ color = MaterialTheme.colorScheme.onPrimary,
819+ strokeWidth = 2.dp,
820+ )
821+ } else {
822+ Text(stringResource(R.string.reconnect))
823+ }
824+ }
825+ }
826+ } else {
827+ ConnectionBanner(
828+ state = connectionState,
829+ modifier = Modifier.align(Alignment.TopCenter),
830+ isOnline = isOnline,
831+ // On a hard failure, retry by forcing an SSE reconnect (which
832+ // re-seeds from REST). refreshMessages is the right recovery path
833+ // when the connection is present but the stream died; reconnect()
834+ // is the path when the whole connection is gone (handled by the
835+ // separate "Not connected" state below).
836+ onRetry = { vm.refreshMessages() },
837+ )
838+ if (loading && messages.isEmpty()) {
839+ val loadingLabel = stringResource(R.string.loading)
840+ CircularProgressIndicator(
841+ Modifier
842+ .align(Alignment.Center)
843+ .semantics { contentDescription = loadingLabel },
844+ )
845+ } else if (loadError && messages.isEmpty()) {
846+ // A failed load with nothing to show. Distinct from the empty
847+ // conversation state below — the conversation isn't empty, it
848+ // failed to load, and offering "Start a conversation" here is
849+ // misleading. Offer a Retry instead, mirroring SessionListScreen.
850+ Column(
851+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
852+ horizontalAlignment = Alignment.CenterHorizontally,
853+ ) {
854+ Text(
855+ stringResource(R.string.load_messages_failed),
856+ color = MaterialTheme.colorScheme.error,
857+ )
858+ Spacer(Modifier.size(12.dp))
859+ Button(onClick = { vm.refreshMessages() }) {
860+ Text(stringResource(R.string.retry))
861+ }
862+ }
863+ } else if (messages.isEmpty() && running) {
864+ // A run just started but no parts have arrived yet — the empty
865+ // list with only the trailing "working…" row looks broken, so
866+ // surface a clear starting state until the first part streams in.
867+ val workingText = stringResource(R.string.working)
868+ Column(
869+ modifier = Modifier.align(Alignment.Center).padding(24.dp),
870+ horizontalAlignment = Alignment.CenterHorizontally,
871+ ) {
872+ CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
873+ Spacer(Modifier.size(12.dp))
874+ Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
875+ }
876+ } else if (messages.isEmpty()) {
877+ EmptyConversation(
878+ onSuggestion = {
879+ vm.updateDraft(it)
880+ // Focus the input so the user can edit the suggestion before
881+ // sending, instead of having to manually tap the field.
882+ runCatching { inputFocusRequester.requestFocus() }
883+ },
884+ modifier = Modifier.align(Alignment.Center),
885+ )
886+ } else {
887+ // Pull-to-refresh wraps the message list so the user can force an SSE
888+ // reconnect + re-seed with the same gesture they use on the session and
889+ // file lists, instead of hunting for the top-bar refresh icon. The empty
890+ // / loading / error states above stay outside the PTR box since there's
891+ // no list content to pull against.
892+ PullToRefreshBox(
893+ isRefreshing = refreshing,
894+ onRefresh = { vm.refreshMessages() },
895+ modifier = Modifier.fillMaxSize(),
896+ ) {
897+ val lastMessageId = messages.lastOrNull()?.info?.id
898+ // Text-to-speech for reading assistant replies aloud; shuts down when the
899+ // message list leaves composition.
900+ val tts = rememberTtsController()
901+ val speakingMessageId by tts.speakingId
902+ LazyColumn(
903+ state = listState,
904+ modifier = Modifier.fillMaxSize(),
905+ // Extra bottom padding reserves room for the jump-to-latest FAB so it
906+ // never floats over the last message.
907+ contentPadding = PaddingValues(
908+ start = 16.dp,
909+ top = 16.dp,
910+ end = 16.dp,
911+ bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
912+ ),
913+ verticalArrangement = Arrangement.spacedBy(16.dp),
914+ ) {
915+ items(
916+ items = listItems,
917+ key = { it.key },
918+ contentType = { it.contentType },
919+ ) { item ->
920+ when (item) {
921+ is MessageListItem.Separator -> DateSeparator(item.label)
922+ is MessageListItem.Message -> {
923+ val message = item.message
924+ // Only the last (streaming) message needs isRunning — it drives the
925+ // reasoning-block spinner. Passing the live flag to every bubble
926+ // makes all visible messages recompose whenever a run starts or stops.
927+ val modelLabel = remember(message.info, models) {
928+ (message.info as? soy.iko.opencode.data.model.AssistantMessage)
929+ ?.let { resolveModelLabel(it, models) }
930+ }
931+ MessageBubble(
932+ message,
933+ isRunning = running && message.info.id == lastMessageId,
934+ imageContext = imageContext,
935+ modelLabel = modelLabel,
936+ onOpenFile = onOpenFile,
937+ onRevert = { vm.revertTo(message.info.id) },
938+ onEdit = { text ->
939+ // editMessage reverts to before this message (hiding it and
940+ // everything after); the revert banner surfaces the rewind
941+ // with an Undo. Focus + scroll the composer into view like the
942+ // Quote action so the prefilled draft isn't off-screen.
943+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
944+ vm.editMessage(message.info.id, text)
945+ runCatching { inputFocusRequester.requestFocus() }
946+ contentScope.launch {
947+ runCatchingCancellable {
948+ listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
949+ }
950+ }
951+ },
952+ onSpeak = { text -> tts.toggle(message.info.id, text) },
953+ isSpeaking = message.info.id == speakingMessageId,
954+ onQuote = { text ->
955+ vm.quoteReply(text)
956+ runCatching { inputFocusRequester.requestFocus() }
957+ },
958+ onBranch = { text -> vm.branchFrom(text) },
959+ )
960+ }
961+ }
962+ }
963+ if (running) {
964+ item(key = "__typing") {
965+ val workingText = stringResource(R.string.working)
966+ Row(
967+ verticalAlignment = Alignment.CenterVertically,
968+ modifier = Modifier.semantics {
969+ contentDescription = workingText
970+ },
971+ ) {
972+ CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
973+ Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
974+ }
975+ }
976+ }
977+ }
978+ }
979+ // Jump-to-latest affordance when the user has scrolled away during a stream.
980+ AnimatedVisibility(
981+ visible = !isPinnedToBottom && listItems.isNotEmpty(),
982+ modifier = Modifier.align(Alignment.BottomEnd),
983+ ) {
984+ // Badge the FAB when new content arrived while the user was scrolled up, so
985+ // they know there's something new to jump to (cleared once back at bottom).
986+ BadgedBox(
987+ badge = {
988+ if (hasNewContent) {
989+ val newContentLabel = stringResource(R.string.new_messages)
990+ Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
991+ }
992+ },
993+ modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
994+ ) {
995+ ExtendedFloatingActionButton(
996+ onClick = {
997+ hasNewContent = false
998+ if (listItems.isNotEmpty()) {
999+ // Scroll to the effective last index, including the
1000+ // trailing "__typing" row when a run is active.
1001+ val target = if (running) listItems.size else listItems.lastIndex
1002+ contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1003+ }
1004+ },
1005+ icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(R.string.latest)) },
1006+ text = { Text(stringResource(R.string.latest)) },
1007+ )
1008+ }
1009+ }
1010+ }
1011+ }
1012+ }
1013+ }
1014+ }
1015+
1016+ if (showExitConfirm) {
1017+ AlertDialog(
1018+ onDismissRequest = { showExitConfirm = false },
1019+ title = { Text(stringResource(R.string.stop_and_exit_title)) },
1020+ text = { Text(stringResource(R.string.stop_and_exit_text)) },
1021+ confirmButton = {
1022+ TextButton(onClick = {
1023+ showExitConfirm = false
1024+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1025+ vm.abort()
1026+ onBack()
1027+ }) { Text(stringResource(R.string.stop_and_exit)) }
1028+ },
1029+ dismissButton = {
1030+ TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1031+ },
1032+ )
1033+ }
1034+
1035+ if (showStopConfirm) {
1036+ AlertDialog(
1037+ onDismissRequest = { showStopConfirm = false },
1038+ title = { Text(stringResource(R.string.stop_run_title)) },
1039+ text = { Text(stringResource(R.string.stop_run_text)) },
1040+ confirmButton = {
1041+ TextButton(onClick = {
1042+ showStopConfirm = false
1043+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1044+ vm.abort()
1045+ }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1046+ },
1047+ dismissButton = {
1048+ TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1049+ },
1050+ )
1051+ }
1052+
1053+ if (showRenameDialog) {
1054+ RenameSessionChatDialog(
1055+ initialTitle = sessionTitle ?: "",
1056+ onDismiss = { showRenameDialog = false },
1057+ onConfirm = { newName ->
1058+ showRenameDialog = false
1059+ vm.renameSession(newName)
1060+ },
1061+ )
1062+ }
1063+
1064+ if (showDeleteDialog) {
1065+ AlertDialog(
1066+ onDismissRequest = { showDeleteDialog = false },
1067+ title = { Text(stringResource(R.string.delete_session_chat_title)) },
1068+ text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1069+ confirmButton = {
1070+ TextButton(onClick = {
1071+ showDeleteDialog = false
1072+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1073+ vm.deleteSession()
1074+ }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1075+ },
1076+ dismissButton = {
1077+ TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1078+ },
1079+ )
1080+ }
1081+
1082+ if (showShellDialog) {
1083+ ShellCommandDialog(
1084+ onDismiss = { showShellDialog = false },
1085+ onRun = { cmd ->
1086+ showShellDialog = false
1087+ vm.runShell(cmd)
1088+ },
1089+ )
1090+ }
1091+
1092+ if (showModelPicker) {
1093+ ModelPickerSheet(
1094+ options = models,
1095+ selected = selectedModel,
1096+ loading = modelsLoading,
1097+ error = modelsError,
1098+ onSelect = { vm.selectModel(it) },
1099+ onRetry = { vm.reloadModels() },
1100+ onDismiss = { showModelPicker = false },
1101+ )
1102+ }
1103+
1104+ if (showAgentPicker) {
1105+ AgentPickerSheet(
1106+ agents = agents,
1107+ selected = selectedAgent,
1108+ loading = agentsLoading,
1109+ error = agentsError,
1110+ onSelect = { vm.selectAgent(it?.name) },
1111+ onRetry = { vm.reloadAgents() },
1112+ onDismiss = { showAgentPicker = false },
1113+ )
1114+ }
1115+
1116+ if (showCommandPicker) {
1117+ CommandPickerSheet(
1118+ commands = commands,
1119+ loading = commandsLoading,
1120+ error = commandsError,
1121+ onSelect = { vm.runCommand(it) },
1122+ onRetry = { vm.reloadCommands() },
1123+ onDismiss = { showCommandPicker = false },
1124+ )
1125+ }
1126+
1127+ pendingPermission?.let { permission ->
1128+ PermissionDialog(
1129+ permission = permission,
1130+ onRespond = { response -> vm.respondPermission(permission, response) },
1131+ )
1132+ }
1133+
1134+ if (showPalette) {
1135+ CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1136+ }
1137+}
1138+
1139+@Composable
1140+private fun ChatInputBar(
1141+ value: String,
1142+ onValueChange: (String) -> Unit,
1143+ running: Boolean,
1144+ aborting: Boolean,
1145+ enabled: Boolean,
1146+ sendOnEnter: Boolean,
1147+ onSend: () -> Unit,
1148+ onAbort: () -> Unit,
1149+ queuedFollowUp: String?,
1150+ onQueueFollowUp: (String) -> Unit,
1151+ onCancelQueue: () -> Unit,
1152+ focusRequester: androidx.compose.ui.focus.FocusRequester,
1153+ attachments: List<PendingAttachment>,
1154+ staging: Boolean,
1155+ onRemoveAttachment: (String) -> Unit,
1156+ onPickPhoto: () -> Unit,
1157+ onPickFile: () -> Unit,
1158+ onCamera: () -> Unit,
1159+ onVoice: () -> Unit,
1160+) {
1161+ // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1162+ val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1163+ Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1164+ Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1165+ // A queued follow-up replaces the Stop button with a "queued" chip so the
1166+ // user sees their message will be sent when the run finishes, and can cancel.
1167+ if (queuedFollowUp != null) {
1168+ Row(
1169+ modifier = Modifier
1170+ .fillMaxWidth()
1171+ .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1172+ verticalAlignment = Alignment.CenterVertically,
1173+ ) {
1174+ Column(modifier = Modifier.weight(1f)) {
1175+ Text(
1176+ stringResource(R.string.queued),
1177+ style = MaterialTheme.typography.labelSmall,
1178+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1179+ )
1180+ Text(
1181+ queuedFollowUp,
1182+ style = MaterialTheme.typography.bodySmall,
1183+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1184+ maxLines = 1,
1185+ overflow = TextOverflow.Ellipsis,
1186+ )
1187+ }
1188+ TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1189+ Text(stringResource(R.string.cancel))
1190+ }
1191+ }
1192+ }
1193+ // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1194+ AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1195+ Row(
1196+ modifier = Modifier.fillMaxWidth().padding(8.dp),
1197+ verticalAlignment = Alignment.Bottom,
1198+ ) {
1199+ // Attach menu: photo picker, camera, or any file.
1200+ var showAttachMenu by remember { mutableStateOf(false) }
1201+ Box {
1202+ IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1203+ Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1204+ }
1205+ DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1206+ DropdownMenuItem(
1207+ leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1208+ text = { Text(stringResource(R.string.attach_photo)) },
1209+ onClick = { showAttachMenu = false; onPickPhoto() },
1210+ )
1211+ DropdownMenuItem(
1212+ leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1213+ text = { Text(stringResource(R.string.attach_camera)) },
1214+ onClick = { showAttachMenu = false; onCamera() },
1215+ )
1216+ DropdownMenuItem(
1217+ leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1218+ text = { Text(stringResource(R.string.attach_file)) },
1219+ onClick = { showAttachMenu = false; onPickFile() },
1220+ )
1221+ }
1222+ }
1223+ // Voice dictation: appends recognized speech to the draft.
1224+ IconButton(onClick = onVoice, enabled = enabled) {
1225+ Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1226+ }
1227+ OutlinedTextField(
1228+ value = value,
1229+ onValueChange = { v ->
1230+ // Cap input length so a huge paste can't stall the UI. Shares are
1231+ // capped separately in MainActivity; this guards typed/pasted drafts.
1232+ onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1233+ },
1234+ modifier = Modifier
1235+ .weight(1f)
1236+ .focusRequester(focusRequester)
1237+ .testTag("chat_input")
1238+ .onPreviewKeyEvent { event ->
1239+ if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1240+ // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1241+ // With it off, Enter inserts a newline and Ctrl+Enter sends.
1242+ val send = enterShouldSend(
1243+ enabled = enabled,
1244+ hasContent = hasContent,
1245+ sendOnEnter = sendOnEnter,
1246+ shift = event.isShiftPressed,
1247+ ctrl = event.isCtrlPressed,
1248+ )
1249+ if (send) {
1250+ if (running) onQueueFollowUp(value) else onSend()
1251+ true
1252+ } else {
1253+ false
1254+ }
1255+ },
1256+ placeholder = { Text(stringResource(R.string.message_placeholder)) },
1257+ enabled = enabled,
1258+ maxLines = 6,
1259+ // Show a "N / max" countdown once the draft crosses a high fraction of
1260+ // the cap, so the user knows a paste is about to be truncated instead
1261+ // of being silently cut off. Hidden for normal short prompts to avoid
1262+ // clutter under a typical one-line message.
1263+ supportingText = {
1264+ val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1265+ if (value.length >= threshold) {
1266+ Text(
1267+ stringResource(
1268+ R.string.draft_chars_remaining,
1269+ NetworkConfig.maxDraftLengthChars - value.length,
1270+ NetworkConfig.maxDraftLengthChars,
1271+ ),
1272+ style = MaterialTheme.typography.labelSmall,
1273+ color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1274+ else MaterialTheme.colorScheme.onSurfaceVariant,
1275+ )
1276+ }
1277+ },
1278+ keyboardOptions = KeyboardOptions(
1279+ // With send-on-Enter off, expose the platform default action so the soft
1280+ // keyboard shows a newline key (this is a multi-line field) instead of a
1281+ // Send action — otherwise the setting has no effect on soft keyboards and
1282+ // there's no way to type a newline. Hardware Enter is handled separately.
1283+ imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1284+ capitalization = KeyboardCapitalization.Sentences,
1285+ ),
1286+ keyboardActions = KeyboardActions(onSend = {
1287+ if (enabled) {
1288+ // During a run the Send IME action queues a follow-up, but only when
1289+ // there's typed text — queuing "" would cancel an existing queued
1290+ // follow-up (see the Queue button gate). When not running, an
1291+ // attachment-only send is valid, so gate that path on hasContent.
1292+ if (running) {
1293+ if (value.isNotBlank()) onQueueFollowUp(value)
1294+ } else if (hasContent) {
1295+ onSend()
1296+ }
1297+ }
1298+ }),
1299+ )
1300+ ComposerTrailingButton(
1301+ running = running,
1302+ aborting = aborting,
1303+ canSend = enabled && hasContent,
1304+ canQueue = enabled && value.isNotBlank(),
1305+ onSend = onSend,
1306+ onAbort = onAbort,
1307+ onQueue = { onQueueFollowUp(value) },
1308+ )
1309+ }
1310+ }
1311+ }
1312+}
1313+
1314+/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1315+ * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1316+private fun enterShouldSend(
1317+ enabled: Boolean,
1318+ hasContent: Boolean,
1319+ sendOnEnter: Boolean,
1320+ shift: Boolean,
1321+ ctrl: Boolean,
1322+): Boolean = when {
1323+ !enabled || !hasContent -> false
1324+ sendOnEnter -> !shift
1325+ else -> ctrl
1326+}
1327+
1328+/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1329+ * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1330+ * [ChatInputBar] stays under the complexity threshold. */
1331+@Composable
1332+private fun ComposerTrailingButton(
1333+ running: Boolean,
1334+ aborting: Boolean,
1335+ canSend: Boolean,
1336+ canQueue: Boolean,
1337+ onSend: () -> Unit,
1338+ onAbort: () -> Unit,
1339+ onQueue: () -> Unit,
1340+) {
1341+ if (running) {
1342+ Row(verticalAlignment = Alignment.CenterVertically) {
1343+ // While a run is active the trailing action is Stop, so the only send affordance is
1344+ // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1345+ // That leaves a touch-only user with the setting off no way to queue a follow-up
1346+ // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1347+ // there's typed TEXT so queuing is always reachable, without changing the user's
1348+ // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1349+ // canSend, which is also true for an attachment-only composer — because queuing "" just
1350+ // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1351+ // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1352+ if (canQueue) {
1353+ IconButton(
1354+ onClick = onQueue,
1355+ modifier = Modifier.testTag("queue_button"),
1356+ ) {
1357+ Icon(
1358+ Icons.AutoMirrored.Filled.Send,
1359+ contentDescription = stringResource(R.string.queue_followup),
1360+ )
1361+ }
1362+ }
1363+ // Show a spinner while the abort REST call is in flight so the user sees the stop
1364+ // was sent, and disable to prevent a double-tap.
1365+ IconButton(
1366+ onClick = onAbort,
1367+ enabled = !aborting,
1368+ modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1369+ ) {
1370+ if (aborting) {
1371+ val stopLabel = stringResource(R.string.stop)
1372+ CircularProgressIndicator(
1373+ Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1374+ strokeWidth = 2.dp,
1375+ )
1376+ } else {
1377+ Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1378+ }
1379+ }
1380+ }
1381+ } else {
1382+ IconButton(
1383+ onClick = onSend,
1384+ enabled = canSend,
1385+ modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1386+ ) {
1387+ Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1388+ }
1389+ }
1390+}
1391+
1392+@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1393+@Composable
1394+private fun EmptyConversation(
1395+ onSuggestion: (String) -> Unit,
1396+ modifier: Modifier = Modifier,
1397+) {
1398+ // A few example prompts so a first-time user has a one-tap path to their first
1399+ // message instead of staring at a blank input. Tapping a chip fills the draft
1400+ // (without sending) so the user can edit it before sending.
1401+ val suggestions = remember {
1402+ listOf(
1403+ R.string.empty_chat_suggest_1,
1404+ R.string.empty_chat_suggest_2,
1405+ R.string.empty_chat_suggest_3,
1406+ )
1407+ }
1408+ Column(
1409+ modifier = modifier.padding(32.dp),
1410+ horizontalAlignment = Alignment.CenterHorizontally,
1411+ ) {
1412+ Icon(
1413+ Icons.Filled.AutoAwesome,
1414+ contentDescription = null,
1415+ modifier = Modifier.size(48.dp),
1416+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
1417+ )
1418+ Spacer(Modifier.size(16.dp))
1419+ Text(
1420+ stringResource(R.string.empty_chat_title),
1421+ style = MaterialTheme.typography.titleMedium,
1422+ )
1423+ Spacer(Modifier.size(8.dp))
1424+ Text(
1425+ stringResource(R.string.empty_chat_hint),
1426+ style = MaterialTheme.typography.bodyMedium,
1427+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1428+ )
1429+ Spacer(Modifier.size(20.dp))
1430+ // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1431+ // so a longer localized prompt doesn't push the chips off-screen on a phone.
1432+ FlowRow(
1433+ modifier = Modifier.fillMaxWidth(),
1434+ horizontalArrangement = Arrangement.spacedBy(8.dp),
1435+ verticalArrangement = Arrangement.spacedBy(8.dp),
1436+ ) {
1437+ suggestions.forEach { resId ->
1438+ val text = stringResource(resId)
1439+ androidx.compose.material3.AssistChip(
1440+ onClick = { onSuggestion(text) },
1441+ label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1442+ )
1443+ }
1444+ }
1445+ }
1446+}
1447+
1448+/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1449+@Composable
1450+private fun RevertBanner(onUndo: () -> Unit) {
1451+ Surface(
1452+ color = MaterialTheme.colorScheme.tertiaryContainer,
1453+ tonalElevation = 2.dp,
1454+ modifier = Modifier.fillMaxWidth(),
1455+ ) {
1456+ Row(
1457+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1458+ verticalAlignment = Alignment.CenterVertically,
1459+ horizontalArrangement = Arrangement.SpaceBetween,
1460+ ) {
1461+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1462+ Icon(
1463+ Icons.Filled.Restore,
1464+ contentDescription = null,
1465+ tint = MaterialTheme.colorScheme.onTertiaryContainer,
1466+ modifier = Modifier.size(18.dp),
1467+ )
1468+ Text(
1469+ stringResource(R.string.reverted_banner),
1470+ style = MaterialTheme.typography.bodySmall,
1471+ color = MaterialTheme.colorScheme.onTertiaryContainer,
1472+ modifier = Modifier.padding(start = 8.dp),
1473+ )
1474+ }
1475+ TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1476+ }
1477+ }
1478+}
1479+
1480+/** A banner shown while messages composed offline are queued in the outbox, with a
1481+ * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1482+@Composable
1483+private fun OutboxBanner(
1484+ count: Int,
1485+ sending: Boolean,
1486+ onFlush: () -> Unit,
1487+ onDiscard: () -> Unit,
1488+) {
1489+ Surface(
1490+ color = MaterialTheme.colorScheme.secondaryContainer,
1491+ tonalElevation = 2.dp,
1492+ modifier = Modifier.fillMaxWidth(),
1493+ ) {
1494+ Row(
1495+ modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1496+ verticalAlignment = Alignment.CenterVertically,
1497+ horizontalArrangement = Arrangement.SpaceBetween,
1498+ ) {
1499+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1500+ if (sending) {
1501+ CircularProgressIndicator(
1502+ Modifier.size(16.dp),
1503+ strokeWidth = 2.dp,
1504+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1505+ )
1506+ Spacer(Modifier.size(8.dp))
1507+ }
1508+ Text(
1509+ if (sending) {
1510+ stringResource(R.string.outbox_sending)
1511+ } else {
1512+ val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1513+ stringResource(res, count)
1514+ },
1515+ style = MaterialTheme.typography.bodySmall,
1516+ color = MaterialTheme.colorScheme.onSecondaryContainer,
1517+ )
1518+ }
1519+ if (!sending) {
1520+ TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1521+ TextButton(onClick = onDiscard) {
1522+ Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1523+ }
1524+ }
1525+ }
1526+ }
1527+}
1528+
1529+/** Prompt for a one-off shell command to run in the session's worktree. */
1530+@Composable
1531+private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1532+ var command by rememberSaveable { mutableStateOf("") }
1533+ AlertDialog(
1534+ onDismissRequest = onDismiss,
1535+ title = { Text(stringResource(R.string.run_shell_command)) },
1536+ text = {
1537+ OutlinedTextField(
1538+ value = command,
1539+ onValueChange = { command = it },
1540+ modifier = Modifier.fillMaxWidth(),
1541+ placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1542+ label = { Text(stringResource(R.string.shell_command_label)) },
1543+ singleLine = true,
1544+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1545+ keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1546+ )
1547+ },
1548+ confirmButton = {
1549+ TextButton(
1550+ onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1551+ enabled = command.isNotBlank(),
1552+ ) { Text(stringResource(R.string.run)) }
1553+ },
1554+ dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1555+ )
1556+}
1557+
1558+/**
1559+ * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1560+ * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1561+ * equality is structural so `snapshotFlow` emits only when something relevant changes.
1562+ */
1563+private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1564+
1565+/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1566+ * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1567+ * streaming, not just plain assistant text. O(1). */
1568+private fun streamingContentLength(part: Part?): Int = when (part) {
1569+ is TextPart -> part.text.length
1570+ is ReasoningPart -> part.text.length
1571+ is ToolPart -> when (val st = part.state) {
1572+ is ToolCompleted -> st.output?.length ?: 0
1573+ is ToolError -> st.error?.length ?: 0
1574+ is ToolRunning -> st.title?.length ?: 0
1575+ else -> 0
1576+ }
1577+ else -> 0
1578+}
1579+
1580+/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1581+ * dialog but lives in the chat screen so the user can rename without backing out to
1582+ * the list. Pre-filled with the current title; the cap matches the list dialog. */
1583+@Composable
1584+private fun RenameSessionChatDialog(
1585+ initialTitle: String,
1586+ onDismiss: () -> Unit,
1587+ onConfirm: (String) -> Unit,
1588+) {
1589+ // Seed the field once (no key input) so a later external title change — e.g. opencode
1590+ // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1591+ // doesn't re-initialize the box and discard the user's in-progress edit.
1592+ var title by rememberSaveable { mutableStateOf(initialTitle) }
1593+ AlertDialog(
1594+ onDismissRequest = onDismiss,
1595+ title = { Text(stringResource(R.string.rename_session_chat)) },
1596+ text = {
1597+ OutlinedTextField(
1598+ value = title,
1599+ onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1600+ modifier = Modifier.fillMaxWidth(),
1601+ placeholder = { Text(stringResource(R.string.session_title_hint)) },
1602+ label = { Text(stringResource(R.string.rename_session_chat)) },
1603+ singleLine = true,
1604+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1605+ keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1606+ )
1607+ },
1608+ confirmButton = {
1609+ TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1610+ Text(stringResource(R.string.save))
1611+ }
1612+ },
1613+ dismissButton = {
1614+ TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1615+ },
1616+ )
1617+}
1618+
1619+/**
1620+ * A single item in the chat message list — either a [Message] bubble or a day
1621+ * [Separator] inserted before the first message of a new day. The separator shifts
1622+ * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1623+ * the [List] of these items (not `messages.size`/`lastIndex`).
1624+ */
1625+private sealed interface MessageListItem {
1626+ val key: Any
1627+ val contentType: Any
1628+
1629+ data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1630+ override val contentType: Any get() = message.info::class
1631+ }
1632+
1633+ data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1634+ // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1635+ // can share a label (e.g. an untimestamped message — empty label — between two
1636+ // same-day messages, or two untimestamped groups), and a label-only key would
1637+ // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1638+ // stable for a given message ordering so slots aren't needlessly recreated.
1639+ override val key: Any get() = "sep_${ordinal}_$label"
1640+ // Separators share a contentType so the LazyColumn can recycle their slots.
1641+ override val contentType: Any get() = "separator"
1642+ }
1643+}
1644+
1645+/**
1646+ * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1647+ * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1648+ * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1649+ * Messages with no timestamp are grouped under an empty-label separator only if they
1650+ * start the list, so a server that omits timestamps doesn't suppress the first divider.
1651+ *
1652+ * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1653+ * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1654+ * labels; older days fall back to a locale-stable medium-date format.
1655+ */
1656+private fun buildMessageListItems(
1657+ messages: List<MessageWithParts>,
1658+ todayLabel: String,
1659+ yesterdayLabel: String,
1660+): List<MessageListItem> {
1661+ if (messages.isEmpty()) return emptyList()
1662+ val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1663+ val dateFmt = mediumDateFormat()
1664+ val result = ArrayList<MessageListItem>(messages.size + 4)
1665+ val seenKeys = HashSet<String>(messages.size * 2)
1666+ var lastDayKey: String? = null
1667+ var sepOrdinal = 0
1668+ var emptyIdOrdinal = 0
1669+ var first = true
1670+ for (message in messages) {
1671+ val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1672+ val dayKey = ts?.let { dayKey(it) } ?: ""
1673+ // Emit a separator before the very first message (so a leading un-timestamped message
1674+ // still gets the first divider, empty label and all), and thereafter only when crossing
1675+ // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1676+ // neither emits its own separator nor resets the day — otherwise a following same-day
1677+ // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1678+ if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1679+ result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1680+ }
1681+ if (dayKey.isNotEmpty()) lastDayKey = dayKey
1682+ first = false
1683+ // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1684+ // empty id — and the reducer intentionally keeps several such messages as distinct
1685+ // holders — so give each a stable synthetic key and defensively de-collide any remaining
1686+ // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1687+ var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1688+ if (!seenKeys.add(key)) {
1689+ var suffix = 1
1690+ while (!seenKeys.add("$key#$suffix")) suffix++
1691+ key = "$key#$suffix"
1692+ }
1693+ result.add(MessageListItem.Message(message, key))
1694+ }
1695+ return result
1696+}
1697+
1698+/**
1699+ * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1700+ *
1701+ * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1702+ * whole `messages` list, which must stay so the live message's fresh parts render), so a
1703+ * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1704+ * every message on every token. Message timestamps are immutable once assigned, so we
1705+ * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1706+ * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1707+ * thread during composition, so the coarse lock is uncontended.
1708+ */
1709+private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1710+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1711+}
1712+
1713+private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1714+ dayKeyCache.getOrPut(epochMillis) {
1715+ java.time.Instant.ofEpochMilli(epochMillis)
1716+ .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1717+ }
1718+}
1719+
1720+// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1721+// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1722+// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1723+private var cachedDateFmt: java.text.DateFormat? = null
1724+private var cachedDateFmtLocale: java.util.Locale? = null
1725+
1726+private fun mediumDateFormat(): java.text.DateFormat {
1727+ val locale = java.util.Locale.getDefault()
1728+ val existing = cachedDateFmt
1729+ if (existing != null && cachedDateFmtLocale == locale) return existing
1730+ return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1731+ cachedDateFmt = it
1732+ cachedDateFmtLocale = locale
1733+ }
1734+}
1735+
1736+/**
1737+ * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1738+ * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1739+ * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1740+ * messages.
1741+ */
1742+private fun dayLabel(
1743+ dayKey: String,
1744+ ts: Long,
1745+ today: java.time.LocalDate,
1746+ todayLabel: String,
1747+ yesterdayLabel: String,
1748+ dateFmt: java.text.DateFormat,
1749+): String {
1750+ if (dayKey.isEmpty()) return ""
1751+ val epochDay = dayKey.toLongOrNull() ?: return ""
1752+ val date = java.time.LocalDate.ofEpochDay(epochDay)
1753+ return when {
1754+ date == today -> todayLabel
1755+ date == today.minusDays(1) -> yesterdayLabel
1756+ else -> dateFmt.format(java.util.Date(ts))
1757+ }
1758+}
1759+
1760+/**
1761+ * A centered day divider in the message list. Renders nothing for an empty label
1762+ * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1763+ */
1764+@Composable
1765+private fun DateSeparator(label: String) {
1766+ if (label.isBlank()) return
1767+ Row(
1768+ modifier = Modifier.fillMaxWidth(),
1769+ horizontalArrangement = Arrangement.Center,
1770+ ) {
1771+ Surface(
1772+ color = MaterialTheme.colorScheme.surfaceVariant,
1773+ shape = MaterialTheme.shapes.small,
1774+ ) {
1775+ Text(
1776+ label,
1777+ style = MaterialTheme.typography.labelSmall,
1778+ color = MaterialTheme.colorScheme.onSurfaceVariant,
1779+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
1780+ )
1781+ }
1782+ }
1783+}