@@ -1,1955 +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.launch
120−import kotlinx.coroutines.withContext
121−import soy.iko.opencode.data.model.Part
122−import soy.iko.opencode.data.model.MessageWithParts
123−import soy.iko.opencode.data.model.ReasoningPart
124−import soy.iko.opencode.data.model.TextPart
125−import soy.iko.opencode.data.model.ToolCompleted
126−import soy.iko.opencode.data.model.ToolError
127−import soy.iko.opencode.data.model.ToolPart
128−import soy.iko.opencode.data.model.ToolRunning
129−import soy.iko.opencode.data.network.EventStreamClient
130−import soy.iko.opencode.data.network.NetworkConfig
131−import soy.iko.opencode.di.AppContainer
132−import soy.iko.opencode.R
133−import soy.iko.opencode.ui.components.CommandPalette
134−import soy.iko.opencode.ui.components.ConnectionBanner
135−import soy.iko.opencode.ui.components.PaletteAction
136−import soy.iko.opencode.ui.components.copyToClipboard
137−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
138−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
139−import soy.iko.opencode.ui.components.showToast
140−import soy.iko.opencode.ui.components.toImageContext
141−import soy.iko.opencode.ui.vmFactory
142−import soy.iko.opencode.util.runCatchingCancellable
144−@OptIn(ExperimentalMaterial3Api::class)
147− container: AppContainer,
150− onOpenFile: ((String) -> Unit)? = null,
151− onOpenSession: ((String) -> Unit)? = null,
153− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
154− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
155− val running by vm.running.collectAsStateWithLifecycle()
156− val aborting by vm.aborting.collectAsStateWithLifecycle()
157− val loading by vm.loading.collectAsStateWithLifecycle()
158− val loadError by vm.loadError.collectAsStateWithLifecycle()
159− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
160− val models by vm.models.collectAsStateWithLifecycle()
161− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
162− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
163− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
164− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
165− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
166− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
167− val agents by vm.agents.collectAsStateWithLifecycle()
168− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
169− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
170− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
171− val commands by vm.commands.collectAsStateWithLifecycle()
172− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
173− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
174− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
175− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
176− val draft by vm.draft.collectAsStateWithLifecycle()
177− val attachments by vm.attachments.collectAsStateWithLifecycle()
178− val reverted by vm.reverted.collectAsStateWithLifecycle()
179− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
180− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
181− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
182− val isOnline by container.isOnline.collectAsStateWithLifecycle()
183− val haptics = LocalHapticFeedback.current
184− val scope = rememberCoroutineScope()
185− val shareContext = LocalContext.current
186− val defaultShareSubject = stringResource(R.string.share_subject)
187− val sessionLabel = stringResource(R.string.session)
188− val defaultModelLabel = stringResource(R.string.default_model)
189− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
191− append(selectedModel?.modelLabel ?: defaultModelLabel)
192− selectedAgent?.let { append(" · $it") }
196− // Connection profile (with auth) for rendering inline image attachments.
197− // Collect as state so a server switch recomposes the image context.
198− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
199− val imageContext = remember(activeConnection?.profile) {
200− activeConnection?.profile?.toImageContext()
203− // Mark this session as read while the user is viewing it; clear on leave so new
204− // background activity can badge it again.
205− DisposableEffect(sessionId) {
206− container.setCurrentSession(sessionId)
207− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
210− // Navigate away when the session is deleted via SSE so the user isn't left
211− // on a zombie screen showing a conversation that no longer exists. Surface a
212− // toast (not a snackbar) because the screen is about to be popped — a snackbar
213− // would be torn down before the user could read it, while a toast survives.
214− // Covers both SSE-driven deletion (deleted on another device) and a user-
215− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
216− // sets the same flag on success).
217− val deletedContext = LocalContext.current
218− LaunchedEffect(sessionDeleted) {
219− if (sessionDeleted) {
220− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
225− val snackbar = remember { SnackbarHostState() }
226− val retryLabel = stringResource(R.string.retry)
227− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
228− var showModelPicker by rememberSaveable { mutableStateOf(false) }
229− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
230− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
231− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
232− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
233− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
234− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
235− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
236− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
237− var showShellDialog by rememberSaveable { mutableStateOf(false) }
238− var showPalette by rememberSaveable { mutableStateOf(false) }
239− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
240− // a confirmation dialog (from both the overflow menu and the command palette).
241− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
242− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
244− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
245− // action list doesn't need a Composable context. Actions map to the same handlers the
246− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
247− val paletteModelLabel = stringResource(R.string.palette_switch_model)
248− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
249− val paletteCommandLabel = stringResource(R.string.palette_run_command)
250− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
251− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
252− val paletteShellLabel = stringResource(R.string.run_shell_command)
253− val paletteActions = remember(
254− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
255− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
258− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
259− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
260− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
261− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
262− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
263− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
267− // Keep the screen awake while the agent is working in *this* session. The foreground
268− // service that holds process priority during a run is managed app-wide off
269− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
270− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
271− // SSE stream before the completion notification fires.
272− val currentView = LocalView.current
273− val appContext = LocalContext.current.applicationContext
274− DisposableEffect(running) {
275− currentView.keepScreenOn = running
276− onDispose { currentView.keepScreenOn = false }
279− LaunchedEffect(Unit) {
280− vm.errorEvents.collect { event ->
281− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
282− // message-load failure) would silently re-submit the last prompt on tap.
283− val result = if (event.retryable) {
284− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
286− snackbar.showSnackbar(event.message)
288− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
292− // --- Attachments, voice, and share-link plumbing ---
293− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
294− val attachFailedMsg = stringResource(R.string.attachment_failed)
295− val attachLimitMsg = stringResource(R.string.attachment_limit)
296− val noCameraMsg = stringResource(R.string.no_camera_app)
297− val noVoiceMsg = stringResource(R.string.no_voice_app)
298− val voicePrompt = stringResource(R.string.voice_prompt)
299− val linkCopiedMsg = stringResource(R.string.link_copied)
301− // Count of picks currently being read + base64-encoded off the main thread, so the
302− // composer can show a staging placeholder immediately (chips only materialize once done).
303− var stagingCount by remember { mutableStateOf(0) }
305− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
306− // per-prompt count cap and surfacing per-file errors without aborting the batch.
307− fun stageUris(uris: List<Uri>) {
308− if (uris.isEmpty()) return
313− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
314− snackbar.showSnackbar(attachLimitMsg)
317− when (val result = uri.toAttachmentResult(appContext)) {
318− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
319− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
320− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
329− val photoPicker = rememberLauncherForActivityResult(
330− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
331− ) { uris -> stageUris(uris) }
333− val filePicker = rememberLauncherForActivityResult(
334− ActivityResultContracts.GetMultipleContents(),
335− ) { uris -> stageUris(uris) }
337− // Uri survives a config change mid-capture so the TakePicture result still resolves.
338− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
339− val cameraLauncher = rememberLauncherForActivityResult(
340− ActivityResultContracts.TakePicture(),
342− val uri = pendingCaptureUri
343− pendingCaptureUri = null
344− if (success && uri != null) stageUris(listOf(uri))
347− val voiceLauncher = rememberLauncherForActivityResult(
348− ActivityResultContracts.StartActivityForResult(),
350− if (result.resultCode == Activity.RESULT_OK) {
351− val spoken = result.data
352− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
354− ?.takeIf { it.isNotBlank() }
355− if (spoken != null) {
356− // Append to the existing draft rather than replacing, so dictation adds to
357− // whatever the user already typed.
358− val current = vm.draft.value
359− val combined = if (current.isBlank()) spoken else "$current $spoken"
360− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
365− fun launchCamera() {
366− val uri = newCameraCaptureUri(appContext)
368− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
371− pendingCaptureUri = uri
372− runCatching { cameraLauncher.launch(uri) }
373− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
377− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
378− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
379− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
381− runCatching { voiceLauncher.launch(intent) }
382− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
385− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
386− LaunchedEffect(Unit) {
387− vm.shareLinkEvents.collect { url ->
388− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
389− snackbar.showSnackbar(linkCopiedMsg)
393− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
394− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
395− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
396− // a dropped branch-navigation event in the gap.
397− val branchedMsg = stringResource(R.string.branch_created)
398− LaunchedEffect(Unit) {
399− vm.branchEvents.collect { newId ->
400− showToast(shareContext, branchedMsg)
401− onOpenSession?.invoke(newId)
405− // Stage images shared into the app (via the system share sheet) as attachments.
406− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
407− // while this ChatScreen is already composed — which happens in two-pane mode, where the
408− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
409− // only fire on first composition. consumePendingSharedMedia() atomically drains the
410− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
411− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
412− LaunchedEffect(pendingSharedMedia) {
413− val shared = container.consumePendingSharedMedia()
414− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
418− if (vm.send(draft)) {
419− // TextHandleMove (a light tick) is semantically right for a send commit;
420− // LongPress is reserved for long-press/swipe gestures.
421− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
425− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
428− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
429− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
430− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
431− // typing (and the composer's own Enter-to-send handling) is untouched.
432− modifier = Modifier.onPreviewKeyEvent { ev ->
433− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
435− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
436− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
437− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
438− showStopConfirm = true; true
446− val changeLabel = stringResource(R.string.change_model_agent)
447− // The subtitle reads "model · agent", so tapping the title offers *both*
448− // — a small menu picks which picker to open. Previously the tap went
449− // straight to the model picker, leaving the agent changeable only via
450− // the overflow menu despite the title implying otherwise.
453− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
454− // node; the click label rides on `clickable` (onClickLabel) instead of
455− // an explicit contentDescription, which would have SUPPRESSED the child
456− // Texts and announced only "Change model and agent".
459− enabled = models.isNotEmpty(),
461− onClickLabel = changeLabel,
462− ) { showTitleMenu = true }
463− .semantics(mergeDescendants = true) {},
464− verticalAlignment = Alignment.CenterVertically,
466− Column(modifier = Modifier.weight(1f, fill = false)) {
467− // maxLines=1 + Ellipsis so a long session title can't wrap and
468− // push the top bar to multiple lines, shifting the whole layout.
470− sessionTitle ?: sessionLabel,
472− overflow = TextOverflow.Ellipsis,
476− style = MaterialTheme.typography.labelSmall,
477− color = MaterialTheme.colorScheme.onSurfaceVariant,
479− overflow = TextOverflow.Ellipsis,
482− // Visual affordance that the title is tappable; without it the
483− // title is indistinguishable from plain text and the pickers are
484− // effectively undiscoverable.
485− if (models.isNotEmpty()) {
487− Icons.Filled.KeyboardArrowDown,
488− contentDescription = null,
489− tint = MaterialTheme.colorScheme.onSurfaceVariant,
490− modifier = Modifier.size(20.dp),
494− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
496− text = { Text(stringResource(R.string.palette_switch_model)) },
497− enabled = !modelsLoading || models.isNotEmpty(),
498− onClick = { showTitleMenu = false; showModelPicker = true },
501− text = { Text(stringResource(R.string.palette_choose_agent)) },
502− enabled = !agentsLoading || agents.isNotEmpty(),
503− onClick = { showTitleMenu = false; showAgentPicker = true },
509− IconButton(onClick = {
510− if (running) showExitConfirm = true else onBack()
512− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
516− // At-a-glance run status in the top bar. When the user is scrolled
517− // up (jump-to-latest FAB visible), the input-bar Stop button and the
518− // trailing "working…" row are off-screen, so a top-bar spinner is the
519− // only signal the agent is still working.
521− val workingLabel = stringResource(R.string.working)
522− CircularProgressIndicator(
523− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
527− // Manual refresh: forces an SSE reconnect, which re-seeds messages
528− // from REST. A recovery path when the stream silently drops and the
529− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
530− // immediate tap feedback — the SSE reconnect may not visibly change
531− // the connection state when already Connected, so without it the tap
532− // appears to do nothing.
533− val refreshLabel = stringResource(R.string.refresh)
535− onClick = { vm.refreshMessages() },
536− enabled = activeConnection != null && !refreshing,
539− CircularProgressIndicator(
540− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
544− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
547− // Overflow menu consolidates the less-frequent actions (share,
548− // commands, agent, model, rename, delete) so the top bar stays
549− // scannable on narrow phones — previously 5 icons crowded the bar
550− // alongside the back button and tappable title. Catalog-loading
551− // spinners stay inline (next to the overflow) so a load state is
552− // visible without opening the menu.
553− val moreLabel = stringResource(R.string.more)
554− val loadingLabel = stringResource(R.string.loading)
555− val shareLabel = stringResource(R.string.share_conversation)
556− val commandsLabel = stringResource(R.string.commands)
557− val renameLabel = stringResource(R.string.rename_session_chat)
558− val deleteLabel = stringResource(R.string.delete_session_chat)
559− val createShareLabel = stringResource(R.string.create_share_link)
560− val copyShareLabel = stringResource(R.string.copy_share_link)
561− val stopShareLabel = stringResource(R.string.stop_sharing)
562− val summarizeLabel = stringResource(R.string.summarize_conversation)
563− val initLabel = stringResource(R.string.generate_agents_md)
564− val shellLabel = stringResource(R.string.run_shell_command)
566− IconButton(onClick = { showOverflowMenu = true }) {
567− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
570− expanded = showOverflowMenu,
571− onDismissRequest = { showOverflowMenu = false },
574− text = { Text(shareLabel) },
575− enabled = hasMessages,
577− showOverflowMenu = false
579− val md = withContext(Dispatchers.Default) {
580− buildConversationMarkdown(vm.messages.value, sessionTitle)
582− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
583− type = "text/markdown"
584− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
585− putExtra(android.content.Intent.EXTRA_TEXT, md)
587− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
588− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
593− text = { Text(commandsLabel) },
594− enabled = !commandsLoading || commands.isNotEmpty(),
595− onClick = { showOverflowMenu = false; showCommandPicker = true },
597− androidx.compose.material3.HorizontalDivider()
598− // Session sharing: create a public link, copy an existing one, or revoke it.
599− if (shareUrl == null) {
601− text = { Text(createShareLabel) },
602− enabled = hasMessages,
603− onClick = { showOverflowMenu = false; vm.shareSession() },
607− text = { Text(copyShareLabel) },
609− showOverflowMenu = false
611− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
612− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
617− text = { Text(stopShareLabel) },
618− onClick = { showOverflowMenu = false; vm.unshareSession() },
622− text = { Text(summarizeLabel) },
623− enabled = hasMessages && !running,
624− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
627− text = { Text(initLabel) },
629− onClick = { showOverflowMenu = false; showInitConfirm = true },
632− text = { Text(shellLabel) },
634− onClick = { showOverflowMenu = false; showShellDialog = true },
636− androidx.compose.material3.HorizontalDivider()
638− text = { Text(renameLabel) },
639− onClick = { showOverflowMenu = false; showRenameDialog = true },
642− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
643− onClick = { showOverflowMenu = false; showDeleteDialog = true },
646− // While a catalog is initially loading (empty list + loading flag),
647− // show a tiny inline spinner beside the overflow so the user can see
648− // a load is in progress without opening the menu. Once loaded the
649− // spinner disappears; the menu items are always enabled (tapping a
650− // picker with no items shows the "no models/agents/commands" state).
651− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
652− (agentsLoading && agents.isEmpty()) ||
653− (modelsLoading && models.isEmpty())
654− if (catalogLoading) {
655− CircularProgressIndicator(
657− .align(Alignment.TopEnd)
659− .semantics { contentDescription = loadingLabel },
667− snackbarHost = { SnackbarHost(snackbar) },
669− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
670− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
671− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
672− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
674− // Pinned above the composer so the agent's plan and progress stay visible
675− // while scrolled up mid-run; renders nothing when there's no plan.
676− TodoPlanBar(todoPlan)
677− AnimatedVisibility(visible = reverted) {
678− RevertBanner(onUndo = { vm.unrevert() })
680− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
682− count = queuedOffline.size,
683− sending = outboxSending,
684− onFlush = { vm.flushQueued() },
685− onDiscard = { vm.discardAllQueued() },
690− onValueChange = vm::updateDraft,
692− aborting = aborting,
693− enabled = activeConnection != null,
694− sendOnEnter = sendOnEnter,
696− onAbort = { showStopConfirm = true },
697− queuedFollowUp = queuedFollowUp,
698− onQueueFollowUp = vm::queueFollowUp,
699− onCancelQueue = { vm.queueFollowUp("") },
700− focusRequester = inputFocusRequester,
701− attachments = attachments,
702− staging = stagingCount > 0,
703− onRemoveAttachment = vm::removeAttachment,
706− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
709− onPickFile = { filePicker.launch("*/*") },
710− onCamera = { launchCamera() },
711− onVoice = { launchVoice() },
716− // Collect messages inside the content lambda so streaming token updates
717− // recompose only this subtree, not the top bar / input bar / 20+ other
718− // state reads in the ChatScreen body.
719− val messages by vm.messages.collectAsStateWithLifecycle()
720− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
721− val listState = rememberLazyListState()
722− val contentScope = rememberCoroutineScope()
723− val timeTick = rememberRelativeTimeTick()
724− // Group messages by day and interleave date separators so a long conversation
725− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
726− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
727− // outside the PullToRefreshBox so the auto-scroll effects below can reference
728− // the same list the LazyColumn renders (separators shift the indices vs. the
729− // raw messages list, so scroll targets must be in listItems space).
730− val todayLabel = stringResource(R.string.today)
731− val yesterdayLabel = stringResource(R.string.yesterday)
732− val listItems = remember(messages, todayLabel, yesterdayLabel) {
733− buildMessageListItems(messages, todayLabel, yesterdayLabel)
735− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
736− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
737− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
738− // would capture the first composition's list — which is empty, since `messages`
739− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
740− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
741− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
742− // whose value tracks the latest list.
743− val currentListItems by rememberUpdatedState(listItems)
745− // New-content signal for the jump-to-latest FAB: set when content grows while the user
746− // is scrolled away from the bottom, cleared once they return (see the collector below).
747− var hasNewContent by remember { mutableStateOf(false) }
749− val isPinnedToBottom by remember {
751− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
752− // When a run is active, the LazyColumn has one trailing "__typing"
753− // item after the last list item. Account for it so "pinned to bottom"
754− // includes the working indicator — otherwise the pin check targets
755− // listItems.lastIndex, the typing row sits just below the viewport,
756− // and the user never sees the progress indicator even when pinned.
757− val items = currentListItems
758− val effectiveLast = if (running) items.size else items.lastIndex
759− lastVisible >= effectiveLast || items.isEmpty()
763− // Jump to the newest message once, when the conversation first loads. Guarded by a
764− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
765− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
766− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
767− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
768− LaunchedEffect(listItems.isNotEmpty()) {
769− if (listItems.isNotEmpty() && !didInitialScroll) {
770− // When a run is active the LazyColumn has a trailing "__typing" row at
771− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
772− // running session lands truly pinned to bottom and streaming auto-scroll engages.
773− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
774− didInitialScroll = true
778− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
779− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
780− // isPinnedToBottom check flips to false the instant you send — freezing
781− // auto-scroll. If the user was pinned to the last item just before the run
782− // began, bring the typing row into view so the pin (and streaming follow) is
783− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
784− // recomputed to false by now) so we don't scroll when the user had scrolled up.
785− LaunchedEffect(running) {
786− if (running && listItems.isNotEmpty()) {
787− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
788− if (lastVisible >= listItems.lastIndex) {
789− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
794− LaunchedEffect(Unit) {
798− // Track list size + the streaming length of the last part so we auto-scroll
799− // as content arrives, plus the pinned flag. A small data class with primitive
800− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
801− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
802− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
803− // and tool output — not just TextPart — keeps a pinned view following a long
804− // reasoning/tool block while it streams (previously it stalled at 0).
805− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
806− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
807− }.collect { signal ->
808− if (signal.pinned) {
809− // Back at the bottom: clear the new-content badge.
810− hasNewContent = false
811− if (signal.size > 0) {
812− // Scroll to the effective last index, including the trailing
813− // "__typing" row when a run is active so the working indicator
814− // is brought into view (not just the last message).
815− val items = currentListItems
816− val target = if (running) items.size else items.lastIndex
817− listState.scrollToItem(target)
819− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
820− // Content arrived while scrolled up — badge the jump-to-latest FAB.
821− hasNewContent = true
823− prevSize = signal.size
824− prevLen = signal.lastTextLength
828− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
829− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
830− // content padding accounts for the bottomBar's raised height, so the message
831− // list is already above the keyboard. Adding imePadding here would double-apply
832− // the IME inset and push messages too far up.
833− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
834− if (activeConnection == null) {
836− modifier = Modifier.align(Alignment.Center).padding(24.dp),
837− horizontalAlignment = Alignment.CenterHorizontally,
840− stringResource(R.string.not_connected),
841− color = MaterialTheme.colorScheme.error,
843− Spacer(Modifier.size(12.dp))
844− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
846− CircularProgressIndicator(
847− Modifier.size(20.dp),
848− color = MaterialTheme.colorScheme.onPrimary,
852− Text(stringResource(R.string.reconnect))
858− state = connectionState,
859− modifier = Modifier.align(Alignment.TopCenter),
860− isOnline = isOnline,
861− // On a hard failure, retry by forcing an SSE reconnect (which
862− // re-seeds from REST). refreshMessages is the right recovery path
863− // when the connection is present but the stream died; reconnect()
864− // is the path when the whole connection is gone (handled by the
865− // separate "Not connected" state below).
866− onRetry = { vm.refreshMessages() },
868− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
869− // recovery is a swipe away everywhere — not just when the message list is
870− // populated. Previously PTR was only around the populated list, leaving the
871− // error/loading states reachable only via a button tap.
873− isRefreshing = refreshing,
874− onRefresh = { vm.refreshMessages() },
875− // Cap width and center on large screens for readability — full-width
876− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
877− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
878− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
880− // Reserve top space when the banner is visible so it doesn't overlap the
881− // first message / state content.
882− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
883− val topPad = if (bannerVisible) 44.dp else 16.dp
884− if (loading && messages.isEmpty()) {
885− val loadingLabel = stringResource(R.string.loading)
886− CircularProgressIndicator(
887− Modifier.align(Alignment.Center).padding(top = topPad),
890− Box(modifier = Modifier.semantics { contentDescription = loadingLabel })
891− } else if (loadError && messages.isEmpty()) {
892− // A failed load with nothing to show. Distinct from the empty
893− // conversation state below — the conversation isn't empty, it
894− // failed to load, and offering "Start a conversation" here is
895− // misleading. Offer a Retry instead, mirroring SessionListScreen.
897− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
898− horizontalAlignment = Alignment.CenterHorizontally,
901− stringResource(R.string.load_messages_failed),
902− color = MaterialTheme.colorScheme.error,
904− Spacer(Modifier.size(12.dp))
905− Button(onClick = { vm.refreshMessages() }) {
906− Text(stringResource(R.string.retry))
909− } else if (messages.isEmpty() && running) {
910− // A run just started but no parts have arrived yet — the empty
911− // list with only the trailing "working…" row looks broken, so
912− // surface a clear starting state until the first part streams in.
913− val workingText = stringResource(R.string.working)
915− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
916− horizontalAlignment = Alignment.CenterHorizontally,
918− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
919− Spacer(Modifier.size(12.dp))
920− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
922− } else if (messages.isEmpty()) {
926− // Focus the input so the user can edit the suggestion before
927− // sending, instead of having to manually tap the field.
928− runCatching { inputFocusRequester.requestFocus() }
930− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
933− val lastMessageId = messages.lastOrNull()?.info?.id
934− // Text-to-speech for reading assistant replies aloud; shuts down when the
935− // message list leaves composition.
936− val tts = rememberTtsController()
937− val speakingMessageId by tts.speakingId
940− modifier = Modifier.fillMaxSize(),
941− // Extra bottom padding reserves room for the jump-to-latest FAB so it
942− // never floats over the last message. Top padding grows when the
943− // connection banner is visible so it doesn't overlap the first message.
944− contentPadding = PaddingValues(
948− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
950− verticalArrangement = Arrangement.spacedBy(16.dp),
955− contentType = { it.contentType },
957− // Default placement animation so inserted/moved rows glide in. Kept to the
958− // default (no heavy fade spec) so a streaming message growing in place
959− // doesn't animate on every token.
960− Box(Modifier.animateItem()) {
962− is MessageListItem.Separator -> DateSeparator(item.label)
963− is MessageListItem.Message -> {
964− val message = item.message
965− // Only the last (streaming) message needs isRunning — it drives the
966− // reasoning-block spinner. Passing the live flag to every bubble
967− // makes all visible messages recompose whenever a run starts or stops.
968− val modelLabel = remember(message.info, models) {
969− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
970− ?.let { resolveModelLabel(it, models) }
974− isRunning = running && message.info.id == lastMessageId,
975− imageContext = imageContext,
976− modelLabel = modelLabel,
977− onOpenFile = onOpenFile,
978− onRevert = { vm.revertTo(message.info.id) },
980− // editMessage reverts to before this message (hiding it and
981− // everything after); the revert banner surfaces the rewind
982− // with an Undo. Focus + scroll the composer into view like the
983− // Quote action so the prefilled draft isn't off-screen.
984− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
985− vm.editMessage(message.info.id, text)
986− runCatching { inputFocusRequester.requestFocus() }
987− contentScope.launch {
988− runCatchingCancellable {
989− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
993− onSpeak = { text -> tts.toggle(message.info.id, text) },
994− isSpeaking = message.info.id == speakingMessageId,
997− runCatching { inputFocusRequester.requestFocus() }
999− onBranch = { text -> vm.branchFrom(text) },
1000− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1001− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1002− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1004− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1011− item(key = "__typing") {
1012− val workingText = stringResource(R.string.working)
1014− verticalAlignment = Alignment.CenterVertically,
1015− modifier = Modifier.semantics {
1016− contentDescription = workingText
1019− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1020− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1027− // Jump-to-latest affordance when the user has scrolled away during a stream.
1028− AnimatedVisibility(
1029− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1030− modifier = Modifier.align(Alignment.BottomEnd),
1032− // Badge the FAB when new content arrived while the user was scrolled up, so
1033− // they know there's something new to jump to (cleared once back at bottom).
1036− if (hasNewContent) {
1037− val newContentLabel = stringResource(R.string.new_messages)
1038− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1041− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1043− ExtendedFloatingActionButton(
1045− hasNewContent = false
1046− if (listItems.isNotEmpty()) {
1047− // Scroll to the effective last index, including the
1048− // trailing "__typing" row when a run is active.
1049− val target = if (running) listItems.size else listItems.lastIndex
1050− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1053− // contentDescription null: the visible "Latest" text already labels
1054− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1055− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1056− text = { Text(stringResource(R.string.latest)) },
1060− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1061− // user has scrolled down past the first few messages. Symmetric to the
1062− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1063− val scrolledDown by remember {
1064− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1066− AnimatedVisibility(
1067− visible = scrolledDown && listItems.size > 4,
1068− modifier = Modifier.align(Alignment.BottomStart),
1070− SmallFloatingActionButton(
1072− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1074− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1077− Icons.Filled.KeyboardArrowUp,
1078− contentDescription = stringResource(R.string.scroll_to_top),
1087− if (showExitConfirm) {
1089− onDismissRequest = { showExitConfirm = false },
1090− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1091− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1093− TextButton(onClick = {
1094− showExitConfirm = false
1095− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1098− }) { Text(stringResource(R.string.stop_and_exit)) }
1101− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1106− if (showStopConfirm) {
1108− onDismissRequest = { showStopConfirm = false },
1109− title = { Text(stringResource(R.string.stop_run_title)) },
1110− text = { Text(stringResource(R.string.stop_run_text)) },
1112− TextButton(onClick = {
1113− showStopConfirm = false
1114− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1116− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1119− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1124− if (showSummarizeConfirm) {
1126− onDismissRequest = { showSummarizeConfirm = false },
1127− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1128− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1130− TextButton(onClick = {
1131− showSummarizeConfirm = false
1133− }) { Text(stringResource(R.string.action_continue)) }
1136− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1141− if (showInitConfirm) {
1143− onDismissRequest = { showInitConfirm = false },
1144− title = { Text(stringResource(R.string.init_confirm_title)) },
1145− text = { Text(stringResource(R.string.init_confirm_text)) },
1147− TextButton(onClick = {
1148− showInitConfirm = false
1150− }) { Text(stringResource(R.string.action_continue)) }
1153− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1158− if (showRenameDialog) {
1159− RenameSessionChatDialog(
1160− initialTitle = sessionTitle ?: "",
1161− onDismiss = { showRenameDialog = false },
1162− onConfirm = { newName ->
1163− showRenameDialog = false
1164− vm.renameSession(newName)
1169− if (showDeleteDialog) {
1171− onDismissRequest = { showDeleteDialog = false },
1172− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1173− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1175− TextButton(onClick = {
1176− showDeleteDialog = false
1177− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1179− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1182− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1187− if (showShellDialog) {
1188− ShellCommandDialog(
1189− onDismiss = { showShellDialog = false },
1191− showShellDialog = false
1197− if (showModelPicker) {
1200− selected = selectedModel,
1201− loading = modelsLoading,
1202− error = modelsError,
1203− onSelect = { vm.selectModel(it) },
1204− onRetry = { vm.reloadModels() },
1205− onDismiss = { showModelPicker = false },
1209− if (showAgentPicker) {
1212− selected = selectedAgent,
1213− loading = agentsLoading,
1214− error = agentsError,
1215− onSelect = { vm.selectAgent(it?.name) },
1216− onRetry = { vm.reloadAgents() },
1217− onDismiss = { showAgentPicker = false },
1221− if (showCommandPicker) {
1222− CommandPickerSheet(
1223− commands = commands,
1224− loading = commandsLoading,
1225− error = commandsError,
1226− onSelect = { vm.runCommand(it) },
1227− onRetry = { vm.reloadCommands() },
1228− onDismiss = { showCommandPicker = false },
1232− pendingPermission?.let { permission ->
1234− permission = permission,
1235− position = permissionProgress.position,
1236− total = permissionProgress.total,
1237− onRespond = { response -> vm.respondPermission(permission, response) },
1242− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1247−private fun ChatInputBar(
1249− onValueChange: (String) -> Unit,
1253− sendOnEnter: Boolean,
1254− onSend: () -> Unit,
1255− onAbort: () -> Unit,
1256− queuedFollowUp: String?,
1257− onQueueFollowUp: (String) -> Unit,
1258− onCancelQueue: () -> Unit,
1259− focusRequester: androidx.compose.ui.focus.FocusRequester,
1260− attachments: List<PendingAttachment>,
1262− onRemoveAttachment: (String) -> Unit,
1263− onPickPhoto: () -> Unit,
1264− onPickFile: () -> Unit,
1265− onCamera: () -> Unit,
1266− onVoice: () -> Unit,
1268− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1269− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1270− // Full-screen editor state: opened when the user wants more space for a long prompt.
1271− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1272− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1273− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1274− // A queued follow-up replaces the Stop button with a "queued" chip so the
1275− // user sees their message will be sent when the run finishes, and can cancel.
1276− if (queuedFollowUp != null) {
1278− modifier = Modifier
1280− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1281− verticalAlignment = Alignment.CenterVertically,
1283− Column(modifier = Modifier.weight(1f)) {
1285− stringResource(R.string.queued),
1286− style = MaterialTheme.typography.labelSmall,
1287− color = MaterialTheme.colorScheme.onSurfaceVariant,
1291− style = MaterialTheme.typography.bodySmall,
1292− color = MaterialTheme.colorScheme.onSurfaceVariant,
1294− overflow = TextOverflow.Ellipsis,
1297− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1298− Text(stringResource(R.string.cancel))
1302− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1303− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1305− modifier = Modifier.fillMaxWidth().padding(8.dp),
1306− verticalAlignment = Alignment.Bottom,
1308− // Attach menu: photo picker, camera, or any file.
1309− var showAttachMenu by remember { mutableStateOf(false) }
1311− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1312− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1314− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1316− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1317− text = { Text(stringResource(R.string.attach_photo)) },
1318− onClick = { showAttachMenu = false; onPickPhoto() },
1321− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1322− text = { Text(stringResource(R.string.attach_camera)) },
1323− onClick = { showAttachMenu = false; onCamera() },
1326− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1327− text = { Text(stringResource(R.string.attach_file)) },
1328− onClick = { showAttachMenu = false; onPickFile() },
1332− // Voice dictation: appends recognized speech to the draft.
1333− IconButton(onClick = onVoice, enabled = enabled) {
1334− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1336− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1337− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1338− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1342− onValueChange = { v ->
1343− // Cap input length so a huge paste can't stall the UI. Shares are
1344− // capped separately in MainActivity; this guards typed/pasted drafts.
1345− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1347− modifier = Modifier
1349− .focusRequester(focusRequester)
1350− .testTag("chat_input")
1351− .onPreviewKeyEvent { event ->
1352− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1353− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1354− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1355− val send = enterShouldSend(
1357− hasContent = hasContent,
1358− sendOnEnter = sendOnEnter,
1359− shift = event.isShiftPressed,
1360− ctrl = event.isCtrlPressed,
1363− if (running) onQueueFollowUp(value) else onSend()
1369− // While a run is active a typed message only queues (sends after the run), so
1370− // the placeholder says so instead of the plain "Message…".
1372− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1376− // Show a "N / max" countdown once the draft crosses a high fraction of
1377− // the cap, so the user knows a paste is about to be truncated instead
1378− // of being silently cut off. Hidden for normal short prompts to avoid
1379− // clutter under a typical one-line message.
1381− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1382− if (value.length >= threshold) {
1385− R.string.draft_chars_remaining,
1386− NetworkConfig.maxDraftLengthChars - value.length,
1387− NetworkConfig.maxDraftLengthChars,
1389− style = MaterialTheme.typography.labelSmall,
1390− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1391− else MaterialTheme.colorScheme.onSurfaceVariant,
1395− keyboardOptions = KeyboardOptions(
1396− // When "Send on Enter" is on, expose ImeAction.Send so the soft
1397− // keyboard shows a send key — matching the setting's intent and
1398− // giving touch-only users a keyboard send affordance. When off,
1399− // ImeAction.Default keeps the enter/newline key for multi-line input.
1400− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1401− capitalization = KeyboardCapitalization.Sentences,
1403− keyboardActions = KeyboardActions(
1405− if (enabled && hasContent) onSend()
1409− ComposerTrailingButton(
1411− aborting = aborting,
1412− canSend = enabled && hasContent,
1413− canQueue = enabled && value.isNotBlank(),
1416− onQueue = { onQueueFollowUp(value) },
1420− if (showFullScreenEditor) {
1423− onValueChange = onValueChange,
1424− onDismiss = { showFullScreenEditor = false },
1425− onSend = { showFullScreenEditor = false; onSend() },
1426− canSend = enabled && hasContent,
1432−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1433− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1434−@OptIn(ExperimentalMaterial3Api::class)
1436−private fun FullScreenEditor(
1438− onValueChange: (String) -> Unit,
1439− onDismiss: () -> Unit,
1440− onSend: () -> Unit,
1443− androidx.compose.ui.window.Dialog(
1444− onDismissRequest = onDismiss,
1445− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1449− androidx.compose.material3.TopAppBar(
1450− title = { Text(stringResource(R.string.message_placeholder)) },
1452− androidx.compose.material3.TextButton(onClick = onDismiss) {
1453− Text(stringResource(R.string.collapse_editor))
1459− Surface(tonalElevation = 3.dp) {
1461− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1462− horizontalArrangement = Arrangement.End,
1464− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1465− Text(stringResource(R.string.send))
1473− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1474− modifier = Modifier.fillMaxSize().padding(padding),
1475− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1476− maxLines = Int.MAX_VALUE,
1477− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1483−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1484− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1485−private fun enterShouldSend(
1487− hasContent: Boolean,
1488− sendOnEnter: Boolean,
1492− !enabled || !hasContent -> false
1493− sendOnEnter -> !shift
1497−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1498− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1499− * [ChatInputBar] stays under the complexity threshold. */
1501−private fun ComposerTrailingButton(
1506− onSend: () -> Unit,
1507− onAbort: () -> Unit,
1508− onQueue: () -> Unit,
1511− Row(verticalAlignment = Alignment.CenterVertically) {
1512− // While a run is active the trailing action is Stop, so the only send affordance is
1513− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1514− // That leaves a touch-only user with the setting off no way to queue a follow-up
1515− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1516− // there's typed TEXT so queuing is always reachable, without changing the user's
1517− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1518− // canSend, which is also true for an attachment-only composer — because queuing "" just
1519− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1520− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1524− modifier = Modifier.testTag("queue_button"),
1526− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1527− // icon (which can be read as "snooze" or "later"), and isn't confused with
1528− // the Send action sitting right beside the Stop button.
1530− Icons.AutoMirrored.Filled.PlaylistAdd,
1531− contentDescription = stringResource(R.string.queue_followup),
1535− // Show a spinner while the abort REST call is in flight so the user sees the stop
1536− // was sent, and disable to prevent a double-tap.
1539− enabled = !aborting,
1540− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1543− val stopLabel = stringResource(R.string.stop)
1544− CircularProgressIndicator(
1545− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1546− strokeWidth = 2.dp,
1549− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1557− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1559− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1564−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1566−private fun EmptyConversation(
1567− onSuggestion: (String) -> Unit,
1568− modifier: Modifier = Modifier,
1570− // A few example prompts so a first-time user has a one-tap path to their first
1571− // message instead of staring at a blank input. Tapping a chip fills the draft
1572− // (without sending) so the user can edit it before sending.
1573− val suggestions = remember {
1575− R.string.empty_chat_suggest_1,
1576− R.string.empty_chat_suggest_2,
1577− R.string.empty_chat_suggest_3,
1581− modifier = modifier.padding(32.dp),
1582− horizontalAlignment = Alignment.CenterHorizontally,
1585− Icons.Filled.AutoAwesome,
1586− contentDescription = null,
1587− modifier = Modifier.size(48.dp),
1588− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1590− Spacer(Modifier.size(16.dp))
1592− stringResource(R.string.empty_chat_title),
1593− style = MaterialTheme.typography.titleMedium,
1595− Spacer(Modifier.size(8.dp))
1597− stringResource(R.string.empty_chat_hint),
1598− style = MaterialTheme.typography.bodyMedium,
1599− color = MaterialTheme.colorScheme.onSurfaceVariant,
1601− Spacer(Modifier.size(20.dp))
1602− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1603− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1605− modifier = Modifier.fillMaxWidth(),
1606− horizontalArrangement = Arrangement.spacedBy(8.dp),
1607− verticalArrangement = Arrangement.spacedBy(8.dp),
1609− suggestions.forEach { resId ->
1610− val text = stringResource(resId)
1611− androidx.compose.material3.AssistChip(
1612− onClick = { onSuggestion(text) },
1613− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1620−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1622−private fun RevertBanner(onUndo: () -> Unit) {
1624− color = MaterialTheme.colorScheme.tertiaryContainer,
1625− tonalElevation = 2.dp,
1626− modifier = Modifier.fillMaxWidth(),
1629− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1630− verticalAlignment = Alignment.CenterVertically,
1631− horizontalArrangement = Arrangement.SpaceBetween,
1633− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1635− Icons.Filled.Restore,
1636− contentDescription = null,
1637− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1638− modifier = Modifier.size(18.dp),
1641− stringResource(R.string.reverted_banner),
1642− style = MaterialTheme.typography.bodySmall,
1643− color = MaterialTheme.colorScheme.onTertiaryContainer,
1644− modifier = Modifier.padding(start = 8.dp),
1647− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1652−/** A banner shown while messages composed offline are queued in the outbox, with a
1653− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1655−private fun OutboxBanner(
1658− onFlush: () -> Unit,
1659− onDiscard: () -> Unit,
1662− color = MaterialTheme.colorScheme.secondaryContainer,
1663− tonalElevation = 2.dp,
1664− modifier = Modifier.fillMaxWidth(),
1667− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1668− verticalAlignment = Alignment.CenterVertically,
1669− horizontalArrangement = Arrangement.SpaceBetween,
1671− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1673− CircularProgressIndicator(
1674− Modifier.size(16.dp),
1675− strokeWidth = 2.dp,
1676− color = MaterialTheme.colorScheme.onSecondaryContainer,
1678− Spacer(Modifier.size(8.dp))
1682− stringResource(R.string.outbox_sending)
1684− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1685− stringResource(res, count)
1687− style = MaterialTheme.typography.bodySmall,
1688− color = MaterialTheme.colorScheme.onSecondaryContainer,
1692− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1693− TextButton(onClick = onDiscard) {
1694− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1701−/** Prompt for a one-off shell command to run in the session's worktree. */
1703−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1704− var command by rememberSaveable { mutableStateOf("") }
1706− onDismissRequest = onDismiss,
1707− title = { Text(stringResource(R.string.run_shell_command)) },
1711− onValueChange = { command = it },
1712− modifier = Modifier.fillMaxWidth(),
1713− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1714− label = { Text(stringResource(R.string.shell_command_label)) },
1716− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1717− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1722− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1723− enabled = command.isNotBlank(),
1724− ) { Text(stringResource(R.string.run)) }
1726− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1731− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1732− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1733− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1735−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1737−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1738− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1739− * streaming, not just plain assistant text. O(1). */
1740−private fun streamingContentLength(part: Part?): Int = when (part) {
1741− is TextPart -> part.text.length
1742− is ReasoningPart -> part.text.length
1743− is ToolPart -> when (val st = part.state) {
1744− is ToolCompleted -> st.output?.length ?: 0
1745− is ToolError -> st.error?.length ?: 0
1746− is ToolRunning -> st.title?.length ?: 0
1752−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1753− * dialog but lives in the chat screen so the user can rename without backing out to
1754− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1756−private fun RenameSessionChatDialog(
1757− initialTitle: String,
1758− onDismiss: () -> Unit,
1759− onConfirm: (String) -> Unit,
1761− // Seed the field once (no key input) so a later external title change — e.g. opencode
1762− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1763− // doesn't re-initialize the box and discard the user's in-progress edit.
1764− var title by rememberSaveable { mutableStateOf(initialTitle) }
1766− onDismissRequest = onDismiss,
1767− title = { Text(stringResource(R.string.rename_session_chat)) },
1771− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1772− modifier = Modifier.fillMaxWidth(),
1773− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1774− label = { Text(stringResource(R.string.rename_session_chat)) },
1776− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1777− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1781− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1782− Text(stringResource(R.string.save))
1786− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1792− * A single item in the chat message list — either a [Message] bubble or a day
1793− * [Separator] inserted before the first message of a new day. The separator shifts
1794− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1795− * the [List] of these items (not `messages.size`/`lastIndex`).
1797−private sealed interface MessageListItem {
1799− val contentType: Any
1801− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1802− override val contentType: Any get() = message.info::class
1805− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1806− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1807− // can share a label (e.g. an untimestamped message — empty label — between two
1808− // same-day messages, or two untimestamped groups), and a label-only key would
1809− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1810− // stable for a given message ordering so slots aren't needlessly recreated.
1811− override val key: Any get() = "sep_${ordinal}_$label"
1812− // Separators share a contentType so the LazyColumn can recycle their slots.
1813− override val contentType: Any get() = "separator"
1818− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1819− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1820− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1821− * Messages with no timestamp are grouped under an empty-label separator only if they
1822− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1824− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1825− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1826− * labels; older days fall back to a locale-stable medium-date format.
1828−private fun buildMessageListItems(
1829− messages: List<MessageWithParts>,
1830− todayLabel: String,
1831− yesterdayLabel: String,
1832−): List<MessageListItem> {
1833− if (messages.isEmpty()) return emptyList()
1834− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1835− val dateFmt = mediumDateFormat()
1836− val result = ArrayList<MessageListItem>(messages.size + 4)
1837− val seenKeys = HashSet<String>(messages.size * 2)
1838− var lastDayKey: String? = null
1840− var emptyIdOrdinal = 0
1842− for (message in messages) {
1843− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1844− val dayKey = ts?.let { dayKey(it) } ?: ""
1845− // Emit a separator before the very first message (so a leading un-timestamped message
1846− // still gets the first divider, empty label and all), and thereafter only when crossing
1847− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1848− // neither emits its own separator nor resets the day — otherwise a following same-day
1849− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1850− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1851− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1853− if (dayKey.isNotEmpty()) lastDayKey = dayKey
1855− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1856− // empty id — and the reducer intentionally keeps several such messages as distinct
1857− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1858− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1859− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1860− if (!seenKeys.add(key)) {
1862− while (!seenKeys.add("$key#$suffix")) suffix++
1863− key = "$key#$suffix"
1865− result.add(MessageListItem.Message(message, key))
1871− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1873− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1874− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1875− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1876− * every message on every token. Message timestamps are immutable once assigned, so we
1877− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1878− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1879− * thread during composition, so the coarse lock is uncontended.
1881−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1882− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1885−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1886− dayKeyCache.getOrPut(epochMillis) {
1887− java.time.Instant.ofEpochMilli(epochMillis)
1888− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1892−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1893−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1894−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1895−private var cachedDateFmt: java.text.DateFormat? = null
1896−private var cachedDateFmtLocale: java.util.Locale? = null
1898−private fun mediumDateFormat(): java.text.DateFormat {
1899− val locale = java.util.Locale.getDefault()
1900− val existing = cachedDateFmt
1901− if (existing != null && cachedDateFmtLocale == locale) return existing
1902− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1904− cachedDateFmtLocale = locale
1909− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1910− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1911− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1914−private fun dayLabel(
1917− today: java.time.LocalDate,
1918− todayLabel: String,
1919− yesterdayLabel: String,
1920− dateFmt: java.text.DateFormat,
1922− if (dayKey.isEmpty()) return ""
1923− val epochDay = dayKey.toLongOrNull() ?: return ""
1924− val date = java.time.LocalDate.ofEpochDay(epochDay)
1926− date == today -> todayLabel
1927− date == today.minusDays(1) -> yesterdayLabel
1928− else -> dateFmt.format(java.util.Date(ts))
1933− * A centered day divider in the message list. Renders nothing for an empty label
1934− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1937−private fun DateSeparator(label: String) {
1938− if (label.isBlank()) return
1940− modifier = Modifier.fillMaxWidth(),
1941− horizontalArrangement = Arrangement.Center,
1944− color = MaterialTheme.colorScheme.surfaceVariant,
1945− shape = MaterialTheme.shapes.small,
1949− style = MaterialTheme.typography.labelSmall,
1950− color = MaterialTheme.colorScheme.onSurfaceVariant,
1951− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),