@@ -1,1991 +0,0 @@
1−@file:Suppress("TooManyFunctions")
3−package soy.iko.opencode.ui.chat
5−import android.app.Activity
6−import android.content.Intent
8−import android.speech.RecognizerIntent
9−import androidx.activity.compose.BackHandler
10−import androidx.activity.compose.rememberLauncherForActivityResult
11−import androidx.activity.result.PickVisualMediaRequest
12−import androidx.activity.result.contract.ActivityResultContracts
13−import androidx.compose.animation.AnimatedVisibility
14−import androidx.compose.foundation.clickable
15−import androidx.compose.foundation.layout.Arrangement
16−import androidx.compose.foundation.layout.Box
17−import androidx.compose.foundation.layout.Column
18−import androidx.compose.foundation.layout.FlowRow
19−import androidx.compose.foundation.layout.PaddingValues
20−import androidx.compose.foundation.layout.Row
21−import androidx.compose.foundation.layout.Spacer
22−import androidx.compose.foundation.layout.WindowInsets
23−import androidx.compose.foundation.layout.fillMaxSize
24−import androidx.compose.foundation.layout.fillMaxWidth
25−import androidx.compose.foundation.layout.imePadding
26−import androidx.compose.foundation.layout.navigationBars
27−import androidx.compose.foundation.layout.padding
28−import androidx.compose.foundation.layout.size
29−import androidx.compose.foundation.layout.union
30−import androidx.compose.foundation.layout.widthIn
31−import androidx.compose.foundation.layout.windowInsetsPadding
32−import androidx.compose.foundation.layout.wrapContentWidth
33−import androidx.compose.foundation.lazy.LazyColumn
34−import androidx.compose.foundation.lazy.items
35−import androidx.compose.foundation.lazy.rememberLazyListState
36−import androidx.compose.material.icons.Icons
37−import androidx.compose.material.icons.automirrored.filled.ArrowBack
38−import androidx.compose.material.icons.automirrored.filled.Send
39−import androidx.compose.material.icons.filled.Add
40−import androidx.compose.material.icons.filled.AutoAwesome
41−import androidx.compose.material.icons.filled.Delete
42−import androidx.compose.material.icons.filled.Description
43−import androidx.compose.material.icons.filled.Edit
44−import androidx.compose.material.icons.filled.Expand
45−import androidx.compose.material.icons.filled.KeyboardArrowDown
46−import androidx.compose.material.icons.filled.KeyboardArrowUp
47−import androidx.compose.material.icons.filled.Mic
48−import androidx.compose.material.icons.filled.MoreVert
49−import androidx.compose.material.icons.filled.PhotoCamera
50−import androidx.compose.material.icons.filled.PhotoLibrary
51−import androidx.compose.material.icons.filled.Refresh
52−import androidx.compose.material.icons.filled.Restore
53−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
54−import androidx.compose.material.icons.filled.Schedule
55−import androidx.compose.material.icons.filled.Stop
56−import androidx.compose.material3.AlertDialog
57−import androidx.compose.material3.Badge
58−import androidx.compose.material3.BadgedBox
59−import androidx.compose.material3.Button
60−import androidx.compose.material3.CircularProgressIndicator
61−import androidx.compose.material3.SmallFloatingActionButton
62−import androidx.compose.material3.DropdownMenu
63−import androidx.compose.material3.DropdownMenuItem
64−import androidx.compose.material3.ExperimentalMaterial3Api
65−import androidx.compose.material3.ExtendedFloatingActionButton
66−import androidx.compose.material3.FloatingActionButton
67−import androidx.compose.material3.Icon
68−import androidx.compose.material3.IconButton
69−import androidx.compose.material3.MaterialTheme
70−import androidx.compose.material3.OutlinedTextField
71−import androidx.compose.material3.Scaffold
72−import androidx.compose.material3.SnackbarHost
73−import androidx.compose.material3.SnackbarHostState
74−import androidx.compose.material3.Surface
75−import androidx.compose.material3.Text
76−import androidx.compose.material3.TextButton
77−import androidx.compose.material3.TopAppBar
78−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
79−import androidx.compose.runtime.Composable
80−import androidx.compose.runtime.CompositionLocalProvider
81−import androidx.compose.runtime.DisposableEffect
82−import androidx.compose.runtime.LaunchedEffect
83−import androidx.compose.runtime.derivedStateOf
84−import androidx.compose.runtime.getValue
85−import androidx.compose.runtime.mutableStateOf
86−import androidx.compose.runtime.remember
87−import androidx.compose.runtime.rememberCoroutineScope
88−import androidx.compose.runtime.rememberUpdatedState
89−import androidx.compose.runtime.saveable.rememberSaveable
90−import androidx.compose.runtime.setValue
91−import androidx.compose.runtime.snapshotFlow
92−import androidx.compose.foundation.text.KeyboardActions
93−import androidx.compose.foundation.text.KeyboardOptions
94−import androidx.compose.ui.text.input.KeyboardCapitalization
95−import androidx.compose.ui.Alignment
96−import androidx.compose.ui.Modifier
97−import androidx.compose.ui.focus.focusRequester
98−import androidx.compose.ui.input.key.Key
99−import androidx.compose.ui.input.key.KeyEventType
100−import androidx.compose.ui.input.key.isCtrlPressed
101−import androidx.compose.ui.input.key.isShiftPressed
102−import androidx.compose.ui.input.key.key
103−import androidx.compose.ui.input.key.onPreviewKeyEvent
104−import androidx.compose.ui.input.key.type
105−import androidx.compose.ui.platform.LocalContext
106−import androidx.compose.ui.platform.LocalHapticFeedback
107−import androidx.compose.ui.platform.LocalView
108−import androidx.compose.ui.platform.testTag
109−import androidx.compose.ui.res.stringResource
110−import androidx.compose.ui.semantics.Role
111−import androidx.compose.ui.semantics.contentDescription
112−import androidx.compose.ui.semantics.semantics
113−import androidx.compose.ui.text.input.ImeAction
114−import androidx.compose.ui.text.style.TextOverflow
115−import androidx.compose.ui.unit.dp
116−import androidx.lifecycle.compose.collectAsStateWithLifecycle
117−import androidx.lifecycle.viewmodel.compose.viewModel
118−import kotlinx.coroutines.Dispatchers
119−import kotlinx.coroutines.flow.distinctUntilChanged
120−import kotlinx.coroutines.launch
121−import kotlinx.coroutines.withContext
122−import soy.iko.opencode.data.model.Part
123−import soy.iko.opencode.data.model.MessageWithParts
124−import soy.iko.opencode.data.model.ReasoningPart
125−import soy.iko.opencode.data.model.TextPart
126−import soy.iko.opencode.data.model.ToolCompleted
127−import soy.iko.opencode.data.model.ToolError
128−import soy.iko.opencode.data.model.ToolPart
129−import soy.iko.opencode.data.model.ToolRunning
130−import soy.iko.opencode.data.network.EventStreamClient
131−import soy.iko.opencode.data.network.NetworkConfig
132−import soy.iko.opencode.di.AppContainer
133−import soy.iko.opencode.R
134−import soy.iko.opencode.ui.components.CommandPalette
135−import soy.iko.opencode.ui.components.ConnectionBanner
136−import soy.iko.opencode.ui.components.PaletteAction
137−import soy.iko.opencode.ui.components.copyToClipboard
138−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
139−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
140−import soy.iko.opencode.ui.components.showToast
141−import soy.iko.opencode.ui.components.toImageContext
142−import soy.iko.opencode.ui.vmFactory
143−import soy.iko.opencode.util.runCatchingCancellable
145−@OptIn(ExperimentalMaterial3Api::class)
148− container: AppContainer,
151− onOpenFile: ((String) -> Unit)? = null,
152− onOpenSession: ((String) -> Unit)? = null,
154− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
155− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
156− val running by vm.running.collectAsStateWithLifecycle()
157− val aborting by vm.aborting.collectAsStateWithLifecycle()
158− val loading by vm.loading.collectAsStateWithLifecycle()
159− val loadError by vm.loadError.collectAsStateWithLifecycle()
160− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
161− val models by vm.models.collectAsStateWithLifecycle()
162− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
163− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
164− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
165− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
166− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
167− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
168− val agents by vm.agents.collectAsStateWithLifecycle()
169− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
170− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
171− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
172− val commands by vm.commands.collectAsStateWithLifecycle()
173− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
174− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
175− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
176− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
177− val draft by vm.draft.collectAsStateWithLifecycle()
178− val attachments by vm.attachments.collectAsStateWithLifecycle()
179− val reverted by vm.reverted.collectAsStateWithLifecycle()
180− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
181− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
182− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
183− val isOnline by container.isOnline.collectAsStateWithLifecycle()
184− val haptics = LocalHapticFeedback.current
185− val scope = rememberCoroutineScope()
186− val shareContext = LocalContext.current
187− val defaultShareSubject = stringResource(R.string.share_subject)
188− val sessionLabel = stringResource(R.string.session)
189− val defaultModelLabel = stringResource(R.string.default_model)
190− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
192− append(selectedModel?.modelLabel ?: defaultModelLabel)
193− selectedAgent?.let { append(" · $it") }
197− // Connection profile (with auth) for rendering inline image attachments.
198− // Collect as state so a server switch recomposes the image context.
199− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
200− val imageContext = remember(activeConnection?.profile) {
201− activeConnection?.profile?.toImageContext()
204− // Mark this session as read while the user is viewing it; clear on leave so new
205− // background activity can badge it again.
206− DisposableEffect(sessionId) {
207− container.setCurrentSession(sessionId)
208− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
211− // Navigate away when the session is deleted via SSE so the user isn't left
212− // on a zombie screen showing a conversation that no longer exists. Surface a
213− // toast (not a snackbar) because the screen is about to be popped — a snackbar
214− // would be torn down before the user could read it, while a toast survives.
215− // Covers both SSE-driven deletion (deleted on another device) and a user-
216− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
217− // sets the same flag on success).
218− val deletedContext = LocalContext.current
219− LaunchedEffect(sessionDeleted) {
220− if (sessionDeleted) {
221− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
226− val snackbar = remember { SnackbarHostState() }
227− val retryLabel = stringResource(R.string.retry)
228− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
229− var showModelPicker by rememberSaveable { mutableStateOf(false) }
230− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
231− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
232− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
233− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
234− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
235− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
236− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
237− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
238− var showShellDialog by rememberSaveable { mutableStateOf(false) }
239− var showPalette by rememberSaveable { mutableStateOf(false) }
240− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
241− // a confirmation dialog (from both the overflow menu and the command palette).
242− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
243− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
245− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
246− // action list doesn't need a Composable context. Actions map to the same handlers the
247− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
248− val paletteModelLabel = stringResource(R.string.palette_switch_model)
249− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
250− val paletteCommandLabel = stringResource(R.string.palette_run_command)
251− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
252− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
253− val paletteShellLabel = stringResource(R.string.run_shell_command)
254− val paletteActions = remember(
255− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
256− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
259− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
260− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
261− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
262− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
263− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
264− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
268− // Keep the screen awake while the agent is working in *this* session. The foreground
269− // service that holds process priority during a run is managed app-wide off
270− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
271− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
272− // SSE stream before the completion notification fires.
273− val currentView = LocalView.current
274− val appContext = LocalContext.current.applicationContext
275− DisposableEffect(running) {
276− currentView.keepScreenOn = running
277− onDispose { currentView.keepScreenOn = false }
280− LaunchedEffect(Unit) {
281− vm.errorEvents.collect { event ->
282− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
283− // message-load failure) would silently re-submit the last prompt on tap.
284− val result = if (event.retryable) {
285− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
287− snackbar.showSnackbar(event.message)
289− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
293− // --- Attachments, voice, and share-link plumbing ---
294− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
295− val attachFailedMsg = stringResource(R.string.attachment_failed)
296− val attachLimitMsg = stringResource(R.string.attachment_limit)
297− val noCameraMsg = stringResource(R.string.no_camera_app)
298− val noVoiceMsg = stringResource(R.string.no_voice_app)
299− val voicePrompt = stringResource(R.string.voice_prompt)
300− val linkCopiedMsg = stringResource(R.string.link_copied)
302− // Count of picks currently being read + base64-encoded off the main thread, so the
303− // composer can show a staging placeholder immediately (chips only materialize once done).
304− var stagingCount by remember { mutableStateOf(0) }
306− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
307− // per-prompt count cap and surfacing per-file errors without aborting the batch.
308− fun stageUris(uris: List<Uri>) {
309− if (uris.isEmpty()) return
314− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
315− snackbar.showSnackbar(attachLimitMsg)
318− when (val result = uri.toAttachmentResult(appContext)) {
319− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
320− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
321− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
330− val photoPicker = rememberLauncherForActivityResult(
331− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
332− ) { uris -> stageUris(uris) }
334− val filePicker = rememberLauncherForActivityResult(
335− ActivityResultContracts.GetMultipleContents(),
336− ) { uris -> stageUris(uris) }
338− // Uri survives a config change mid-capture so the TakePicture result still resolves.
339− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
340− val cameraLauncher = rememberLauncherForActivityResult(
341− ActivityResultContracts.TakePicture(),
343− val uri = pendingCaptureUri
344− pendingCaptureUri = null
345− if (success && uri != null) stageUris(listOf(uri))
348− val voiceLauncher = rememberLauncherForActivityResult(
349− ActivityResultContracts.StartActivityForResult(),
351− if (result.resultCode == Activity.RESULT_OK) {
352− val spoken = result.data
353− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
355− ?.takeIf { it.isNotBlank() }
356− if (spoken != null) {
357− // Append to the existing draft rather than replacing, so dictation adds to
358− // whatever the user already typed.
359− val current = vm.draft.value
360− val combined = if (current.isBlank()) spoken else "$current $spoken"
361− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
366− fun launchCamera() {
367− val uri = newCameraCaptureUri(appContext)
369− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
372− pendingCaptureUri = uri
373− runCatching { cameraLauncher.launch(uri) }
374− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
378− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
379− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
380− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
382− runCatching { voiceLauncher.launch(intent) }
383− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
386− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
387− LaunchedEffect(Unit) {
388− vm.shareLinkEvents.collect { url ->
389− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
390− snackbar.showSnackbar(linkCopiedMsg)
394− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
395− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
396− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
397− // a dropped branch-navigation event in the gap.
398− val branchedMsg = stringResource(R.string.branch_created)
399− LaunchedEffect(Unit) {
400− vm.branchEvents.collect { newId ->
401− showToast(shareContext, branchedMsg)
402− onOpenSession?.invoke(newId)
406− // Stage images shared into the app (via the system share sheet) as attachments.
407− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
408− // while this ChatScreen is already composed — which happens in two-pane mode, where the
409− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
410− // only fire on first composition. consumePendingSharedMedia() atomically drains the
411− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
412− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
413− LaunchedEffect(pendingSharedMedia) {
414− val shared = container.consumePendingSharedMedia()
415− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
419− if (vm.send(draft)) {
420− // TextHandleMove (a light tick) is semantically right for a send commit;
421− // LongPress is reserved for long-press/swipe gestures.
422− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
426− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
429− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
430− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
431− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
432− // typing (and the composer's own Enter-to-send handling) is untouched.
433− modifier = Modifier.onPreviewKeyEvent { ev ->
434− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
436− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
437− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
438− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
439− showStopConfirm = true; true
447− val changeLabel = stringResource(R.string.change_model_agent)
448− // The subtitle reads "model · agent", so tapping the title offers *both*
449− // — a small menu picks which picker to open. Previously the tap went
450− // straight to the model picker, leaving the agent changeable only via
451− // the overflow menu despite the title implying otherwise.
454− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
455− // node; the click label rides on `clickable` (onClickLabel) instead of
456− // an explicit contentDescription, which would have SUPPRESSED the child
457− // Texts and announced only "Change model and agent".
460− enabled = models.isNotEmpty(),
462− onClickLabel = changeLabel,
463− ) { showTitleMenu = true }
464− .semantics(mergeDescendants = true) {},
465− verticalAlignment = Alignment.CenterVertically,
467− Column(modifier = Modifier.weight(1f, fill = false)) {
468− // maxLines=1 + Ellipsis so a long session title can't wrap and
469− // push the top bar to multiple lines, shifting the whole layout.
471− sessionTitle ?: sessionLabel,
473− overflow = TextOverflow.Ellipsis,
477− style = MaterialTheme.typography.labelSmall,
478− color = MaterialTheme.colorScheme.onSurfaceVariant,
480− overflow = TextOverflow.Ellipsis,
483− // Visual affordance that the title is tappable; without it the
484− // title is indistinguishable from plain text and the pickers are
485− // effectively undiscoverable.
486− if (models.isNotEmpty()) {
488− Icons.Filled.KeyboardArrowDown,
489− contentDescription = null,
490− tint = MaterialTheme.colorScheme.onSurfaceVariant,
491− modifier = Modifier.size(20.dp),
495− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
497− text = { Text(stringResource(R.string.palette_switch_model)) },
498− enabled = !modelsLoading || models.isNotEmpty(),
499− onClick = { showTitleMenu = false; showModelPicker = true },
502− text = { Text(stringResource(R.string.palette_choose_agent)) },
503− enabled = !agentsLoading || agents.isNotEmpty(),
504− onClick = { showTitleMenu = false; showAgentPicker = true },
510− IconButton(onClick = {
511− if (running) showExitConfirm = true else onBack()
513− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
517− // At-a-glance run status in the top bar. When the user is scrolled
518− // up (jump-to-latest FAB visible), the input-bar Stop button and the
519− // trailing "working…" row are off-screen, so a top-bar spinner is the
520− // only signal the agent is still working.
522− val workingLabel = stringResource(R.string.working)
523− CircularProgressIndicator(
524− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
528− // Manual refresh: forces an SSE reconnect, which re-seeds messages
529− // from REST. A recovery path when the stream silently drops and the
530− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
531− // immediate tap feedback — the SSE reconnect may not visibly change
532− // the connection state when already Connected, so without it the tap
533− // appears to do nothing.
534− val refreshLabel = stringResource(R.string.refresh)
536− onClick = { vm.refreshMessages() },
537− enabled = activeConnection != null && !refreshing,
540− CircularProgressIndicator(
541− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
545− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
548− // Overflow menu consolidates the less-frequent actions (share,
549− // commands, agent, model, rename, delete) so the top bar stays
550− // scannable on narrow phones — previously 5 icons crowded the bar
551− // alongside the back button and tappable title. Catalog-loading
552− // spinners stay inline (next to the overflow) so a load state is
553− // visible without opening the menu.
554− val moreLabel = stringResource(R.string.more)
555− val loadingLabel = stringResource(R.string.loading)
556− val shareLabel = stringResource(R.string.share_conversation)
557− val commandsLabel = stringResource(R.string.commands)
558− val renameLabel = stringResource(R.string.rename_session_chat)
559− val deleteLabel = stringResource(R.string.delete_session_chat)
560− val createShareLabel = stringResource(R.string.create_share_link)
561− val copyShareLabel = stringResource(R.string.copy_share_link)
562− val stopShareLabel = stringResource(R.string.stop_sharing)
563− val summarizeLabel = stringResource(R.string.summarize_conversation)
564− val initLabel = stringResource(R.string.generate_agents_md)
565− val shellLabel = stringResource(R.string.run_shell_command)
567− IconButton(onClick = { showOverflowMenu = true }) {
568− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
571− expanded = showOverflowMenu,
572− onDismissRequest = { showOverflowMenu = false },
575− text = { Text(shareLabel) },
576− enabled = hasMessages,
578− showOverflowMenu = false
580− val md = withContext(Dispatchers.Default) {
581− buildConversationMarkdown(vm.messages.value, sessionTitle)
583− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
584− type = "text/markdown"
585− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
586− putExtra(android.content.Intent.EXTRA_TEXT, md)
588− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
589− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
594− text = { Text(commandsLabel) },
595− enabled = !commandsLoading || commands.isNotEmpty(),
596− onClick = { showOverflowMenu = false; showCommandPicker = true },
598− androidx.compose.material3.HorizontalDivider()
599− // Session sharing: create a public link, copy an existing one, or revoke it.
600− if (shareUrl == null) {
602− text = { Text(createShareLabel) },
603− enabled = hasMessages,
604− onClick = { showOverflowMenu = false; vm.shareSession() },
608− text = { Text(copyShareLabel) },
610− showOverflowMenu = false
612− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
613− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
618− text = { Text(stopShareLabel) },
619− onClick = { showOverflowMenu = false; vm.unshareSession() },
623− text = { Text(summarizeLabel) },
624− enabled = hasMessages && !running,
625− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
628− text = { Text(initLabel) },
630− onClick = { showOverflowMenu = false; showInitConfirm = true },
633− text = { Text(shellLabel) },
635− onClick = { showOverflowMenu = false; showShellDialog = true },
637− androidx.compose.material3.HorizontalDivider()
639− text = { Text(renameLabel) },
640− onClick = { showOverflowMenu = false; showRenameDialog = true },
643− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
644− onClick = { showOverflowMenu = false; showDeleteDialog = true },
647− // While a catalog is initially loading (empty list + loading flag),
648− // show a tiny inline spinner beside the overflow so the user can see
649− // a load is in progress without opening the menu. Once loaded the
650− // spinner disappears; the menu items are always enabled (tapping a
651− // picker with no items shows the "no models/agents/commands" state).
652− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
653− (agentsLoading && agents.isEmpty()) ||
654− (modelsLoading && models.isEmpty())
655− if (catalogLoading) {
656− CircularProgressIndicator(
658− .align(Alignment.TopEnd)
660− .semantics { contentDescription = loadingLabel },
668− snackbarHost = { SnackbarHost(snackbar) },
670− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
671− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
672− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
673− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
675− // Pinned above the composer so the agent's plan and progress stay visible
676− // while scrolled up mid-run; renders nothing when there's no plan.
677− TodoPlanBar(todoPlan)
678− AnimatedVisibility(visible = reverted) {
679− RevertBanner(onUndo = { vm.unrevert() })
681− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
683− count = queuedOffline.size,
684− sending = outboxSending,
685− onFlush = { vm.flushQueued() },
686− onDiscard = { vm.discardAllQueued() },
691− onValueChange = vm::updateDraft,
693− aborting = aborting,
694− enabled = activeConnection != null,
695− sendOnEnter = sendOnEnter,
697− onAbort = { showStopConfirm = true },
698− queuedFollowUp = queuedFollowUp,
699− onQueueFollowUp = vm::queueFollowUp,
700− onCancelQueue = { vm.queueFollowUp("") },
701− focusRequester = inputFocusRequester,
702− attachments = attachments,
703− staging = stagingCount > 0,
704− onRemoveAttachment = vm::removeAttachment,
707− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
710− onPickFile = { filePicker.launch("*/*") },
711− onCamera = { launchCamera() },
712− onVoice = { launchVoice() },
717− // Collect messages inside the content lambda so streaming token updates
718− // recompose only this subtree, not the top bar / input bar / 20+ other
719− // state reads in the ChatScreen body.
720− val messages by vm.messages.collectAsStateWithLifecycle()
721− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
722− val listState = rememberLazyListState()
723− val contentScope = rememberCoroutineScope()
724− val timeTick = rememberRelativeTimeTick()
725− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
726− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
727− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
728− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
729− androidx.compose.runtime.LaunchedEffect(listState) {
730− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
731− .distinctUntilChanged()
732− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
733− } // Group messages by day and interleave date separators so a long conversation
734− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
735− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
736− // outside the PullToRefreshBox so the auto-scroll effects below can reference
737− // the same list the LazyColumn renders (separators shift the indices vs. the
738− // raw messages list, so scroll targets must be in listItems space).
739− val todayLabel = stringResource(R.string.today)
740− val yesterdayLabel = stringResource(R.string.yesterday)
741− val listItems = remember(messages, todayLabel, yesterdayLabel) {
742− buildMessageListItems(messages, todayLabel, yesterdayLabel)
744− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
745− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
746− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
747− // would capture the first composition's list — which is empty, since `messages`
748− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
749− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
750− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
751− // whose value tracks the latest list.
752− val currentListItems by rememberUpdatedState(listItems)
754− // New-content signal for the jump-to-latest FAB: set when content grows while the user
755− // is scrolled away from the bottom, cleared once they return (see the collector below).
756− var hasNewContent by remember { mutableStateOf(false) }
758− val isPinnedToBottom by remember {
760− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
761− // When a run is active, the LazyColumn has one trailing "__typing"
762− // item after the last list item. Account for it so "pinned to bottom"
763− // includes the working indicator — otherwise the pin check targets
764− // listItems.lastIndex, the typing row sits just below the viewport,
765− // and the user never sees the progress indicator even when pinned.
766− val items = currentListItems
767− val effectiveLast = if (running) items.size else items.lastIndex
768− lastVisible >= effectiveLast || items.isEmpty()
772− // Jump to the newest message once, when the conversation first loads. Guarded by a
773− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
774− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
775− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
776− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
777− LaunchedEffect(listItems.isNotEmpty()) {
778− if (listItems.isNotEmpty() && !didInitialScroll) {
779− // When a run is active the LazyColumn has a trailing "__typing" row at
780− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
781− // running session lands truly pinned to bottom and streaming auto-scroll engages.
782− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
783− didInitialScroll = true
787− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
788− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
789− // isPinnedToBottom check flips to false the instant you send — freezing
790− // auto-scroll. If the user was pinned to the last item just before the run
791− // began, bring the typing row into view so the pin (and streaming follow) is
792− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
793− // recomputed to false by now) so we don't scroll when the user had scrolled up.
794− LaunchedEffect(running) {
795− if (running && listItems.isNotEmpty()) {
796− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
797− if (lastVisible >= listItems.lastIndex) {
798− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
803− LaunchedEffect(Unit) {
807− // Track list size + the streaming length of the last part so we auto-scroll
808− // as content arrives, plus the pinned flag. A small data class with primitive
809− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
810− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
811− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
812− // and tool output — not just TextPart — keeps a pinned view following a long
813− // reasoning/tool block while it streams (previously it stalled at 0).
814− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
815− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
816− }.collect { signal ->
817− if (signal.pinned) {
818− // Back at the bottom: clear the new-content badge.
819− hasNewContent = false
820− if (signal.size > 0) {
821− // Scroll to the effective last index, including the trailing
822− // "__typing" row when a run is active so the working indicator
823− // is brought into view (not just the last message).
824− val items = currentListItems
825− val target = if (running) items.size else items.lastIndex
826− listState.scrollToItem(target)
828− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
829− // Content arrived while scrolled up — badge the jump-to-latest FAB.
830− hasNewContent = true
832− prevSize = signal.size
833− prevLen = signal.lastTextLength
837− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
838− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
839− // content padding accounts for the bottomBar's raised height, so the message
840− // list is already above the keyboard. Adding imePadding here would double-apply
841− // the IME inset and push messages too far up.
842− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
843− if (activeConnection == null) {
845− modifier = Modifier.align(Alignment.Center).padding(24.dp),
846− horizontalAlignment = Alignment.CenterHorizontally,
849− stringResource(R.string.not_connected),
850− color = MaterialTheme.colorScheme.error,
852− Spacer(Modifier.size(12.dp))
853− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
855− CircularProgressIndicator(
856− Modifier.size(20.dp),
857− color = MaterialTheme.colorScheme.onPrimary,
861− Text(stringResource(R.string.reconnect))
867− state = connectionState,
868− modifier = Modifier.align(Alignment.TopCenter),
869− isOnline = isOnline,
870− // On a hard failure, retry by forcing an SSE reconnect (which
871− // re-seeds from REST). refreshMessages is the right recovery path
872− // when the connection is present but the stream died; reconnect()
873− // is the path when the whole connection is gone (handled by the
874− // separate "Not connected" state below).
875− onRetry = { vm.refreshMessages() },
877− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
878− // recovery is a swipe away everywhere — not just when the message list is
879− // populated. Previously PTR was only around the populated list, leaving the
880− // error/loading states reachable only via a button tap.
882− isRefreshing = refreshing,
883− onRefresh = { vm.refreshMessages() },
884− // Cap width and center on large screens for readability — full-width
885− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
886− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
887− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
889− // Reserve top space when the banner is visible so it doesn't overlap the
890− // first message / state content.
891− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
892− val topPad = if (bannerVisible) 44.dp else 16.dp
893− if (loading && messages.isEmpty()) {
894− val loadingLabel = stringResource(R.string.loading)
895− // Attach the a11y label directly to the spinner (a detached zero-size Box
896− // isn't reliably focused/announced by TalkBack) and show a visible label so
897− // sighted users get "Loading…" rather than a bare spinner.
899− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
900− horizontalAlignment = Alignment.CenterHorizontally,
902− CircularProgressIndicator(
903− Modifier.semantics { contentDescription = loadingLabel },
906− Spacer(Modifier.size(8.dp))
909− style = MaterialTheme.typography.labelMedium,
910− color = MaterialTheme.colorScheme.onSurfaceVariant,
913− } else if (loadError && messages.isEmpty()) {
914− // A failed load with nothing to show. Distinct from the empty
915− // conversation state below — the conversation isn't empty, it
916− // failed to load, and offering "Start a conversation" here is
917− // misleading. Offer a Retry instead, mirroring SessionListScreen.
919− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
920− horizontalAlignment = Alignment.CenterHorizontally,
923− stringResource(R.string.load_messages_failed),
924− color = MaterialTheme.colorScheme.error,
926− Spacer(Modifier.size(12.dp))
927− Button(onClick = { vm.refreshMessages() }) {
928− Text(stringResource(R.string.retry))
931− } else if (messages.isEmpty() && running) {
932− // A run just started but no parts have arrived yet — the empty
933− // list with only the trailing "working…" row looks broken, so
934− // surface a clear starting state until the first part streams in.
935− val workingText = stringResource(R.string.working)
937− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
938− horizontalAlignment = Alignment.CenterHorizontally,
940− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
941− Spacer(Modifier.size(12.dp))
942− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
944− } else if (messages.isEmpty()) {
948− // Focus the input so the user can edit the suggestion before
949− // sending, instead of having to manually tap the field.
950− runCatching { inputFocusRequester.requestFocus() }
952− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
955− val lastMessageId = messages.lastOrNull()?.info?.id
956− // Text-to-speech for reading assistant replies aloud; shuts down when the
957− // message list leaves composition.
958− val tts = rememberTtsController()
959− val speakingMessageId by tts.speakingId
962− modifier = Modifier.fillMaxSize(),
963− // Extra bottom padding reserves room for the jump-to-latest FAB so it
964− // never floats over the last message. Top padding grows when the
965− // connection banner is visible so it doesn't overlap the first message.
966− contentPadding = PaddingValues(
970− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
972− verticalArrangement = Arrangement.spacedBy(16.dp),
977− contentType = { it.contentType },
979− // Default placement animation so inserted/moved rows glide in. Kept to the
980− // default (no heavy fade spec) so a streaming message growing in place
981− // doesn't animate on every token.
982− Box(Modifier.animateItem()) {
984− is MessageListItem.Separator -> DateSeparator(item.label)
985− is MessageListItem.Message -> {
986− val message = item.message
987− // Only the last (streaming) message needs isRunning — it drives the
988− // reasoning-block spinner. Passing the live flag to every bubble
989− // makes all visible messages recompose whenever a run starts or stops.
990− val modelLabel = remember(message.info, models) {
991− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
992− ?.let { resolveModelLabel(it, models) }
996− isRunning = running && message.info.id == lastMessageId,
997− imageContext = imageContext,
998− modelLabel = modelLabel,
999− onOpenFile = onOpenFile,
1000− onRevert = { vm.revertTo(message.info.id) },
1002− // editMessage reverts to before this message (hiding it and
1003− // everything after); the revert banner surfaces the rewind
1004− // with an Undo. Focus + scroll the composer into view like the
1005− // Quote action so the prefilled draft isn't off-screen.
1006− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1007− vm.editMessage(message.info.id, text)
1008− runCatching { inputFocusRequester.requestFocus() }
1009− contentScope.launch {
1010− runCatchingCancellable {
1011− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1015− onSpeak = { text -> tts.toggle(message.info.id, text) },
1016− isSpeaking = message.info.id == speakingMessageId,
1017− onQuote = { text ->
1018− vm.quoteReply(text)
1019− runCatching { inputFocusRequester.requestFocus() }
1021− onBranch = { text -> vm.branchFrom(text) },
1022− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1023− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1024− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1026− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1027− onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1029− { vm.retryOptimisticMessage(message.info.id) }
1034− onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1036− { vm.dismissOptimistic(message.info.id) }
1047− item(key = "__typing") {
1048− val workingText = stringResource(R.string.working)
1050− verticalAlignment = Alignment.CenterVertically,
1051− modifier = Modifier.semantics {
1052− contentDescription = workingText
1055− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1056− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1063− // Jump-to-latest affordance when the user has scrolled away during a stream.
1064− AnimatedVisibility(
1065− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1066− modifier = Modifier.align(Alignment.BottomEnd),
1068− // Badge the FAB when new content arrived while the user was scrolled up, so
1069− // they know there's something new to jump to (cleared once back at bottom).
1072− if (hasNewContent) {
1073− val newContentLabel = stringResource(R.string.new_messages)
1074− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1077− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1079− ExtendedFloatingActionButton(
1081− hasNewContent = false
1082− if (listItems.isNotEmpty()) {
1083− // Scroll to the effective last index, including the
1084− // trailing "__typing" row when a run is active.
1085− val target = if (running) listItems.size else listItems.lastIndex
1086− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1089− // contentDescription null: the visible "Latest" text already labels
1090− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1091− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1092− text = { Text(stringResource(R.string.latest)) },
1096− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1097− // user has scrolled down past the first few messages. Symmetric to the
1098− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1099− val scrolledDown by remember {
1100− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1102− AnimatedVisibility(
1103− visible = scrolledDown && listItems.size > 4,
1104− modifier = Modifier.align(Alignment.BottomStart),
1106− SmallFloatingActionButton(
1108− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1110− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1113− Icons.Filled.KeyboardArrowUp,
1114− contentDescription = stringResource(R.string.scroll_to_top),
1123− if (showExitConfirm) {
1125− onDismissRequest = { showExitConfirm = false },
1126− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1127− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1129− TextButton(onClick = {
1130− showExitConfirm = false
1131− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1134− }) { Text(stringResource(R.string.stop_and_exit)) }
1137− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1142− if (showStopConfirm) {
1144− onDismissRequest = { showStopConfirm = false },
1145− title = { Text(stringResource(R.string.stop_run_title)) },
1146− text = { Text(stringResource(R.string.stop_run_text)) },
1148− TextButton(onClick = {
1149− showStopConfirm = false
1150− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1152− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1155− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1160− if (showSummarizeConfirm) {
1162− onDismissRequest = { showSummarizeConfirm = false },
1163− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1164− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1166− TextButton(onClick = {
1167− showSummarizeConfirm = false
1169− }) { Text(stringResource(R.string.action_continue)) }
1172− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1177− if (showInitConfirm) {
1179− onDismissRequest = { showInitConfirm = false },
1180− title = { Text(stringResource(R.string.init_confirm_title)) },
1181− text = { Text(stringResource(R.string.init_confirm_text)) },
1183− TextButton(onClick = {
1184− showInitConfirm = false
1186− }) { Text(stringResource(R.string.action_continue)) }
1189− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1194− if (showRenameDialog) {
1195− RenameSessionChatDialog(
1196− initialTitle = sessionTitle ?: "",
1197− onDismiss = { showRenameDialog = false },
1198− onConfirm = { newName ->
1199− showRenameDialog = false
1200− vm.renameSession(newName)
1205− if (showDeleteDialog) {
1207− onDismissRequest = { showDeleteDialog = false },
1208− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1209− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1211− TextButton(onClick = {
1212− showDeleteDialog = false
1213− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1215− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1218− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1223− if (showShellDialog) {
1224− ShellCommandDialog(
1225− onDismiss = { showShellDialog = false },
1227− showShellDialog = false
1233− if (showModelPicker) {
1236− selected = selectedModel,
1237− loading = modelsLoading,
1238− error = modelsError,
1239− onSelect = { vm.selectModel(it) },
1240− onRetry = { vm.reloadModels() },
1241− onDismiss = { showModelPicker = false },
1245− if (showAgentPicker) {
1248− selected = selectedAgent,
1249− loading = agentsLoading,
1250− error = agentsError,
1251− onSelect = { vm.selectAgent(it?.name) },
1252− onRetry = { vm.reloadAgents() },
1253− onDismiss = { showAgentPicker = false },
1257− if (showCommandPicker) {
1258− CommandPickerSheet(
1259− commands = commands,
1260− loading = commandsLoading,
1261− error = commandsError,
1262− onSelect = { vm.runCommand(it) },
1263− onRetry = { vm.reloadCommands() },
1264− onDismiss = { showCommandPicker = false },
1268− pendingPermission?.let { permission ->
1270− permission = permission,
1271− position = permissionProgress.position,
1272− total = permissionProgress.total,
1273− onRespond = { response -> vm.respondPermission(permission, response) },
1278− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1283−private fun ChatInputBar(
1285− onValueChange: (String) -> Unit,
1289− sendOnEnter: Boolean,
1290− onSend: () -> Unit,
1291− onAbort: () -> Unit,
1292− queuedFollowUp: String?,
1293− onQueueFollowUp: (String) -> Unit,
1294− onCancelQueue: () -> Unit,
1295− focusRequester: androidx.compose.ui.focus.FocusRequester,
1296− attachments: List<PendingAttachment>,
1298− onRemoveAttachment: (String) -> Unit,
1299− onPickPhoto: () -> Unit,
1300− onPickFile: () -> Unit,
1301− onCamera: () -> Unit,
1302− onVoice: () -> Unit,
1304− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1305− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1306− // Full-screen editor state: opened when the user wants more space for a long prompt.
1307− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1308− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1309− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1310− // A queued follow-up replaces the Stop button with a "queued" chip so the
1311− // user sees their message will be sent when the run finishes, and can cancel.
1312− if (queuedFollowUp != null) {
1314− modifier = Modifier
1316− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1317− verticalAlignment = Alignment.CenterVertically,
1319− Column(modifier = Modifier.weight(1f)) {
1321− stringResource(R.string.queued),
1322− style = MaterialTheme.typography.labelSmall,
1323− color = MaterialTheme.colorScheme.onSurfaceVariant,
1327− style = MaterialTheme.typography.bodySmall,
1328− color = MaterialTheme.colorScheme.onSurfaceVariant,
1330− overflow = TextOverflow.Ellipsis,
1333− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1334− Text(stringResource(R.string.cancel))
1338− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1339− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1341− modifier = Modifier.fillMaxWidth().padding(8.dp),
1342− verticalAlignment = Alignment.Bottom,
1344− // Attach menu: photo picker, camera, or any file.
1345− var showAttachMenu by remember { mutableStateOf(false) }
1347− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1348− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1350− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1352− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1353− text = { Text(stringResource(R.string.attach_photo)) },
1354− onClick = { showAttachMenu = false; onPickPhoto() },
1357− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1358− text = { Text(stringResource(R.string.attach_camera)) },
1359− onClick = { showAttachMenu = false; onCamera() },
1362− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1363− text = { Text(stringResource(R.string.attach_file)) },
1364− onClick = { showAttachMenu = false; onPickFile() },
1368− // Voice dictation: appends recognized speech to the draft.
1369− IconButton(onClick = onVoice, enabled = enabled) {
1370− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1372− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1373− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1374− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1378− onValueChange = { v ->
1379− // Cap input length so a huge paste can't stall the UI. Shares are
1380− // capped separately in MainActivity; this guards typed/pasted drafts.
1381− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1383− modifier = Modifier
1385− .focusRequester(focusRequester)
1386− .testTag("chat_input")
1387− .onPreviewKeyEvent { event ->
1388− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1389− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1390− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1391− val send = enterShouldSend(
1393− hasContent = hasContent,
1394− sendOnEnter = sendOnEnter,
1395− shift = event.isShiftPressed,
1396− ctrl = event.isCtrlPressed,
1399− if (running) onQueueFollowUp(value) else onSend()
1405− // While a run is active a typed message only queues (sends after the run), so
1406− // the placeholder says so instead of the plain "Message…".
1408− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1412− // Show a "N / max" countdown once the draft crosses a high fraction of
1413− // the cap, so the user knows a paste is about to be truncated instead
1414− // of being silently cut off. Hidden for normal short prompts to avoid
1415− // clutter under a typical one-line message.
1417− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1418− if (value.length >= threshold) {
1421− R.string.draft_chars_remaining,
1422− NetworkConfig.maxDraftLengthChars - value.length,
1423− NetworkConfig.maxDraftLengthChars,
1425− style = MaterialTheme.typography.labelSmall,
1426− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1427− else MaterialTheme.colorScheme.onSurfaceVariant,
1431− keyboardOptions = KeyboardOptions(
1432− // When "Send on Enter" is on, expose ImeAction.Send so the soft
1433− // keyboard shows a send key — matching the setting's intent and
1434− // giving touch-only users a keyboard send affordance. When off,
1435− // ImeAction.Default keeps the enter/newline key for multi-line input.
1436− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1437− capitalization = KeyboardCapitalization.Sentences,
1439− keyboardActions = KeyboardActions(
1441− if (enabled && hasContent) onSend()
1445− ComposerTrailingButton(
1447− aborting = aborting,
1448− canSend = enabled && hasContent,
1449− canQueue = enabled && value.isNotBlank(),
1452− onQueue = { onQueueFollowUp(value) },
1456− if (showFullScreenEditor) {
1459− onValueChange = onValueChange,
1460− onDismiss = { showFullScreenEditor = false },
1461− onSend = { showFullScreenEditor = false; onSend() },
1462− canSend = enabled && hasContent,
1468−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1469− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1470−@OptIn(ExperimentalMaterial3Api::class)
1472−private fun FullScreenEditor(
1474− onValueChange: (String) -> Unit,
1475− onDismiss: () -> Unit,
1476− onSend: () -> Unit,
1479− androidx.compose.ui.window.Dialog(
1480− onDismissRequest = onDismiss,
1481− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1485− androidx.compose.material3.TopAppBar(
1486− title = { Text(stringResource(R.string.message_placeholder)) },
1488− androidx.compose.material3.TextButton(onClick = onDismiss) {
1489− Text(stringResource(R.string.collapse_editor))
1495− Surface(tonalElevation = 3.dp) {
1497− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1498− horizontalArrangement = Arrangement.End,
1500− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1501− Text(stringResource(R.string.send))
1509− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1510− modifier = Modifier.fillMaxSize().padding(padding),
1511− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1512− maxLines = Int.MAX_VALUE,
1513− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1519−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1520− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1521−private fun enterShouldSend(
1523− hasContent: Boolean,
1524− sendOnEnter: Boolean,
1528− !enabled || !hasContent -> false
1529− sendOnEnter -> !shift
1533−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1534− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1535− * [ChatInputBar] stays under the complexity threshold. */
1537−private fun ComposerTrailingButton(
1542− onSend: () -> Unit,
1543− onAbort: () -> Unit,
1544− onQueue: () -> Unit,
1547− Row(verticalAlignment = Alignment.CenterVertically) {
1548− // While a run is active the trailing action is Stop, so the only send affordance is
1549− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1550− // That leaves a touch-only user with the setting off no way to queue a follow-up
1551− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1552− // there's typed TEXT so queuing is always reachable, without changing the user's
1553− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1554− // canSend, which is also true for an attachment-only composer — because queuing "" just
1555− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1556− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1560− modifier = Modifier.testTag("queue_button"),
1562− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1563− // icon (which can be read as "snooze" or "later"), and isn't confused with
1564− // the Send action sitting right beside the Stop button.
1566− Icons.AutoMirrored.Filled.PlaylistAdd,
1567− contentDescription = stringResource(R.string.queue_followup),
1571− // Show a spinner while the abort REST call is in flight so the user sees the stop
1572− // was sent, and disable to prevent a double-tap.
1575− enabled = !aborting,
1576− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1579− val stopLabel = stringResource(R.string.stop)
1580− CircularProgressIndicator(
1581− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1582− strokeWidth = 2.dp,
1585− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1593− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1595− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1600−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1602−private fun EmptyConversation(
1603− onSuggestion: (String) -> Unit,
1604− modifier: Modifier = Modifier,
1606− // A few example prompts so a first-time user has a one-tap path to their first
1607− // message instead of staring at a blank input. Tapping a chip fills the draft
1608− // (without sending) so the user can edit it before sending.
1609− val suggestions = remember {
1611− R.string.empty_chat_suggest_1,
1612− R.string.empty_chat_suggest_2,
1613− R.string.empty_chat_suggest_3,
1617− modifier = modifier.padding(32.dp),
1618− horizontalAlignment = Alignment.CenterHorizontally,
1621− Icons.Filled.AutoAwesome,
1622− contentDescription = null,
1623− modifier = Modifier.size(48.dp),
1624− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1626− Spacer(Modifier.size(16.dp))
1628− stringResource(R.string.empty_chat_title),
1629− style = MaterialTheme.typography.titleMedium,
1631− Spacer(Modifier.size(8.dp))
1633− stringResource(R.string.empty_chat_hint),
1634− style = MaterialTheme.typography.bodyMedium,
1635− color = MaterialTheme.colorScheme.onSurfaceVariant,
1637− Spacer(Modifier.size(20.dp))
1638− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1639− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1641− modifier = Modifier.fillMaxWidth(),
1642− horizontalArrangement = Arrangement.spacedBy(8.dp),
1643− verticalArrangement = Arrangement.spacedBy(8.dp),
1645− suggestions.forEach { resId ->
1646− val text = stringResource(resId)
1647− androidx.compose.material3.AssistChip(
1648− onClick = { onSuggestion(text) },
1649− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1656−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1658−private fun RevertBanner(onUndo: () -> Unit) {
1660− color = MaterialTheme.colorScheme.tertiaryContainer,
1661− tonalElevation = 2.dp,
1662− modifier = Modifier.fillMaxWidth(),
1665− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1666− verticalAlignment = Alignment.CenterVertically,
1667− horizontalArrangement = Arrangement.SpaceBetween,
1669− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1671− Icons.Filled.Restore,
1672− contentDescription = null,
1673− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1674− modifier = Modifier.size(18.dp),
1677− stringResource(R.string.reverted_banner),
1678− style = MaterialTheme.typography.bodySmall,
1679− color = MaterialTheme.colorScheme.onTertiaryContainer,
1680− modifier = Modifier.padding(start = 8.dp),
1683− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1688−/** A banner shown while messages composed offline are queued in the outbox, with a
1689− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1691−private fun OutboxBanner(
1694− onFlush: () -> Unit,
1695− onDiscard: () -> Unit,
1698− color = MaterialTheme.colorScheme.secondaryContainer,
1699− tonalElevation = 2.dp,
1700− modifier = Modifier.fillMaxWidth(),
1703− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1704− verticalAlignment = Alignment.CenterVertically,
1705− horizontalArrangement = Arrangement.SpaceBetween,
1707− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1709− CircularProgressIndicator(
1710− Modifier.size(16.dp),
1711− strokeWidth = 2.dp,
1712− color = MaterialTheme.colorScheme.onSecondaryContainer,
1714− Spacer(Modifier.size(8.dp))
1718− stringResource(R.string.outbox_sending)
1720− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1721− stringResource(res, count)
1723− style = MaterialTheme.typography.bodySmall,
1724− color = MaterialTheme.colorScheme.onSecondaryContainer,
1728− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1729− TextButton(onClick = onDiscard) {
1730− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1737−/** Prompt for a one-off shell command to run in the session's worktree. */
1739−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1740− var command by rememberSaveable { mutableStateOf("") }
1742− onDismissRequest = onDismiss,
1743− title = { Text(stringResource(R.string.run_shell_command)) },
1747− onValueChange = { command = it },
1748− modifier = Modifier.fillMaxWidth(),
1749− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1750− label = { Text(stringResource(R.string.shell_command_label)) },
1752− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1753− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1758− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1759− enabled = command.isNotBlank(),
1760− ) { Text(stringResource(R.string.run)) }
1762− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1767− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1768− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1769− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1771−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1773−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1774− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1775− * streaming, not just plain assistant text. O(1). */
1776−private fun streamingContentLength(part: Part?): Int = when (part) {
1777− is TextPart -> part.text.length
1778− is ReasoningPart -> part.text.length
1779− is ToolPart -> when (val st = part.state) {
1780− is ToolCompleted -> st.output?.length ?: 0
1781− is ToolError -> st.error?.length ?: 0
1782− is ToolRunning -> st.title?.length ?: 0
1788−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1789− * dialog but lives in the chat screen so the user can rename without backing out to
1790− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1792−private fun RenameSessionChatDialog(
1793− initialTitle: String,
1794− onDismiss: () -> Unit,
1795− onConfirm: (String) -> Unit,
1797− // Seed the field once (no key input) so a later external title change — e.g. opencode
1798− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1799− // doesn't re-initialize the box and discard the user's in-progress edit.
1800− var title by rememberSaveable { mutableStateOf(initialTitle) }
1802− onDismissRequest = onDismiss,
1803− title = { Text(stringResource(R.string.rename_session_chat)) },
1807− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1808− modifier = Modifier.fillMaxWidth(),
1809− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1810− label = { Text(stringResource(R.string.rename_session_chat)) },
1812− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1813− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1817− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1818− Text(stringResource(R.string.save))
1822− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1828− * A single item in the chat message list — either a [Message] bubble or a day
1829− * [Separator] inserted before the first message of a new day. The separator shifts
1830− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1831− * the [List] of these items (not `messages.size`/`lastIndex`).
1833−private sealed interface MessageListItem {
1835− val contentType: Any
1837− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1838− override val contentType: Any get() = message.info::class
1841− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1842− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1843− // can share a label (e.g. an untimestamped message — empty label — between two
1844− // same-day messages, or two untimestamped groups), and a label-only key would
1845− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1846− // stable for a given message ordering so slots aren't needlessly recreated.
1847− override val key: Any get() = "sep_${ordinal}_$label"
1848− // Separators share a contentType so the LazyColumn can recycle their slots.
1849− override val contentType: Any get() = "separator"
1854− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1855− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1856− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1857− * Messages with no timestamp are grouped under an empty-label separator only if they
1858− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1860− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1861− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1862− * labels; older days fall back to a locale-stable medium-date format.
1864−private fun buildMessageListItems(
1865− messages: List<MessageWithParts>,
1866− todayLabel: String,
1867− yesterdayLabel: String,
1868−): List<MessageListItem> {
1869− if (messages.isEmpty()) return emptyList()
1870− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1871− val dateFmt = mediumDateFormat()
1872− val result = ArrayList<MessageListItem>(messages.size + 4)
1873− val seenKeys = HashSet<String>(messages.size * 2)
1874− var lastDayKey: String? = null
1876− var emptyIdOrdinal = 0
1878− for (message in messages) {
1879− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1880− val dayKey = ts?.let { dayKey(it) } ?: ""
1881− // Emit a separator before the very first message (so a leading un-timestamped message
1882− // still gets the first divider, empty label and all), and thereafter only when crossing
1883− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1884− // neither emits its own separator nor resets the day — otherwise a following same-day
1885− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1886− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1887− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1889− if (dayKey.isNotEmpty()) lastDayKey = dayKey
1891− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1892− // empty id — and the reducer intentionally keeps several such messages as distinct
1893− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1894− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1895− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1896− if (!seenKeys.add(key)) {
1898− while (!seenKeys.add("$key#$suffix")) suffix++
1899− key = "$key#$suffix"
1901− result.add(MessageListItem.Message(message, key))
1907− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1909− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1910− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1911− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1912− * every message on every token. Message timestamps are immutable once assigned, so we
1913− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1914− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1915− * thread during composition, so the coarse lock is uncontended.
1917−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1918− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1921−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1922− dayKeyCache.getOrPut(epochMillis) {
1923− java.time.Instant.ofEpochMilli(epochMillis)
1924− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1928−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1929−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1930−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1931−private var cachedDateFmt: java.text.DateFormat? = null
1932−private var cachedDateFmtLocale: java.util.Locale? = null
1934−private fun mediumDateFormat(): java.text.DateFormat {
1935− val locale = java.util.Locale.getDefault()
1936− val existing = cachedDateFmt
1937− if (existing != null && cachedDateFmtLocale == locale) return existing
1938− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1940− cachedDateFmtLocale = locale
1945− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1946− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1947− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1950−private fun dayLabel(
1953− today: java.time.LocalDate,
1954− todayLabel: String,
1955− yesterdayLabel: String,
1956− dateFmt: java.text.DateFormat,
1958− if (dayKey.isEmpty()) return ""
1959− val epochDay = dayKey.toLongOrNull() ?: return ""
1960− val date = java.time.LocalDate.ofEpochDay(epochDay)
1962− date == today -> todayLabel
1963− date == today.minusDays(1) -> yesterdayLabel
1964− else -> dateFmt.format(java.util.Date(ts))
1969− * A centered day divider in the message list. Renders nothing for an empty label
1970− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1973−private fun DateSeparator(label: String) {
1974− if (label.isBlank()) return
1976− modifier = Modifier.fillMaxWidth(),
1977− horizontalArrangement = Arrangement.Center,
1980− color = MaterialTheme.colorScheme.surfaceVariant,
1981− shape = MaterialTheme.shapes.small,
1985− style = MaterialTheme.typography.labelSmall,
1986− color = MaterialTheme.colorScheme.onSurfaceVariant,
1987− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),