@@ -1,2696 +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.animation.core.RepeatMode
15−import androidx.compose.animation.core.animateFloat
16−import androidx.compose.animation.core.infiniteRepeatable
17−import androidx.compose.animation.core.rememberInfiniteTransition
18−import androidx.compose.animation.core.tween
19−import androidx.compose.foundation.background
20−import androidx.compose.foundation.clickable
21−import androidx.compose.foundation.content.contentReceiver
22−import androidx.compose.foundation.layout.Arrangement
23−import androidx.compose.foundation.layout.Box
24−import androidx.compose.foundation.layout.Column
25−import androidx.compose.foundation.layout.FlowRow
26−import androidx.compose.foundation.layout.PaddingValues
27−import androidx.compose.foundation.layout.Row
28−import androidx.compose.foundation.layout.Spacer
29−import androidx.compose.foundation.layout.WindowInsets
30−import androidx.compose.foundation.layout.fillMaxSize
31−import androidx.compose.foundation.layout.fillMaxWidth
32−import androidx.compose.foundation.layout.height
33−import androidx.compose.foundation.layout.imePadding
34−import androidx.compose.foundation.layout.navigationBars
35−import androidx.compose.foundation.layout.padding
36−import androidx.compose.foundation.layout.size
37−import androidx.compose.foundation.layout.union
38−import androidx.compose.foundation.layout.widthIn
39−import androidx.compose.foundation.layout.windowInsetsPadding
40−import androidx.compose.foundation.layout.wrapContentWidth
41−import androidx.compose.foundation.lazy.LazyColumn
42−import androidx.compose.foundation.lazy.items
43−import androidx.compose.foundation.lazy.rememberLazyListState
44−import androidx.compose.foundation.shape.RoundedCornerShape
45−import androidx.compose.material.icons.Icons
46−import androidx.compose.material.icons.automirrored.filled.ArrowBack
47−import androidx.compose.material.icons.automirrored.filled.Send
48−import androidx.compose.material.icons.filled.Add
49−import androidx.compose.material.icons.filled.AutoAwesome
50−import androidx.compose.material.icons.filled.Delete
51−import androidx.compose.material.icons.filled.Description
52−import androidx.compose.material.icons.filled.Close
53−import androidx.compose.material.icons.filled.Edit
54−import androidx.compose.material.icons.filled.Expand
55−import androidx.compose.material.icons.filled.ExpandLess
56−import androidx.compose.material.icons.filled.ExpandMore
57−import androidx.compose.material.icons.filled.Search
58−import androidx.compose.material.icons.filled.KeyboardArrowDown
59−import androidx.compose.material.icons.filled.KeyboardArrowUp
60−import androidx.compose.material.icons.filled.Mic
61−import androidx.compose.material.icons.filled.MoreVert
62−import androidx.compose.material.icons.filled.PhotoCamera
63−import androidx.compose.material.icons.filled.PhotoLibrary
64−import androidx.compose.material.icons.filled.Refresh
65−import androidx.compose.material.icons.filled.Restore
66−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
67−import androidx.compose.material.icons.automirrored.filled.Reply
68−import androidx.compose.material.icons.filled.Schedule
69−import androidx.compose.material.icons.filled.Stop
70−import androidx.compose.material3.AlertDialog
71−import androidx.compose.material3.Badge
72−import androidx.compose.material3.BadgedBox
73−import androidx.compose.material3.Button
74−import androidx.compose.material3.CircularProgressIndicator
75−import androidx.compose.material3.SmallFloatingActionButton
76−import androidx.compose.material3.DropdownMenu
77−import androidx.compose.material3.DropdownMenuItem
78−import androidx.compose.material3.ExperimentalMaterial3Api
79−import androidx.compose.material3.ExtendedFloatingActionButton
80−import androidx.compose.material3.FloatingActionButton
81−import androidx.compose.material3.Icon
82−import androidx.compose.material3.IconButton
83−import androidx.compose.material3.MaterialTheme
84−import androidx.compose.material3.OutlinedTextField
85−import androidx.compose.material3.Scaffold
86−import androidx.compose.material3.SnackbarDuration
87−import androidx.compose.material3.SwipeToDismissBox
88−import androidx.compose.material3.SwipeToDismissBoxValue
89−import androidx.compose.material3.rememberSwipeToDismissBoxState
90−import androidx.compose.material3.SnackbarHost
91−import androidx.compose.material3.SnackbarHostState
92−import androidx.compose.material3.SnackbarResult
93−import androidx.compose.material3.Surface
94−import androidx.compose.material3.Text
95−import androidx.compose.material3.TextButton
96−import androidx.compose.material3.TopAppBar
97−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
98−import androidx.compose.runtime.Composable
99−import androidx.compose.runtime.CompositionLocalProvider
100−import androidx.compose.runtime.DisposableEffect
101−import androidx.compose.runtime.LaunchedEffect
102−import androidx.compose.runtime.derivedStateOf
103−import androidx.compose.runtime.getValue
104−import androidx.compose.runtime.mutableIntStateOf
105−import androidx.compose.runtime.mutableLongStateOf
106−import androidx.compose.runtime.mutableStateOf
107−import androidx.compose.runtime.produceState
108−import androidx.compose.runtime.remember
109−import androidx.compose.runtime.rememberCoroutineScope
110−import androidx.compose.runtime.rememberUpdatedState
111−import androidx.compose.runtime.saveable.rememberSaveable
112−import androidx.compose.runtime.setValue
113−import androidx.compose.runtime.snapshotFlow
114−import androidx.compose.foundation.text.KeyboardActions
115−import androidx.compose.foundation.text.KeyboardOptions
116−import androidx.compose.ui.text.input.KeyboardCapitalization
117−import androidx.compose.ui.Alignment
118−import androidx.compose.ui.Modifier
119−import androidx.compose.ui.draw.alpha
120−import androidx.compose.ui.draw.clip
121−import androidx.compose.ui.focus.focusRequester
122−import androidx.compose.ui.input.key.Key
123−import androidx.compose.ui.input.key.KeyEventType
124−import androidx.compose.ui.input.key.isCtrlPressed
125−import androidx.compose.ui.input.key.isShiftPressed
126−import androidx.compose.ui.input.key.key
127−import androidx.compose.ui.input.key.onPreviewKeyEvent
128−import androidx.compose.ui.input.key.type
129−import androidx.compose.ui.layout.onSizeChanged
130−import androidx.compose.ui.platform.LocalContext
131−import androidx.compose.ui.platform.LocalDensity
132−import androidx.compose.ui.platform.LocalHapticFeedback
133−import androidx.compose.ui.platform.LocalView
134−import androidx.compose.ui.platform.testTag
135−import androidx.compose.ui.res.stringResource
136−import androidx.compose.ui.semantics.Role
137−import androidx.compose.ui.semantics.contentDescription
138−import androidx.compose.ui.semantics.heading
139−import androidx.compose.ui.semantics.semantics
140−import androidx.compose.ui.text.input.ImeAction
141−import androidx.compose.ui.text.style.TextOverflow
142−import androidx.compose.ui.unit.dp
143−import androidx.lifecycle.compose.collectAsStateWithLifecycle
144−import androidx.lifecycle.viewmodel.compose.viewModel
145−import kotlinx.coroutines.Dispatchers
146−import kotlinx.coroutines.coroutineScope
147−import kotlinx.coroutines.delay
148−import kotlinx.coroutines.flow.distinctUntilChanged
149−import kotlinx.coroutines.launch
150−import kotlinx.coroutines.withContext
151−import soy.iko.opencode.data.model.Part
152−import soy.iko.opencode.data.model.MessageWithParts
153−import soy.iko.opencode.data.model.ReasoningPart
154−import soy.iko.opencode.data.model.TextPart
155−import soy.iko.opencode.data.model.ToolCompleted
156−import soy.iko.opencode.data.model.ToolError
157−import soy.iko.opencode.data.model.ToolPart
158−import soy.iko.opencode.data.model.ToolRunning
159−import soy.iko.opencode.data.model.FilePart
160−import soy.iko.opencode.data.model.sourcePath
161−import soy.iko.opencode.data.model.inputElement
162−import soy.iko.opencode.data.network.EventStreamClient
163−import soy.iko.opencode.data.network.NetworkConfig
164−import soy.iko.opencode.di.AppContainer
165−import soy.iko.opencode.R
166−import soy.iko.opencode.ui.components.CommandPalette
167−import soy.iko.opencode.ui.components.ConnectionBanner
168−import soy.iko.opencode.ui.components.DiffView
169−import soy.iko.opencode.ui.components.PaletteAction
170−import soy.iko.opencode.ui.components.LocalReducedMotion
171−import soy.iko.opencode.ui.components.LocalSearchHighlight
172−import soy.iko.opencode.ui.components.reducedMotionAnimateItem
173−import soy.iko.opencode.ui.components.copyToClipboard
174−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
175−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
176−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
177−import soy.iko.opencode.ui.components.showToast
178−import soy.iko.opencode.ui.components.toImageContext
179−import soy.iko.opencode.ui.vmFactory
180−import soy.iko.opencode.util.runCatchingCancellable
182−@OptIn(ExperimentalMaterial3Api::class)
185− container: AppContainer,
188− onOpenFile: ((String) -> Unit)? = null,
189− onOpenSession: ((String) -> Unit)? = null,
191− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
192− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
193− val running by vm.running.collectAsStateWithLifecycle()
194− val aborting by vm.aborting.collectAsStateWithLifecycle()
195− val loading by vm.loading.collectAsStateWithLifecycle()
196− val loadError by vm.loadError.collectAsStateWithLifecycle()
197− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
198− val models by vm.models.collectAsStateWithLifecycle()
199− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
200− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
201− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
202− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
203− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
204− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
205− val agents by vm.agents.collectAsStateWithLifecycle()
206− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
207− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
208− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
209− val commands by vm.commands.collectAsStateWithLifecycle()
210− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
211− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
212− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
213− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
214− val draft by vm.draft.collectAsStateWithLifecycle()
215− val attachments by vm.attachments.collectAsStateWithLifecycle()
216− val reverted by vm.reverted.collectAsStateWithLifecycle()
217− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
218− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
219− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
220− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
221− val isOnline by container.isOnline.collectAsStateWithLifecycle()
222− val haptics = LocalHapticFeedback.current
223− val scope = rememberCoroutineScope()
224− val shareContext = LocalContext.current
225− val defaultShareSubject = stringResource(R.string.share_subject)
226− val sessionLabel = stringResource(R.string.session)
227− val defaultModelLabel = stringResource(R.string.default_model)
228− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
230− append(selectedModel?.modelLabel ?: defaultModelLabel)
231− selectedAgent?.let { append(" · $it") }
235− // Connection profile (with auth) for rendering inline image attachments.
236− // Collect as state so a server switch recomposes the image context.
237− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
238− val imageContext = remember(activeConnection?.profile) {
239− activeConnection?.profile?.toImageContext()
242− // Mark this session as read while the user is viewing it; clear on leave so new
243− // background activity can badge it again.
244− DisposableEffect(sessionId) {
245− container.setCurrentSession(sessionId)
246− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
249− // Navigate away when the session is deleted via SSE so the user isn't left
250− // on a zombie screen showing a conversation that no longer exists. Surface a
251− // toast (not a snackbar) because the screen is about to be popped — a snackbar
252− // would be torn down before the user could read it, while a toast survives.
253− // Covers both SSE-driven deletion (deleted on another device) and a user-
254− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
255− // sets the same flag on success).
256− val deletedContext = LocalContext.current
257− LaunchedEffect(sessionDeleted) {
258− if (sessionDeleted) {
259− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
264− val snackbar = remember { SnackbarHostState() }
265− val retryLabel = stringResource(R.string.retry)
266− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
267− // Dedicated focus requester for the in-conversation search field. The overflow menu's
268− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
269− // (the composer), so typing went to the composer instead of the search field.
270− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
271− var showModelPicker by rememberSaveable { mutableStateOf(false) }
272− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
273− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
274− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
275− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
276− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
277− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
278− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
279− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
280− var showShellDialog by rememberSaveable { mutableStateOf(false) }
281− var showPalette by rememberSaveable { mutableStateOf(false) }
282− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
283− var searchActive by rememberSaveable { mutableStateOf(false) }
284− var chatSearch by rememberSaveable { mutableStateOf("") }
285− // Index of the currently-focused in-conversation search match (into the filtered list).
286− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
287− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
288− // required reading each message to find the term).
289− var searchPos by rememberSaveable { mutableIntStateOf(0) }
290− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
291− // a confirmation dialog (from both the overflow menu and the command palette).
292− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
293− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
295− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
296− // action list doesn't need a Composable context. Actions map to the same handlers the
297− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
298− val paletteModelLabel = stringResource(R.string.palette_switch_model)
299− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
300− val paletteCommandLabel = stringResource(R.string.palette_run_command)
301− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
302− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
303− val paletteShellLabel = stringResource(R.string.run_shell_command)
304− val paletteActions = remember(
305− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
306− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
309− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
310− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
311− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
312− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
313− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
314− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
318− // Keep the screen awake while the agent is working in *this* session. The foreground
319− // service that holds process priority during a run is managed app-wide off
320− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
321− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
322− // SSE stream before the completion notification fires.
323− val currentView = LocalView.current
324− val appContext = LocalContext.current.applicationContext
325− DisposableEffect(running) {
326− currentView.keepScreenOn = running
327− onDispose { currentView.keepScreenOn = false }
330− LaunchedEffect(Unit) {
331− vm.errorEvents.collect { event ->
332− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
333− // message-load failure) would silently re-submit the last prompt on tap.
334− val result = if (event.retryable) {
335− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
337− snackbar.showSnackbar(event.message)
339− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
343− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
344− // window on the container; show the snackbar over the conversation the user is viewing so
345− // they can cancel without being navigated to the session list first. If the window expires
346− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
347− val undoLabel = stringResource(R.string.undo)
348− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
349− LaunchedEffect(Unit) {
350− vm.deleteUndoEvents.collect {
352− val dismisser = launch {
353− delay(NetworkConfig.undoDeleteDelayMs)
354− snackbar.currentSnackbarData?.dismiss()
356− val result = snackbar.showSnackbar(
357− message = sessionDeletedLabel,
358− actionLabel = undoLabel,
359− duration = SnackbarDuration.Indefinite,
362− if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
367− // --- Attachments, voice, and share-link plumbing ---
368− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
369− val attachFailedMsg = stringResource(R.string.attachment_failed)
370− val attachLimitMsg = stringResource(R.string.attachment_limit)
371− val noCameraMsg = stringResource(R.string.no_camera_app)
372− val noVoiceMsg = stringResource(R.string.no_voice_app)
373− val voicePrompt = stringResource(R.string.voice_prompt)
374− val linkCopiedMsg = stringResource(R.string.link_copied)
375− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
377− // Count of picks currently being read + base64-encoded off the main thread, so the
378− // composer can show a staging placeholder immediately (chips only materialize once done).
379− var stagingCount by remember { mutableStateOf(0) }
381− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
382− // per-prompt count cap and surfacing per-file errors without aborting the batch.
383− fun stageUris(uris: List<Uri>) {
384− if (uris.isEmpty()) return
389− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
390− snackbar.showSnackbar(attachLimitMsg)
393− when (val result = uri.toAttachmentResult(appContext)) {
394− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
395− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
396− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
405− val photoPicker = rememberLauncherForActivityResult(
406− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
407− ) { uris -> stageUris(uris) }
409− val filePicker = rememberLauncherForActivityResult(
410− ActivityResultContracts.GetMultipleContents(),
411− ) { uris -> stageUris(uris) }
413− // Uri survives a config change mid-capture so the TakePicture result still resolves.
414− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
415− val cameraLauncher = rememberLauncherForActivityResult(
416− ActivityResultContracts.TakePicture(),
418− val uri = pendingCaptureUri
419− pendingCaptureUri = null
420− if (success && uri != null) stageUris(listOf(uri))
423− val voiceLauncher = rememberLauncherForActivityResult(
424− ActivityResultContracts.StartActivityForResult(),
426− if (result.resultCode == Activity.RESULT_OK) {
427− val spoken = result.data
428− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
430− ?.takeIf { it.isNotBlank() }
431− if (spoken != null) {
432− // Append to the existing draft rather than replacing, so dictation adds to
433− // whatever the user already typed.
434− val current = vm.draft.value
435− val combined = if (current.isBlank()) spoken else "$current $spoken"
436− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
441− fun launchCamera() {
442− val uri = newCameraCaptureUri(appContext)
444− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
447− pendingCaptureUri = uri
448− runCatching { cameraLauncher.launch(uri) }
449− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
453− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
454− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
455− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
457− runCatching { voiceLauncher.launch(intent) }
458− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
461− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
462− LaunchedEffect(Unit) {
463− vm.shareLinkEvents.collect { url ->
464− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
465− snackbar.showSnackbar(linkCopiedMsg)
469− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
470− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
471− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
472− // a dropped branch-navigation event in the gap.
473− val branchedMsg = stringResource(R.string.branch_created)
474− LaunchedEffect(Unit) {
475− vm.branchEvents.collect { newId ->
476− showToast(shareContext, branchedMsg)
477− onOpenSession?.invoke(newId)
481− // Stage images shared into the app (via the system share sheet) as attachments.
482− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
483− // while this ChatScreen is already composed — which happens in two-pane mode, where the
484− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
485− // only fire on first composition. consumePendingSharedMedia() atomically drains the
486− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
487− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
488− LaunchedEffect(pendingSharedMedia) {
489− val shared = container.consumePendingSharedMedia()
490− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
494− if (vm.send(draft)) {
495− // TextHandleMove (a light tick) is semantically right for a send commit;
496− // LongPress is reserved for long-press/swipe gestures.
497− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
501− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
504− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
505− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
506− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
507− // typing (and the composer's own Enter-to-send handling) is untouched.
508− modifier = Modifier.onPreviewKeyEvent { ev ->
509− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
511− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
512− // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
513− // the field so the user can type immediately.
514− ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
515− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
516− ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
517− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
518− showStopConfirm = true; true
526− val changeLabel = stringResource(R.string.change_model_agent)
527− // The subtitle reads "model · agent", so tapping the title offers *both*
528− // — a small menu picks which picker to open. Previously the tap went
529− // straight to the model picker, leaving the agent changeable only via
530− // the overflow menu despite the title implying otherwise.
533− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
534− // node; the click label rides on `clickable` (onClickLabel) instead of
535− // an explicit contentDescription, which would have SUPPRESSED the child
536− // Texts and announced only "Change model and agent".
540− onClickLabel = changeLabel,
541− ) { showTitleMenu = true }
542− .semantics(mergeDescendants = true) {},
543− verticalAlignment = Alignment.CenterVertically,
545− Column(modifier = Modifier.weight(1f, fill = false)) {
546− // maxLines=1 + Ellipsis so a long session title can't wrap and
547− // push the top bar to multiple lines, shifting the whole layout.
549− sessionTitle ?: sessionLabel,
551− overflow = TextOverflow.Ellipsis,
555− style = MaterialTheme.typography.labelSmall,
556− color = MaterialTheme.colorScheme.onSurfaceVariant,
558− overflow = TextOverflow.Ellipsis,
561− // Always show the affordance so the title reads as tappable even when
562− // the model catalog failed to load (models empty). Without it the title
563− // is indistinguishable from plain text and the pickers are effectively
564− // undiscoverable — and the dropdown items already disable themselves
565− // while a catalog is loading or unavailable.
567− Icons.Filled.KeyboardArrowDown,
568− contentDescription = null,
569− tint = MaterialTheme.colorScheme.onSurfaceVariant,
570− modifier = Modifier.size(20.dp),
573− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
575− text = { Text(stringResource(R.string.palette_switch_model)) },
576− enabled = !modelsLoading || models.isNotEmpty(),
577− onClick = { showTitleMenu = false; showModelPicker = true },
580− text = { Text(stringResource(R.string.palette_choose_agent)) },
581− enabled = !agentsLoading || agents.isNotEmpty(),
582− onClick = { showTitleMenu = false; showAgentPicker = true },
588− IconButton(onClick = {
589− if (running) showExitConfirm = true else onBack()
591− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
595− // At-a-glance run status in the top bar. When the user is scrolled
596− // up (jump-to-latest FAB visible), the input-bar Stop button and the
597− // trailing "working…" row are off-screen, so a top-bar spinner is the
598− // only signal the agent is still working.
600− val workingLabel = stringResource(R.string.working)
601− CircularProgressIndicator(
602− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
606− // Manual refresh: forces an SSE reconnect, which re-seeds messages
607− // from REST. A recovery path when the stream silently drops and the
608− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
609− // immediate tap feedback — the SSE reconnect may not visibly change
610− // the connection state when already Connected, so without it the tap
611− // appears to do nothing.
612− val refreshLabel = stringResource(R.string.refresh)
614− onClick = { vm.refreshMessages() },
615− enabled = activeConnection != null && !refreshing,
618− CircularProgressIndicator(
619− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
623− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
626− // Overflow menu consolidates the less-frequent actions (share,
627− // commands, agent, model, rename, delete) so the top bar stays
628− // scannable on narrow phones — previously 5 icons crowded the bar
629− // alongside the back button and tappable title. Catalog-loading
630− // spinners stay inline (next to the overflow) so a load state is
631− // visible without opening the menu.
632− val moreLabel = stringResource(R.string.more)
633− val loadingLabel = stringResource(R.string.loading)
634− val shareLabel = stringResource(R.string.share_conversation)
635− val commandsLabel = stringResource(R.string.commands)
636− val renameLabel = stringResource(R.string.rename_session_chat)
637− val deleteLabel = stringResource(R.string.delete_session_chat)
638− val createShareLabel = stringResource(R.string.create_share_link)
639− val copyShareLabel = stringResource(R.string.copy_share_link)
640− val stopShareLabel = stringResource(R.string.stop_sharing)
641− val summarizeLabel = stringResource(R.string.summarize_conversation)
642− val initLabel = stringResource(R.string.generate_agents_md)
643− val shellLabel = stringResource(R.string.run_shell_command)
645− IconButton(onClick = { showOverflowMenu = true }) {
646− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
649− expanded = showOverflowMenu,
650− onDismissRequest = { showOverflowMenu = false },
653− text = { Text(shareLabel) },
654− enabled = hasMessages,
656− showOverflowMenu = false
658− val md = withContext(Dispatchers.Default) {
659− buildConversationMarkdown(vm.messages.value, sessionTitle)
661− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
662− type = "text/markdown"
663− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
664− putExtra(android.content.Intent.EXTRA_TEXT, md)
666− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
667− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
672− text = { Text(commandsLabel) },
673− enabled = !commandsLoading || commands.isNotEmpty(),
674− onClick = { showOverflowMenu = false; showCommandPicker = true },
677− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
678− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
681− text = { Text(stringResource(R.string.find_in_conversation)) },
683− showOverflowMenu = false
685− // Focus is requested by the LaunchedEffect(searchActive)
686− // below, which waits for the search field to be composed
687− // before requesting focus (calling requestFocus here would
688− // target a field that isn't in the composition yet).
691− androidx.compose.material3.HorizontalDivider()
692− // Session sharing: create a public link, copy an existing one, or revoke it.
693− if (shareUrl == null) {
695− text = { Text(createShareLabel) },
696− enabled = hasMessages,
697− onClick = { showOverflowMenu = false; vm.shareSession() },
701− text = { Text(copyShareLabel) },
703− showOverflowMenu = false
705− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
706− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
711− text = { Text(stopShareLabel) },
712− onClick = { showOverflowMenu = false; vm.unshareSession() },
716− text = { Text(summarizeLabel) },
717− enabled = hasMessages && !running,
718− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
721− text = { Text(initLabel) },
723− onClick = { showOverflowMenu = false; showInitConfirm = true },
726− text = { Text(shellLabel) },
728− onClick = { showOverflowMenu = false; showShellDialog = true },
730− androidx.compose.material3.HorizontalDivider()
732− text = { Text(renameLabel) },
733− onClick = { showOverflowMenu = false; showRenameDialog = true },
736− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
737− onClick = { showOverflowMenu = false; showDeleteDialog = true },
740− // While a catalog is initially loading (empty list + loading flag),
741− // show a tiny inline spinner beside the overflow so the user can see
742− // a load is in progress without opening the menu. Once loaded the
743− // spinner disappears; the menu items are always enabled (tapping a
744− // picker with no items shows the "no models/agents/commands" state).
745− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
746− (agentsLoading && agents.isEmpty()) ||
747− (modelsLoading && models.isEmpty())
748− if (catalogLoading) {
749− CircularProgressIndicator(
751− .align(Alignment.TopEnd)
753− .semantics { contentDescription = loadingLabel },
761− snackbarHost = { SnackbarHost(snackbar) },
763− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
764− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
765− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
766− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
768− // Pinned above the composer so the agent's plan and progress stay visible
769− // while scrolled up mid-run; renders nothing when there's no plan.
770− TodoPlanBar(todoPlan)
771− val bannerMotion = rememberVisibilityTransitions()
774− enter = bannerMotion.enter,
775− exit = bannerMotion.exit,
779− onUndo = { vm.unrevert() },
783− visible = queuedOffline.isNotEmpty(),
784− enter = bannerMotion.enter,
785− exit = bannerMotion.exit,
788− count = queuedOffline.size,
789− sending = outboxSending,
790− onFlush = { vm.flushQueued() },
791− onDiscard = { vm.discardAllQueued() },
796− onValueChange = vm::updateDraft,
798− aborting = aborting,
799− enabled = activeConnection != null,
800− sendOnEnter = sendOnEnter,
802− onAbort = { showStopConfirm = true },
803− queuedFollowUp = queuedFollowUp,
804− onQueueFollowUp = vm::queueFollowUp,
805− onCancelQueue = { vm.queueFollowUp("") },
806− focusRequester = inputFocusRequester,
807− attachments = attachments,
808− staging = stagingCount > 0,
809− onRemoveAttachment = vm::removeAttachment,
812− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
815− onPickFile = { filePicker.launch("*/*") },
816− onCamera = { launchCamera() },
817− onVoice = { launchVoice() },
818− onPasteImage = { stageUris(it) },
823− // Collect messages inside the content lambda so streaming token updates
824− // recompose only this subtree, not the top bar / input bar / 20+ other
825− // state reads in the ChatScreen body.
826− val messages by vm.messages.collectAsStateWithLifecycle()
827− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
828− val listState = rememberLazyListState()
829− val contentScope = rememberCoroutineScope()
830− val timeTick = rememberRelativeTimeTick()
831− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
832− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
833− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
834− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
835− androidx.compose.runtime.LaunchedEffect(listState) {
836− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
837− .distinctUntilChanged()
838− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
839− } // Group messages by day and interleave date separators so a long conversation
840− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
841− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
842− // outside the PullToRefreshBox so the auto-scroll effects below can reference
843− // the same list the LazyColumn renders (separators shift the indices vs. the
844− // raw messages list, so scroll targets must be in listItems space).
845− val todayLabel = stringResource(R.string.today)
846− val yesterdayLabel = stringResource(R.string.yesterday)
847− // In-conversation search: when active, narrow to messages whose text contains the query.
848− // Computed on the filtered set so day separators still align with the visible messages.
849− val searchQuery = chatSearch.trim()
850− val searchMessages = remember(messages, searchQuery) {
851− if (searchQuery.isEmpty()) messages
852− else messages.filter { m ->
855− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
856− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
858− // Match the tool name plus its running/completed/error text and the
859− // stringified input, so searching for an error string or a file the
860− // tool touched actually finds the message it appeared in.
861− p.tool.contains(searchQuery, ignoreCase = true) ||
862− (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
863− (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
864− p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
865− (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
866− p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
868− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
869− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
875− // Keep the focused-match index in range as the query (and thus the match set) changes.
876− // A new query resets to the first match; a shrunk set clamps to the last valid index.
877− LaunchedEffect(searchQuery, searchMessages.size) {
878− if (searchPos >= searchMessages.size) searchPos = 0
880− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
881− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
883− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
884− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
885− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
886− // would capture the first composition's list — which is empty, since `messages`
887− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
888− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
889− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
890− // whose value tracks the latest list.
891− val currentListItems by rememberUpdatedState(listItems)
893− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
894− // while the user was scrolled away from the bottom, cleared once they return. A count
895− // (vs. a bare dot) tells the user how much they missed at a glance.
896− var newContentCount by remember { mutableIntStateOf(0) }
898− val isPinnedToBottom by remember {
900− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
901− // When a run is active, the LazyColumn has one trailing "__typing"
902− // item after the last list item. Account for it so "pinned to bottom"
903− // includes the working indicator — otherwise the pin check targets
904− // listItems.lastIndex, the typing row sits just below the viewport,
905− // and the user never sees the progress indicator even when pinned.
906− val items = currentListItems
907− val effectiveLast = if (running) items.size else items.lastIndex
908− lastVisible >= effectiveLast || items.isEmpty()
912− // Jump to the newest message once, when the conversation first loads. Guarded by a
913− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
914− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
915− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
916− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
917− LaunchedEffect(listItems.isNotEmpty()) {
918− if (listItems.isNotEmpty() && !didInitialScroll) {
919− // When a run is active the LazyColumn has a trailing "__typing" row at
920− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
921− // running session lands truly pinned to bottom and streaming auto-scroll engages.
922− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
923− didInitialScroll = true
927− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
928− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
929− // isPinnedToBottom check flips to false the instant you send — freezing
930− // auto-scroll. If the user was pinned to the last item just before the run
931− // began, bring the typing row into view so the pin (and streaming follow) is
932− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
933− // recomputed to false by now) so we don't scroll when the user had scrolled up.
934− LaunchedEffect(running) {
935− if (running && listItems.isNotEmpty()) {
936− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
937− if (lastVisible >= listItems.lastIndex) {
938− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
943− // Scroll the focused search match into view whenever the user steps through results with
944− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
945− // includes date separators) and animates there.
946− LaunchedEffect(searchPos, searchQuery, listItems) {
947− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
948− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
949− val index = listItems.indexOfFirst {
950− it is MessageListItem.Message && it.message.info.id == target.info.id
952− if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
955− LaunchedEffect(Unit) {
959− // Track list size + the streaming length of the last part so we auto-scroll
960− // as content arrives, plus the pinned flag. A small data class with primitive
961− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
962− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
963− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
964− // and tool output — not just TextPart — keeps a pinned view following a long
965− // reasoning/tool block while it streams (previously it stalled at 0).
966− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
967− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
968− }.collect { signal ->
969− if (signal.pinned) {
970− // Back at the bottom: clear the new-content badge.
972− if (signal.size > 0) {
973− // Scroll to the effective last index, including the trailing
974− // "__typing" row when a run is active so the working indicator
975− // is brought into view (not just the last message).
976− val items = currentListItems
977− val target = if (running) items.size else items.lastIndex
978− listState.scrollToItem(target)
980− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
981− // Content arrived while scrolled up — increment the jump-to-latest badge.
982− // Only count whole new items (not per-token growth) so the number reflects
983− // new messages, not a token count.
984− if (signal.size > prevSize) newContentCount += signal.size - prevSize
985− else if (newContentCount == 0) newContentCount = 1
987− prevSize = signal.size
988− prevLen = signal.lastTextLength
992− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
993− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
994− // content padding accounts for the bottomBar's raised height, so the message
995− // list is already above the keyboard. Adding imePadding here would double-apply
996− // the IME inset and push messages too far up.
997− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
998− if (activeConnection == null) {
1000− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1001− horizontalAlignment = Alignment.CenterHorizontally,
1004− stringResource(R.string.not_connected),
1005− color = MaterialTheme.colorScheme.error,
1007− Spacer(Modifier.size(12.dp))
1008− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1009− if (reconnecting) {
1010− CircularProgressIndicator(
1011− Modifier.size(20.dp),
1012− color = MaterialTheme.colorScheme.onPrimary,
1013− strokeWidth = 2.dp,
1016− Text(stringResource(R.string.reconnect))
1021− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1022− // Measure the banner's actual height instead of hardcoding 44dp. At large
1023− // accessibility font scales the banner's labelMedium text + spinner + Retry
1024− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1025− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1026− // fires while the banner is composed (visible), so gate the inset on
1027− // bannerVisible and fall back to 44dp until the first measurement arrives.
1028− var bannerHeightPx by remember { mutableIntStateOf(0) }
1029− val density = LocalDensity.current
1030− val topPad = if (bannerVisible) {
1031− if (bannerHeightPx > 0) {
1032− with(density) { bannerHeightPx.toDp() } + 4.dp
1040− state = connectionState,
1041− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1042− isOnline = isOnline,
1043− // On a hard failure, retry by forcing an SSE reconnect (which
1044− // re-seeds from REST). refreshMessages is the right recovery path
1045− // when the connection is present but the stream died; reconnect()
1046− // is the path when the whole connection is gone (handled by the
1047− // separate "Not connected" state below).
1048− onRetry = { vm.refreshMessages() },
1050− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1051− // recovery is a swipe away everywhere — not just when the message list is
1052− // populated. Previously PTR was only around the populated list, leaving the
1053− // error/loading states reachable only via a button tap.
1055− isRefreshing = refreshing,
1056− onRefresh = { vm.refreshMessages() },
1057− // Cap width and center on large screens for readability — full-width
1058− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1059− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1060− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1062− // Reserve top space when the banner is visible so it doesn't overlap the
1063− // first message / state content. (topPad computed above.)
1064− if (loading && messages.isEmpty()) {
1065− val loadingLabel = stringResource(R.string.loading)
1066− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1067− // than a bare centered spinner and the first real messages pop into an
1068− // already-shaped list instead of a blank-then-pop. Alpha pulses (gated by
1069− // reduced-motion) to convey ongoing work; the column carries the a11y label.
1070− val reducedMotion = LocalReducedMotion.current
1071− val transition = rememberInfiniteTransition(label = "skeleton")
1072− val pulse by transition.animateFloat(
1073− initialValue = 0.35f,
1074− targetValue = 0.7f,
1075− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
1076− label = "skeletonAlpha",
1078− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
1079− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
1081− fun bar(widthFraction: Float) {
1084− .fillMaxWidth(widthFraction)
1086− .clip(RoundedCornerShape(4.dp))
1087− .background(skeletonColor)
1088− .alpha(skeletonAlpha),
1092− modifier = Modifier
1093− .align(Alignment.TopCenter)
1094− .padding(top = topPad)
1097− .semantics { contentDescription = loadingLabel },
1098− verticalArrangement = Arrangement.spacedBy(14.dp),
1101− val left = i % 2 == 0
1103− modifier = Modifier.fillMaxWidth(),
1104− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
1107− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
1108− verticalArrangement = Arrangement.spacedBy(6.dp),
1116− } else if (loadError && messages.isEmpty()) {
1117− // A failed load with nothing to show. Distinct from the empty
1118− // conversation state below — the conversation isn't empty, it
1119− // failed to load, and offering "Start a conversation" here is
1120− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1122− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1123− horizontalAlignment = Alignment.CenterHorizontally,
1126− stringResource(R.string.load_messages_failed),
1127− color = MaterialTheme.colorScheme.error,
1129− Spacer(Modifier.size(12.dp))
1130− Button(onClick = { vm.refreshMessages() }) {
1131− Text(stringResource(R.string.retry))
1134− } else if (messages.isEmpty() && running) {
1135− // A run just started but no parts have arrived yet — the empty
1136− // list with only the trailing "working…" row looks broken, so
1137− // surface a clear starting state until the first part streams in.
1138− val workingText = stringResource(R.string.working)
1140− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1141− horizontalAlignment = Alignment.CenterHorizontally,
1143− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
1144− Spacer(Modifier.size(12.dp))
1145− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
1147− } else if (messages.isEmpty()) {
1151− // Focus the input so the user can edit the suggestion before
1152− // sending, instead of having to manually tap the field.
1153− runCatching { inputFocusRequester.requestFocus() }
1155− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1158− val lastMessageId = messages.lastOrNull()?.info?.id
1159− // Text-to-speech for reading assistant replies aloud; shuts down when the
1160− // message list leaves composition.
1161− val tts = rememberTtsController()
1162− val speakingMessageId by tts.speakingId
1163− val ttsState by tts.state
1164− // Provide the in-conversation search query to the markdown renderer so matching
1165− // text spans are highlighted in-place (in addition to the focused-row highlight
1166− // above). Scoped to the list so cleared search stops highlighting immediately.
1167− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1168− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1171− modifier = Modifier.fillMaxSize(),
1172− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1173− // never floats over the last message. Top padding grows when the
1174− // connection banner is visible so it doesn't overlap the first message.
1175− contentPadding = PaddingValues(
1179− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1181− verticalArrangement = Arrangement.spacedBy(16.dp),
1186− contentType = { it.contentType },
1188− // When in-conversation search is stepping through matches, highlight the
1189− // focused one's row so the user can spot it at a glance among the filtered
1190− // results (full in-text term highlighting would require threading the query
1191− // through the markdown renderer; the row highlight + scroll-to-match covers
1192− // the navigation use case desktop chat apps solve with next/prev).
1193− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1194− searchMessages.getOrNull(searchPos)?.info?.id
1196− val isFocusedMatch = focusedMatchId != null &&
1197− item is MessageListItem.Message &&
1198− item.message.info.id == focusedMatchId
1199− // Default placement animation so inserted/moved rows glide in. Skipped
1200− // entirely under reduced motion so a streaming message growing in place
1201− // doesn't animate on every token (and respects the a11y preference).
1204− .then(reducedMotionAnimateItem())
1206− if (isFocusedMatch) {
1207− Modifier.background(
1208− MaterialTheme.colorScheme.secondaryContainer,
1209− MaterialTheme.shapes.medium,
1217− is MessageListItem.Separator -> DateSeparator(item.label)
1218− is MessageListItem.Message -> {
1219− val message = item.message
1220− // Only the last (streaming) message needs isRunning — it drives the
1221− // reasoning-block spinner. Passing the live flag to every bubble
1222− // makes all visible messages recompose whenever a run starts or stops.
1223− val modelLabel = remember(message.info, models) {
1224− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1225− ?.let { resolveModelLabel(it, models) }
1227− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1228− // image/code-only messages, which then opt out of the swipe gesture.
1229− val quoteText = remember(message.parts) {
1231− .filterIsInstance<TextPart>()
1232− .joinToString("\n\n") { it.text }
1234− .takeIf { it.isNotEmpty() }
1236− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1237− // snapping back (the message isn't dismissed — the quote fills the composer).
1238− // Only enabled when there's text to quote, so non-text messages don't
1239− // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1240− val swipeState = rememberSwipeToDismissBoxState(
1241− confirmValueChange = { value ->
1242− if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1243− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1244− vm.quoteReply(quoteText)
1245− runCatching { inputFocusRequester.requestFocus() }
1251− state = swipeState,
1252− enableDismissFromEndToStart = false,
1253− enableDismissFromStartToEnd = quoteText != null,
1254− backgroundContent = {
1256− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1257− contentAlignment = Alignment.CenterStart,
1260− Icons.AutoMirrored.Filled.Reply,
1261− contentDescription = null,
1262− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1269− isRunning = running && message.info.id == lastMessageId,
1270− imageContext = imageContext,
1271− modelLabel = modelLabel,
1272− onOpenFile = onOpenFile,
1273− onRevert = { vm.revertTo(message.info.id) },
1275− // editMessage reverts to before this message (hiding it and
1276− // everything after); the revert banner surfaces the rewind
1277− // with an Undo. Focus + scroll the composer into view like the
1278− // Quote action so the prefilled draft isn't off-screen.
1279− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1280− vm.editMessage(message.info.id, text)
1281− runCatching { inputFocusRequester.requestFocus() }
1282− contentScope.launch {
1283− runCatchingCancellable {
1284− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1288− onSpeak = { text ->
1289− if (!tts.toggle(message.info.id, text)) {
1290− // TTS engine unavailable (init failed / not yet ready
1291− // / blank text): surface feedback so the button doesn't
1292− // appear dead. Throttled so a rapid double-tap (stop
1293− // then immediate re-tap before ready) doesn't spam.
1294− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1297− isSpeaking = message.info.id == speakingMessageId,
1298− ttsState = if (message.info.id == speakingMessageId) ttsState else TtsState.IDLE,
1299− onPause = { tts.pause() },
1300− onResume = { tts.resume() },
1301− onQuote = { text ->
1302− vm.quoteReply(text)
1303− runCatching { inputFocusRequester.requestFocus() }
1305− onBranch = { text -> vm.branchFrom(text) },
1306− // Regenerate is only meaningful for a finished assistant reply
1307− // (not the actively-streaming one), so gate it on !running.
1308− onRegenerate = if (!running) {
1309− { vm.regenerate(message.info.id) }
1311− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1312− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1313− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1315− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1316− onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1318− { vm.retryOptimisticMessage(message.info.id) }
1323− onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1325− { vm.dismissOptimistic(message.info.id) }
1331− // Per-message share: build a single-message Markdown
1332− // transcript off-thread and fire ACTION_SEND, mirroring the
1333− // whole-conversation share but scoped to just this message.
1335− val md = withContext(Dispatchers.Default) {
1336− buildMessageMarkdown(message)
1338− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1339− type = "text/markdown"
1340− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1341− putExtra(android.content.Intent.EXTRA_TEXT, md)
1343− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1344− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1354− item(key = "__typing") {
1355− val workingText = stringResource(R.string.working)
1356− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1357− // survives LazyColumn recycling — a local remember reset to 0:00 when
1358− // the row was disposed and scrolled back into view. The VM stamps the
1359− // start on the real false→true transition (send/run/init), not on
1360− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1361− // once per second; the value is decorative (the a11y label is the row's).
1362− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1363− val elapsedMs by produceState(0L, startMs) {
1364− if (startMs == 0L) return@produceState
1366− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1370− val elapsedText = remember(elapsedMs) {
1371− val total = elapsedMs / 1000
1372− // Locale.US for stable digit formatting: on locales with
1373− // non-ASCII digits (ar-/fa-) the default locale would render
1374− // localized digits inside the Monospace block, breaking the
1375− // fixed-width alignment the monospace family was chosen for.
1376− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1379− verticalAlignment = Alignment.CenterVertically,
1380− // Animate this slot in/out so the working row doesn't pop in and
1381− // jolt the message list when a run starts/stops — matching the
1382− // AnimatedVisibility used by every other transient banner/FAB here.
1383− modifier = Modifier
1384− .then(reducedMotionAnimateItem())
1385− .padding(vertical = 4.dp),
1387− // Merge the indicator + label + clock into one TalkBack node so
1388− // it's announced once (the working label, then the elapsed time)
1389− // instead of "working… / working… / 0:14" with the label read
1390− // twice. The Stop IconButton below stays separately focusable.
1392− verticalAlignment = Alignment.CenterVertically,
1393− modifier = Modifier.semantics(mergeDescendants = true) {
1394− contentDescription = "$workingText $elapsedText"
1397− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1398− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1399− Spacer(Modifier.size(8.dp))
1401− Icons.Filled.Schedule,
1402− contentDescription = null,
1403− modifier = Modifier.size(14.dp),
1404− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1408− style = MaterialTheme.typography.labelMedium,
1409− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1410− color = MaterialTheme.colorScheme.onSurfaceVariant,
1411− modifier = Modifier.padding(start = 4.dp),
1414− // A trailing Stop on the working row so the run can be aborted
1415− // without scrolling back to the composer (which may be off-screen
1416− // while the user reads the streaming output up-thread).
1417− Spacer(Modifier.weight(1f))
1418− val stopLabel = stringResource(R.string.stop)
1420− onClick = { showStopConfirm = true },
1421− modifier = Modifier.semantics { contentDescription = stopLabel },
1423− Icon(Icons.Filled.Stop, contentDescription = null)
1432− // Jump-to-latest affordance when the user has scrolled away during a stream.
1433− val fabMotion = rememberVisibilityTransitions()
1434− AnimatedVisibility(
1435− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1436− enter = fabMotion.enter,
1437− exit = fabMotion.exit,
1438− modifier = Modifier.align(Alignment.BottomEnd),
1440− // Badge the FAB when new content arrived while the user was scrolled up, so
1441− // they know there's something new to jump to (cleared once back at bottom).
1444− if (newContentCount > 0) {
1445− val newContentLabel = stringResource(R.string.new_messages)
1446− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel }) {
1447− Text(if (newContentCount > 99) "99+" else newContentCount.toString())
1451− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1453− ExtendedFloatingActionButton(
1455− newContentCount = 0
1456− if (listItems.isNotEmpty()) {
1457− // Scroll to the effective last index, including the
1458− // trailing "__typing" row when a run is active.
1459− val target = if (running) listItems.size else listItems.lastIndex
1460− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1463− // contentDescription null: the visible "Latest" text already labels
1464− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1465− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1466− text = { Text(stringResource(R.string.latest)) },
1470− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1471− // user has scrolled down past the first few messages. Symmetric to the
1472− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1473− val scrolledDown by remember {
1474− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1476− AnimatedVisibility(
1477− visible = scrolledDown && listItems.size > 4,
1478− enter = fabMotion.enter,
1479− exit = fabMotion.exit,
1480− modifier = Modifier.align(Alignment.BottomStart),
1482− SmallFloatingActionButton(
1484− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1486− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1489− Icons.Filled.KeyboardArrowUp,
1490− contentDescription = stringResource(R.string.scroll_to_top),
1494− // In-conversation search bar. Overlays the list so typing filters messages in
1495− // place; the match count + a no-matches note give immediate feedback.
1496− val searchMotion = rememberVisibilityTransitions()
1497− AnimatedVisibility(
1498− visible = searchActive,
1499− enter = searchMotion.enter,
1500− exit = searchMotion.exit,
1501− modifier = Modifier.align(Alignment.TopCenter),
1504− tonalElevation = 3.dp,
1505− modifier = Modifier
1506− .padding(horizontal = 12.dp, vertical = 4.dp)
1509− // Focus the search field when the bar appears (from the overflow menu's
1510− // "Find in conversation" or Ctrl+F), so the user can start typing
1511− // immediately. Runs after the search field enters the composition.
1512− LaunchedEffect(searchActive) {
1513− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1516− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1517− verticalAlignment = Alignment.CenterVertically,
1520− value = chatSearch,
1521− onValueChange = { chatSearch = it },
1522− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1523− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1525− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1526− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1528− // Match counter: "N of M" where N is the focused match (1-based) and
1529− // M is the total matching messages. Only shown when there's a query.
1530− val matchCount = searchMessages.size
1532− if (searchQuery.isNotEmpty() && matchCount > 0) {
1533− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1534− } else if (searchQuery.isNotEmpty()) {
1535− stringResource(R.string.search_no_matches)
1537− style = MaterialTheme.typography.labelSmall,
1538− color = MaterialTheme.colorScheme.onSurfaceVariant,
1539− modifier = Modifier.padding(horizontal = 4.dp),
1541− // Step through matches (Previous / Next), disabled when there are
1542− // fewer than two to navigate. Wrap around at the ends so repeated
1543− // taps cycle through every hit.
1544− val prevLabel = stringResource(R.string.find_previous)
1545− val nextLabel = stringResource(R.string.find_next)
1548− if (matchCount > 0) {
1549− searchPos = (searchPos - 1 + matchCount) % matchCount
1552− enabled = matchCount > 1,
1554− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1558− if (matchCount > 0) {
1559− searchPos = (searchPos + 1) % matchCount
1562− enabled = matchCount > 1,
1564− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1566− IconButton(onClick = {
1567− searchActive = false
1570− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1575− // When a search yields no matches (but the conversation isn't empty), say so
1576− // instead of showing a blank list.
1577− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1579− stringResource(R.string.search_no_matches),
1580− style = MaterialTheme.typography.bodyMedium,
1581− color = MaterialTheme.colorScheme.onSurfaceVariant,
1582− modifier = Modifier.align(Alignment.Center),
1590− if (showExitConfirm) {
1592− onDismissRequest = { showExitConfirm = false },
1593− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1594− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1596− TextButton(onClick = {
1597− showExitConfirm = false
1598− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1601− }) { Text(stringResource(R.string.stop_and_exit)) }
1604− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1609− if (showStopConfirm) {
1611− onDismissRequest = { showStopConfirm = false },
1612− title = { Text(stringResource(R.string.stop_run_title)) },
1613− text = { Text(stringResource(R.string.stop_run_text)) },
1615− TextButton(onClick = {
1616− showStopConfirm = false
1617− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1619− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1622− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1627− if (showSummarizeConfirm) {
1629− onDismissRequest = { showSummarizeConfirm = false },
1630− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1631− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1633− TextButton(onClick = {
1634− showSummarizeConfirm = false
1636− }) { Text(stringResource(R.string.action_continue)) }
1639− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1644− if (showInitConfirm) {
1646− onDismissRequest = { showInitConfirm = false },
1647− title = { Text(stringResource(R.string.init_confirm_title)) },
1648− text = { Text(stringResource(R.string.init_confirm_text)) },
1650− TextButton(onClick = {
1651− showInitConfirm = false
1653− }) { Text(stringResource(R.string.action_continue)) }
1656− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1661− if (showRenameDialog) {
1662− RenameSessionChatDialog(
1663− initialTitle = sessionTitle ?: "",
1664− onDismiss = { showRenameDialog = false },
1665− onConfirm = { newName ->
1666− showRenameDialog = false
1667− vm.renameSession(newName)
1672− if (showDeleteDialog) {
1674− onDismissRequest = { showDeleteDialog = false },
1675− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1676− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1678− TextButton(onClick = {
1679− showDeleteDialog = false
1680− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1682− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1685− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1690− if (showShellDialog) {
1691− ShellCommandDialog(
1692− onDismiss = { showShellDialog = false },
1694− showShellDialog = false
1700− if (showModelPicker) {
1703− selected = selectedModel,
1704− loading = modelsLoading,
1705− error = modelsError,
1706− onSelect = { vm.selectModel(it) },
1707− onRetry = { vm.reloadModels() },
1708− onDismiss = { showModelPicker = false },
1712− if (showAgentPicker) {
1715− selected = selectedAgent,
1716− loading = agentsLoading,
1717− error = agentsError,
1718− onSelect = { vm.selectAgent(it?.name) },
1719− onRetry = { vm.reloadAgents() },
1720− onDismiss = { showAgentPicker = false },
1724− if (showCommandPicker) {
1725− CommandPickerSheet(
1726− commands = commands,
1727− loading = commandsLoading,
1728− error = commandsError,
1729− onSelect = { vm.runCommand(it) },
1730− onRetry = { vm.reloadCommands() },
1731− onDismiss = { showCommandPicker = false },
1735− pendingPermission?.let { permission ->
1737− permission = permission,
1738− position = permissionProgress.position,
1739− total = permissionProgress.total,
1740− onRespond = { response -> vm.respondPermission(permission, response) },
1745− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1748− if (showShortcutsDialog) {
1749− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
1750− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
1751− // depends on the "Send on Enter" setting, noted inline.
1753− onDismissRequest = { showShortcutsDialog = false },
1754− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
1756− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
1757− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
1758− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
1759− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
1760− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
1761− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
1765− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
1772−private fun ShortcutRow(keys: String, desc: String) {
1773− Row(verticalAlignment = Alignment.CenterVertically) {
1776− style = MaterialTheme.typography.labelLarge,
1777− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1778− modifier = Modifier.widthIn(min = 160.dp),
1782− style = MaterialTheme.typography.bodyMedium,
1783− color = MaterialTheme.colorScheme.onSurfaceVariant,
1788−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
1790−private fun ChatInputBar(
1792− onValueChange: (String) -> Unit,
1796− sendOnEnter: Boolean,
1797− onSend: () -> Unit,
1798− onAbort: () -> Unit,
1799− queuedFollowUp: String?,
1800− onQueueFollowUp: (String) -> Unit,
1801− onCancelQueue: () -> Unit,
1802− focusRequester: androidx.compose.ui.focus.FocusRequester,
1803− attachments: List<PendingAttachment>,
1805− onRemoveAttachment: (String) -> Unit,
1806− onPickPhoto: () -> Unit,
1807− onPickFile: () -> Unit,
1808− onCamera: () -> Unit,
1809− onVoice: () -> Unit,
1810− onPasteImage: (List<Uri>) -> Unit,
1812− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1813− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1814− val context = LocalContext.current
1815− // Full-screen editor state: opened when the user wants more space for a long prompt.
1816− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1817− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1818− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1819− // A queued follow-up replaces the Stop button with a "queued" chip so the
1820− // user sees their message will be sent when the run finishes, and can cancel.
1821− if (queuedFollowUp != null) {
1822− val editLabel = stringResource(R.string.edit)
1824− modifier = Modifier
1826− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1827− verticalAlignment = Alignment.CenterVertically,
1829− // Tapping the chip reloads the queued text into the draft (and clears the
1830− // queue) so a typo spotted while queuing can be fixed without retyping.
1832− modifier = Modifier
1834− .clip(MaterialTheme.shapes.small)
1835− .clickable(role = Role.Button, onClickLabel = editLabel) {
1836− onValueChange(queuedFollowUp)
1839− .padding(vertical = 4.dp),
1842− stringResource(R.string.queued),
1843− style = MaterialTheme.typography.labelSmall,
1844− color = MaterialTheme.colorScheme.onSurfaceVariant,
1848− style = MaterialTheme.typography.bodySmall,
1849− color = MaterialTheme.colorScheme.onSurfaceVariant,
1851− overflow = TextOverflow.Ellipsis,
1854− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1855− Text(stringResource(R.string.cancel))
1859− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1860− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1862− modifier = Modifier.fillMaxWidth().padding(8.dp),
1863− verticalAlignment = Alignment.Bottom,
1865− // Attach menu: photo picker, camera, or any file.
1866− var showAttachMenu by remember { mutableStateOf(false) }
1868− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1869− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1871− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1873− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1874− text = { Text(stringResource(R.string.attach_photo)) },
1875− onClick = { showAttachMenu = false; onPickPhoto() },
1878− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1879− text = { Text(stringResource(R.string.attach_camera)) },
1880− onClick = { showAttachMenu = false; onCamera() },
1883− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1884− text = { Text(stringResource(R.string.attach_file)) },
1885− onClick = { showAttachMenu = false; onPickFile() },
1889− // Voice dictation: appends recognized speech to the draft. Hidden (not just
1890− // disabled) when the device has no speech-recognition activity, so a user
1891− // without a voice app doesn't get a button that only fails noisily on tap.
1892− val voiceAvailable = remember {
1893− val pm = context.packageManager
1894− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
1895− pm.queryIntentActivities(intent, 0).isNotEmpty()
1897− if (voiceAvailable) {
1898− IconButton(onClick = onVoice, enabled = enabled) {
1899− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1902− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1903− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1904− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1908− onValueChange = { v ->
1909− // Cap input length so a huge paste can't stall the UI. Shares are
1910− // capped separately in MainActivity; this guards typed/pasted drafts.
1911− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1913− modifier = Modifier
1915− .focusRequester(focusRequester)
1916− .testTag("chat_input")
1917− // Intercept image content pasted/dropped into the field (keyboard paste
1918− // of a copied screenshot, drag from Files, etc.) and route it through the
1919− // same staging path as the attach menu. Non-image content (text) falls
1920− // through unchanged so normal typing/paste works.
1923− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
1924− val clipData = transferable.clipEntry?.clipData
1925− if (clipData != null) {
1926− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
1927− val item = clipData.getItemAt(i)
1928− item.uri?.takeIf { uri ->
1929− item.text == null && uri.toString().let { s ->
1930− s.startsWith("content:") || s.startsWith("file:")
1934− if (imageUris.isNotEmpty()) {
1935− onPasteImage(imageUris)
1942− .onPreviewKeyEvent { event ->
1943− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1944− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1945− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1946− val send = enterShouldSend(
1948− hasContent = hasContent,
1949− sendOnEnter = sendOnEnter,
1950− shift = event.isShiftPressed,
1951− ctrl = event.isCtrlPressed,
1954− if (running) onQueueFollowUp(value) else onSend()
1960− // While a run is active a typed message only queues (sends after the run), so
1961− // the placeholder says so instead of the plain "Message…".
1963− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1967− // Show a "N / max" countdown once the draft crosses a high fraction of
1968− // the cap, so the user knows a paste is about to be truncated instead
1969− // of being silently cut off. Hidden for normal short prompts to avoid
1970− // clutter under a typical one-line message.
1972− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1973− if (value.length >= threshold) {
1976− R.string.draft_chars_remaining,
1977− NetworkConfig.maxDraftLengthChars - value.length,
1978− NetworkConfig.maxDraftLengthChars,
1980− style = MaterialTheme.typography.labelSmall,
1981− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1982− else MaterialTheme.colorScheme.onSurfaceVariant,
1986− keyboardOptions = KeyboardOptions(
1987− // When "Send on Enter" is on, expose ImeAction.Send so the soft
1988− // keyboard shows a send key — matching the setting's intent and
1989− // giving touch-only users a keyboard send affordance. When off,
1990− // ImeAction.Default keeps the enter/newline key for multi-line input.
1991− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1992− capitalization = KeyboardCapitalization.Sentences,
1994− keyboardActions = KeyboardActions(
1996− if (enabled && hasContent) onSend()
2000− ComposerTrailingButton(
2002− aborting = aborting,
2003− canSend = enabled && hasContent,
2004− canQueue = enabled && value.isNotBlank(),
2007− onQueue = { onQueueFollowUp(value) },
2011− if (showFullScreenEditor) {
2014− onValueChange = onValueChange,
2015− onDismiss = { showFullScreenEditor = false },
2017− showFullScreenEditor = false
2018− // Mirror the inline composer's behavior: while a run is active a send
2019− // can't go immediately, so queue the follow-up instead of silently
2020− // dropping it (vm.send() returns false during a run, which previously
2021− // lost the typed message with no feedback).
2022− if (running) onQueueFollowUp(value) else onSend()
2024− canSend = enabled && hasContent,
2026− sendOnEnter = sendOnEnter,
2027− attachments = attachments,
2028− onRemoveAttachment = onRemoveAttachment,
2035−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2036− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2037−@OptIn(ExperimentalMaterial3Api::class)
2039−private fun FullScreenEditor(
2041− onValueChange: (String) -> Unit,
2042− onDismiss: () -> Unit,
2043− onSend: () -> Unit,
2045− running: Boolean = false,
2046− sendOnEnter: Boolean = false,
2047− attachments: List<PendingAttachment> = emptyList(),
2048− onRemoveAttachment: (String) -> Unit = {},
2049− staging: Boolean = false,
2051− androidx.compose.ui.window.Dialog(
2052− onDismissRequest = onDismiss,
2053− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2055− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2056− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2057− // gives the available width so we can center a capped-width column.
2058− androidx.compose.foundation.layout.BoxWithConstraints(
2059− modifier = Modifier.fillMaxSize(),
2060− contentAlignment = Alignment.Center,
2062− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2063− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2066− modifier = Modifier.padding(horizontal = hPad),
2068− androidx.compose.material3.TopAppBar(
2069− title = { Text(stringResource(R.string.compose_editor_title)) },
2071− androidx.compose.material3.TextButton(onClick = onDismiss) {
2072− Text(stringResource(R.string.collapse_editor))
2078− Surface(tonalElevation = 3.dp) {
2080− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2081− horizontalArrangement = Arrangement.End,
2083− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2084− Text(stringResource(if (running) R.string.queue else R.string.send))
2090− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2091− // Show staged attachments in the full-screen editor too, so a user who staged
2092− // images then expanded for a long prompt can still see and remove them without
2093− // collapsing first (mirrors the inline composer's AttachmentStrip).
2094− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
2097− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2098− modifier = Modifier
2101− // Honor the "Send on Enter" setting here too, so the full-screen
2102− // editor matches the inline composer: Enter sends (Shift+Enter
2103− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2104− // when off. Previously this hard-coded ImeAction.Default and had no
2105− // key handler, so a hardware-keyboard user got a different behaviour
2106− // from the inline composer depending on which they happened to open.
2107− .onPreviewKeyEvent { event ->
2108− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2109− val send = enterShouldSend(
2111− hasContent = canSend,
2112− sendOnEnter = sendOnEnter,
2113− shift = event.isShiftPressed,
2114− ctrl = event.isCtrlPressed,
2116− if (send) { onSend(); true } else false
2118− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2119− maxLines = Int.MAX_VALUE,
2120− keyboardOptions = KeyboardOptions(
2121− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2122− capitalization = KeyboardCapitalization.Sentences,
2124− keyboardActions = KeyboardActions(
2125− onSend = { if (canSend) onSend() },
2134−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2135− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2136−private fun enterShouldSend(
2138− hasContent: Boolean,
2139− sendOnEnter: Boolean,
2143− !enabled || !hasContent -> false
2144− sendOnEnter -> !shift
2148−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2149− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2150− * [ChatInputBar] stays under the complexity threshold. */
2152−private fun ComposerTrailingButton(
2157− onSend: () -> Unit,
2158− onAbort: () -> Unit,
2159− onQueue: () -> Unit,
2162− Row(verticalAlignment = Alignment.CenterVertically) {
2163− // While a run is active the trailing action is Stop, so the only send affordance is
2164− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2165− // That leaves a touch-only user with the setting off no way to queue a follow-up
2166− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2167− // there's typed TEXT so queuing is always reachable, without changing the user's
2168− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2169− // canSend, which is also true for an attachment-only composer — because queuing "" just
2170− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2171− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2175− modifier = Modifier.testTag("queue_button"),
2177− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2178− // icon (which can be read as "snooze" or "later"), and isn't confused with
2179− // the Send action sitting right beside the Stop button.
2181− Icons.AutoMirrored.Filled.PlaylistAdd,
2182− contentDescription = stringResource(R.string.queue_followup),
2186− // Show a spinner while the abort REST call is in flight so the user sees the stop
2187− // was sent, and disable to prevent a double-tap.
2190− enabled = !aborting,
2191− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2194− val stopLabel = stringResource(R.string.stop)
2195− CircularProgressIndicator(
2196− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2197− strokeWidth = 2.dp,
2200− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2208− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2210− // Tint the send icon with primary when there's content to send so the commit action
2211− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2213− Icons.AutoMirrored.Filled.Send,
2214− contentDescription = stringResource(R.string.send),
2215− tint = if (canSend) MaterialTheme.colorScheme.primary
2216− else MaterialTheme.colorScheme.onSurfaceVariant,
2222−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2224−private fun EmptyConversation(
2225− onSuggestion: (String) -> Unit,
2226− modifier: Modifier = Modifier,
2228− // A few example prompts so a first-time user has a one-tap path to their first
2229− // message instead of staring at a blank input. Tapping a chip fills the draft
2230− // (without sending) so the user can edit it before sending.
2231− val suggestions = remember {
2233− R.string.empty_chat_suggest_1,
2234− R.string.empty_chat_suggest_2,
2235− R.string.empty_chat_suggest_3,
2239− modifier = modifier.padding(32.dp),
2240− horizontalAlignment = Alignment.CenterHorizontally,
2243− Icons.Filled.AutoAwesome,
2244− contentDescription = null,
2245− modifier = Modifier.size(48.dp),
2246− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2248− Spacer(Modifier.size(16.dp))
2250− stringResource(R.string.empty_chat_title),
2251− style = MaterialTheme.typography.titleMedium,
2253− Spacer(Modifier.size(8.dp))
2255− stringResource(R.string.empty_chat_hint),
2256− style = MaterialTheme.typography.bodyMedium,
2257− color = MaterialTheme.colorScheme.onSurfaceVariant,
2259− Spacer(Modifier.size(20.dp))
2260− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2261− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2263− modifier = Modifier.fillMaxWidth(),
2264− horizontalArrangement = Arrangement.spacedBy(8.dp),
2265− verticalArrangement = Arrangement.spacedBy(8.dp),
2267− suggestions.forEach { resId ->
2268− val text = stringResource(resId)
2269− androidx.compose.material3.AssistChip(
2270− onClick = { onSuggestion(text) },
2271− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2278−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2279− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2280− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2282−private fun RevertBanner(diff: String?, onUndo: () -> Unit) {
2283− val haptics = LocalHapticFeedback.current
2284− var showDiff by rememberSaveable { mutableStateOf(false) }
2285− val expandMotion = rememberVisibilityTransitions()
2287− color = MaterialTheme.colorScheme.tertiaryContainer,
2288− tonalElevation = 2.dp,
2289− modifier = Modifier.fillMaxWidth(),
2293− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2294− verticalAlignment = Alignment.CenterVertically,
2295− horizontalArrangement = Arrangement.SpaceBetween,
2297− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2299− Icons.Filled.Restore,
2300− contentDescription = null,
2301− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2302− modifier = Modifier.size(18.dp),
2305− stringResource(R.string.reverted_banner),
2306− style = MaterialTheme.typography.bodySmall,
2307− color = MaterialTheme.colorScheme.onTertiaryContainer,
2308− modifier = Modifier.padding(start = 8.dp),
2310− // "Show what changed" toggle, shown only when the server provided a diff.
2311− // Collapsible so the banner stays compact by default; a user curious about
2312− // what the revert rolled back can expand it inline without leaving the chat.
2313− if (!diff.isNullOrBlank()) {
2316− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2317− showDiff = !showDiff
2319− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2322− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2323− contentDescription = null,
2324− modifier = Modifier.size(16.dp),
2327− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2328− style = MaterialTheme.typography.labelSmall,
2329− modifier = Modifier.padding(start = 4.dp),
2334− TextButton(onClick = {
2335− // Haptic on undo to match the other destructive/important confirmations: a
2336− // revert restores potentially hundreds of hidden messages.
2337− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2339− }) { Text(stringResource(R.string.undo)) }
2341− // The diff render lives inside the banner's Surface so it inherits the tertiary
2342− // tonal container and reads as part of the banner, not a floating panel.
2343− if (!diff.isNullOrBlank()) {
2344− AnimatedVisibility(
2345− visible = showDiff,
2346− enter = expandMotion.enter,
2347− exit = expandMotion.exit,
2349− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2351− stringResource(R.string.revert_diff_header),
2352− style = MaterialTheme.typography.labelSmall,
2353− color = MaterialTheme.colorScheme.onTertiaryContainer,
2354− modifier = Modifier.padding(bottom = 4.dp),
2356− DiffView(diff, saveKey = "revertDiff")
2364−/** A banner shown while messages composed offline are queued in the outbox, with a
2365− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2367−private fun OutboxBanner(
2370− onFlush: () -> Unit,
2371− onDiscard: () -> Unit,
2373− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2375− color = MaterialTheme.colorScheme.secondaryContainer,
2376− tonalElevation = 2.dp,
2377− modifier = Modifier.fillMaxWidth(),
2380− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2381− verticalAlignment = Alignment.CenterVertically,
2382− horizontalArrangement = Arrangement.SpaceBetween,
2384− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2386− CircularProgressIndicator(
2387− Modifier.size(16.dp),
2388− strokeWidth = 2.dp,
2389− color = MaterialTheme.colorScheme.onSecondaryContainer,
2391− Spacer(Modifier.size(8.dp))
2395− stringResource(R.string.outbox_sending)
2397− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2398− stringResource(res, count)
2400− style = MaterialTheme.typography.bodySmall,
2401− color = MaterialTheme.colorScheme.onSecondaryContainer,
2405− val haptics = LocalHapticFeedback.current
2406− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2407− TextButton(onClick = {
2408− // Confirm before discarding all queued messages (irreversible), matching
2409− // the confirmation pattern used by deleteSession and other destructive
2410− // actions. Previously a single tap dropped every queued message.
2411− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2412− showDiscardConfirm = true
2414− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2419− if (showDiscardConfirm) {
2420− androidx.compose.material3.AlertDialog(
2421− onDismissRequest = { showDiscardConfirm = false },
2422− title = { Text(stringResource(R.string.discard_queued_title)) },
2423− text = { Text(stringResource(R.string.discard_queued_text, count)) },
2425− androidx.compose.material3.TextButton(onClick = {
2426− showDiscardConfirm = false
2428− }) { Text(stringResource(R.string.discard)) }
2431− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
2432− Text(stringResource(R.string.cancel))
2439−/** Prompt for a one-off shell command to run in the session's worktree. */
2441−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
2442− var command by rememberSaveable { mutableStateOf("") }
2444− onDismissRequest = onDismiss,
2445− title = { Text(stringResource(R.string.run_shell_command)) },
2449− onValueChange = { command = it },
2450− modifier = Modifier.fillMaxWidth(),
2451− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
2452− label = { Text(stringResource(R.string.shell_command_label)) },
2454− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2455− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
2460− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
2461− enabled = command.isNotBlank(),
2462− ) { Text(stringResource(R.string.run)) }
2464− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
2469− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
2470− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
2471− * equality is structural so `snapshotFlow` emits only when something relevant changes.
2473−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
2475−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
2476− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
2477− * streaming, not just plain assistant text. O(1). */
2478−private fun streamingContentLength(part: Part?): Int = when (part) {
2479− is TextPart -> part.text.length
2480− is ReasoningPart -> part.text.length
2481− is ToolPart -> when (val st = part.state) {
2482− is ToolCompleted -> st.output?.length ?: 0
2483− is ToolError -> st.error?.length ?: 0
2484− is ToolRunning -> st.title?.length ?: 0
2490−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
2491− * dialog but lives in the chat screen so the user can rename without backing out to
2492− * the list. Pre-filled with the current title; the cap matches the list dialog. */
2494−private fun RenameSessionChatDialog(
2495− initialTitle: String,
2496− onDismiss: () -> Unit,
2497− onConfirm: (String) -> Unit,
2499− // Seed the field once (no key input) so a later external title change — e.g. opencode
2500− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
2501− // doesn't re-initialize the box and discard the user's in-progress edit.
2502− var title by rememberSaveable { mutableStateOf(initialTitle) }
2504− onDismissRequest = onDismiss,
2505− title = { Text(stringResource(R.string.rename_session_chat)) },
2509− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
2510− modifier = Modifier.fillMaxWidth(),
2511− placeholder = { Text(stringResource(R.string.session_title_hint)) },
2512− label = { Text(stringResource(R.string.rename_session_chat)) },
2514− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2515− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
2519− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
2520− Text(stringResource(R.string.save))
2524− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
2530− * A single item in the chat message list — either a [Message] bubble or a day
2531− * [Separator] inserted before the first message of a new day. The separator shifts
2532− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
2533− * the [List] of these items (not `messages.size`/`lastIndex`).
2535−private sealed interface MessageListItem {
2537− val contentType: Any
2539− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
2540− override val contentType: Any get() = message.info::class
2543− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
2544− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
2545− // can share a label (e.g. an untimestamped message — empty label — between two
2546− // same-day messages, or two untimestamped groups), and a label-only key would
2547− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
2548− // stable for a given message ordering so slots aren't needlessly recreated.
2549− override val key: Any get() = "sep_${ordinal}_$label"
2550− // Separators share a contentType so the LazyColumn can recycle their slots.
2551− override val contentType: Any get() = "separator"
2556− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
2557− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
2558− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
2559− * Messages with no timestamp are grouped under an empty-label separator only if they
2560− * start the list, so a server that omits timestamps doesn't suppress the first divider.
2562− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
2563− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
2564− * labels; older days fall back to a locale-stable medium-date format.
2566−private fun buildMessageListItems(
2567− messages: List<MessageWithParts>,
2568− todayLabel: String,
2569− yesterdayLabel: String,
2570−): List<MessageListItem> {
2571− if (messages.isEmpty()) return emptyList()
2572− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
2573− val dateFmt = mediumDateFormat()
2574− val result = ArrayList<MessageListItem>(messages.size + 4)
2575− val seenKeys = HashSet<String>(messages.size * 2)
2576− var lastDayKey: String? = null
2578− var emptyIdOrdinal = 0
2580− for (message in messages) {
2581− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
2582− val dayKey = ts?.let { dayKey(it) } ?: ""
2583− // Emit a separator before the very first message (so a leading un-timestamped message
2584− // still gets the first divider, empty label and all), and thereafter only when crossing
2585− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
2586− // neither emits its own separator nor resets the day — otherwise a following same-day
2587− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
2588− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
2589− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
2591− if (dayKey.isNotEmpty()) lastDayKey = dayKey
2593− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
2594− // empty id — and the reducer intentionally keeps several such messages as distinct
2595− // holders — so give each a stable synthetic key and defensively de-collide any remaining
2596− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
2597− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
2598− if (!seenKeys.add(key)) {
2600− while (!seenKeys.add("$key#$suffix")) suffix++
2601− key = "$key#$suffix"
2603− result.add(MessageListItem.Message(message, key))
2609− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2611− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2612− * whole `messages` list, which must stay so the live message's fresh parts render), so a
2613− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2614− * every message on every token. Message timestamps are immutable once assigned, so we
2615− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2616− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2617− * thread during composition, so the coarse lock is uncontended.
2619−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2620− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2623−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2624− dayKeyCache.getOrPut(epochMillis) {
2625− java.time.Instant.ofEpochMilli(epochMillis)
2626− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2630−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2631−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2632−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2633−private var cachedDateFmt: java.text.DateFormat? = null
2634−private var cachedDateFmtLocale: java.util.Locale? = null
2636−private fun mediumDateFormat(): java.text.DateFormat {
2637− val locale = java.util.Locale.getDefault()
2638− val existing = cachedDateFmt
2639− if (existing != null && cachedDateFmtLocale == locale) return existing
2640− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2642− cachedDateFmtLocale = locale
2647− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2648− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2649− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2652−private fun dayLabel(
2655− today: java.time.LocalDate,
2656− todayLabel: String,
2657− yesterdayLabel: String,
2658− dateFmt: java.text.DateFormat,
2660− if (dayKey.isEmpty()) return ""
2661− val epochDay = dayKey.toLongOrNull() ?: return ""
2662− val date = java.time.LocalDate.ofEpochDay(epochDay)
2664− date == today -> todayLabel
2665− date == today.minusDays(1) -> yesterdayLabel
2666− else -> dateFmt.format(java.util.Date(ts))
2671− * A centered day divider in the message list. Renders nothing for an empty label
2672− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2675−private fun DateSeparator(label: String) {
2676− if (label.isBlank()) return
2678− modifier = Modifier.fillMaxWidth(),
2679− horizontalArrangement = Arrangement.Center,
2682− color = MaterialTheme.colorScheme.surfaceVariant,
2683− shape = MaterialTheme.shapes.small,
2684− // Marked as a heading so TalkBack users can navigate day-by-day with the
2685− // heading-skip gesture — the canonical affordance for date dividers in a list.
2686− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
2690− style = MaterialTheme.typography.labelSmall,
2691− color = MaterialTheme.colorScheme.onSurfaceVariant,
2692− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),