@@ -1,1703 +0,0 @@
1−package soy.iko.opencode.ui.chat
3−import android.app.Activity
4−import android.content.Intent
6−import android.speech.RecognizerIntent
7−import androidx.activity.compose.BackHandler
8−import androidx.activity.compose.rememberLauncherForActivityResult
9−import androidx.activity.result.PickVisualMediaRequest
10−import androidx.activity.result.contract.ActivityResultContracts
11−import androidx.compose.animation.AnimatedVisibility
12−import androidx.compose.foundation.clickable
13−import androidx.compose.foundation.layout.Arrangement
14−import androidx.compose.foundation.layout.Box
15−import androidx.compose.foundation.layout.Column
16−import androidx.compose.foundation.layout.FlowRow
17−import androidx.compose.foundation.layout.PaddingValues
18−import androidx.compose.foundation.layout.Row
19−import androidx.compose.foundation.layout.Spacer
20−import androidx.compose.foundation.layout.WindowInsets
21−import androidx.compose.foundation.layout.fillMaxSize
22−import androidx.compose.foundation.layout.fillMaxWidth
23−import androidx.compose.foundation.layout.imePadding
24−import androidx.compose.foundation.layout.navigationBars
25−import androidx.compose.foundation.layout.padding
26−import androidx.compose.foundation.layout.size
27−import androidx.compose.foundation.layout.union
28−import androidx.compose.foundation.layout.windowInsetsPadding
29−import androidx.compose.foundation.lazy.LazyColumn
30−import androidx.compose.foundation.lazy.items
31−import androidx.compose.foundation.lazy.rememberLazyListState
32−import androidx.compose.material.icons.Icons
33−import androidx.compose.material.icons.automirrored.filled.ArrowBack
34−import androidx.compose.material.icons.automirrored.filled.Send
35−import androidx.compose.material.icons.filled.Add
36−import androidx.compose.material.icons.filled.AutoAwesome
37−import androidx.compose.material.icons.filled.Delete
38−import androidx.compose.material.icons.filled.Description
39−import androidx.compose.material.icons.filled.Edit
40−import androidx.compose.material.icons.filled.KeyboardArrowDown
41−import androidx.compose.material.icons.filled.Mic
42−import androidx.compose.material.icons.filled.MoreVert
43−import androidx.compose.material.icons.filled.PhotoCamera
44−import androidx.compose.material.icons.filled.PhotoLibrary
45−import androidx.compose.material.icons.filled.Refresh
46−import androidx.compose.material.icons.filled.Restore
47−import androidx.compose.material.icons.filled.Stop
48−import androidx.compose.material3.AlertDialog
49−import androidx.compose.material3.Button
50−import androidx.compose.material3.CircularProgressIndicator
51−import androidx.compose.material3.DropdownMenu
52−import androidx.compose.material3.DropdownMenuItem
53−import androidx.compose.material3.ExperimentalMaterial3Api
54−import androidx.compose.material3.ExtendedFloatingActionButton
55−import androidx.compose.material3.FloatingActionButton
56−import androidx.compose.material3.Icon
57−import androidx.compose.material3.IconButton
58−import androidx.compose.material3.MaterialTheme
59−import androidx.compose.material3.OutlinedTextField
60−import androidx.compose.material3.Scaffold
61−import androidx.compose.material3.SnackbarHost
62−import androidx.compose.material3.SnackbarHostState
63−import androidx.compose.material3.Surface
64−import androidx.compose.material3.Text
65−import androidx.compose.material3.TextButton
66−import androidx.compose.material3.TopAppBar
67−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
68−import androidx.compose.runtime.Composable
69−import androidx.compose.runtime.CompositionLocalProvider
70−import androidx.compose.runtime.DisposableEffect
71−import androidx.compose.runtime.LaunchedEffect
72−import androidx.compose.runtime.derivedStateOf
73−import androidx.compose.runtime.getValue
74−import androidx.compose.runtime.mutableStateOf
75−import androidx.compose.runtime.remember
76−import androidx.compose.runtime.rememberCoroutineScope
77−import androidx.compose.runtime.rememberUpdatedState
78−import androidx.compose.runtime.saveable.rememberSaveable
79−import androidx.compose.runtime.setValue
80−import androidx.compose.runtime.snapshotFlow
81−import androidx.compose.foundation.text.KeyboardActions
82−import androidx.compose.foundation.text.KeyboardOptions
83−import androidx.compose.ui.text.input.KeyboardCapitalization
84−import androidx.compose.ui.Alignment
85−import androidx.compose.ui.Modifier
86−import androidx.compose.ui.focus.focusRequester
87−import androidx.compose.ui.input.key.Key
88−import androidx.compose.ui.input.key.KeyEventType
89−import androidx.compose.ui.input.key.isCtrlPressed
90−import androidx.compose.ui.input.key.isShiftPressed
91−import androidx.compose.ui.input.key.key
92−import androidx.compose.ui.input.key.onPreviewKeyEvent
93−import androidx.compose.ui.input.key.type
94−import androidx.compose.ui.platform.LocalContext
95−import androidx.compose.ui.platform.LocalHapticFeedback
96−import androidx.compose.ui.platform.LocalView
97−import androidx.compose.ui.platform.testTag
98−import androidx.compose.ui.res.stringResource
99−import androidx.compose.ui.semantics.Role
100−import androidx.compose.ui.semantics.contentDescription
101−import androidx.compose.ui.semantics.semantics
102−import androidx.compose.ui.text.input.ImeAction
103−import androidx.compose.ui.text.style.TextOverflow
104−import androidx.compose.ui.unit.dp
105−import androidx.lifecycle.compose.collectAsStateWithLifecycle
106−import androidx.lifecycle.viewmodel.compose.viewModel
107−import kotlinx.coroutines.Dispatchers
108−import kotlinx.coroutines.launch
109−import kotlinx.coroutines.withContext
110−import soy.iko.opencode.data.model.Part
111−import soy.iko.opencode.data.model.MessageWithParts
112−import soy.iko.opencode.data.model.ReasoningPart
113−import soy.iko.opencode.data.model.TextPart
114−import soy.iko.opencode.data.model.ToolCompleted
115−import soy.iko.opencode.data.model.ToolError
116−import soy.iko.opencode.data.model.ToolPart
117−import soy.iko.opencode.data.model.ToolRunning
118−import soy.iko.opencode.data.network.EventStreamClient
119−import soy.iko.opencode.data.network.NetworkConfig
120−import soy.iko.opencode.di.AppContainer
121−import soy.iko.opencode.R
122−import soy.iko.opencode.ui.components.CommandPalette
123−import soy.iko.opencode.ui.components.ConnectionBanner
124−import soy.iko.opencode.ui.components.PaletteAction
125−import soy.iko.opencode.ui.components.copyToClipboard
126−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
127−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
128−import soy.iko.opencode.ui.components.showToast
129−import soy.iko.opencode.ui.components.toImageContext
130−import soy.iko.opencode.ui.vmFactory
131−import soy.iko.opencode.util.runCatchingCancellable
133−@OptIn(ExperimentalMaterial3Api::class)
136− container: AppContainer,
139− onOpenFile: ((String) -> Unit)? = null,
140− onOpenSession: ((String) -> Unit)? = null,
142− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
143− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
144− val running by vm.running.collectAsStateWithLifecycle()
145− val aborting by vm.aborting.collectAsStateWithLifecycle()
146− val loading by vm.loading.collectAsStateWithLifecycle()
147− val loadError by vm.loadError.collectAsStateWithLifecycle()
148− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
149− val models by vm.models.collectAsStateWithLifecycle()
150− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
151− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
152− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
153− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
154− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
155− val agents by vm.agents.collectAsStateWithLifecycle()
156− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
157− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
158− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
159− val commands by vm.commands.collectAsStateWithLifecycle()
160− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
161− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
162− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
163− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
164− val draft by vm.draft.collectAsStateWithLifecycle()
165− val attachments by vm.attachments.collectAsStateWithLifecycle()
166− val reverted by vm.reverted.collectAsStateWithLifecycle()
167− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
168− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
169− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
170− val isOnline by container.isOnline.collectAsStateWithLifecycle()
171− val haptics = LocalHapticFeedback.current
172− val scope = rememberCoroutineScope()
173− val shareContext = LocalContext.current
174− val defaultShareSubject = stringResource(R.string.share_subject)
175− val sessionLabel = stringResource(R.string.session)
176− val defaultModelLabel = stringResource(R.string.default_model)
177− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
179− append(selectedModel?.modelLabel ?: defaultModelLabel)
180− selectedAgent?.let { append(" · $it") }
184− // Connection profile (with auth) for rendering inline image attachments.
185− // Collect as state so a server switch recomposes the image context.
186− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
187− val imageContext = remember(activeConnection?.profile) {
188− activeConnection?.profile?.toImageContext()
191− // Mark this session as read while the user is viewing it; clear on leave so new
192− // background activity can badge it again.
193− DisposableEffect(sessionId) {
194− container.setCurrentSession(sessionId)
195− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
198− // Navigate away when the session is deleted via SSE so the user isn't left
199− // on a zombie screen showing a conversation that no longer exists. Surface a
200− // toast (not a snackbar) because the screen is about to be popped — a snackbar
201− // would be torn down before the user could read it, while a toast survives.
202− // Covers both SSE-driven deletion (deleted on another device) and a user-
203− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
204− // sets the same flag on success).
205− val deletedContext = LocalContext.current
206− LaunchedEffect(sessionDeleted) {
207− if (sessionDeleted) {
208− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
213− val snackbar = remember { SnackbarHostState() }
214− val retryLabel = stringResource(R.string.retry)
215− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
216− var showModelPicker by rememberSaveable { mutableStateOf(false) }
217− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
218− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
219− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
220− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
221− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
222− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
223− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
224− var showShellDialog by rememberSaveable { mutableStateOf(false) }
225− var showPalette by rememberSaveable { mutableStateOf(false) }
227− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
228− // action list doesn't need a Composable context. Actions map to the same handlers the
229− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
230− val paletteModelLabel = stringResource(R.string.palette_switch_model)
231− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
232− val paletteCommandLabel = stringResource(R.string.palette_run_command)
233− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
234− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
235− val paletteShellLabel = stringResource(R.string.run_shell_command)
236− val paletteActions = remember(
237− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
238− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
241− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
242− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
243− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
244− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { vm.summarize() })
245− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
246− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
250− // Keep the screen awake while the agent is working in *this* session. The foreground
251− // service that holds process priority during a run is managed app-wide off
252− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
253− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
254− // SSE stream before the completion notification fires.
255− val currentView = LocalView.current
256− val appContext = LocalContext.current.applicationContext
257− DisposableEffect(running) {
258− currentView.keepScreenOn = running
259− onDispose { currentView.keepScreenOn = false }
262− LaunchedEffect(Unit) {
263− vm.errorEvents.collect { event ->
264− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
265− // message-load failure) would silently re-submit the last prompt on tap.
266− val result = if (event.retryable) {
267− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
269− snackbar.showSnackbar(event.message)
271− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
275− // --- Attachments, voice, and share-link plumbing ---
276− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
277− val attachFailedMsg = stringResource(R.string.attachment_failed)
278− val attachLimitMsg = stringResource(R.string.attachment_limit)
279− val noCameraMsg = stringResource(R.string.no_camera_app)
280− val noVoiceMsg = stringResource(R.string.no_voice_app)
281− val voicePrompt = stringResource(R.string.voice_prompt)
282− val linkCopiedMsg = stringResource(R.string.link_copied)
284− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
285− // per-prompt count cap and surfacing per-file errors without aborting the batch.
286− fun stageUris(uris: List<Uri>) {
287− if (uris.isEmpty()) return
290− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
291− snackbar.showSnackbar(attachLimitMsg)
294− when (val result = uri.toAttachmentResult(appContext)) {
295− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
296− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
297− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
303− val photoPicker = rememberLauncherForActivityResult(
304− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
305− ) { uris -> stageUris(uris) }
307− val filePicker = rememberLauncherForActivityResult(
308− ActivityResultContracts.GetMultipleContents(),
309− ) { uris -> stageUris(uris) }
311− // Uri survives a config change mid-capture so the TakePicture result still resolves.
312− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
313− val cameraLauncher = rememberLauncherForActivityResult(
314− ActivityResultContracts.TakePicture(),
316− val uri = pendingCaptureUri
317− pendingCaptureUri = null
318− if (success && uri != null) stageUris(listOf(uri))
321− val voiceLauncher = rememberLauncherForActivityResult(
322− ActivityResultContracts.StartActivityForResult(),
324− if (result.resultCode == Activity.RESULT_OK) {
325− val spoken = result.data
326− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
328− ?.takeIf { it.isNotBlank() }
329− if (spoken != null) {
330− // Append to the existing draft rather than replacing, so dictation adds to
331− // whatever the user already typed.
332− val current = vm.draft.value
333− val combined = if (current.isBlank()) spoken else "$current $spoken"
334− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
339− fun launchCamera() {
340− val uri = newCameraCaptureUri(appContext)
342− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
345− pendingCaptureUri = uri
346− runCatching { cameraLauncher.launch(uri) }
347− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
351− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
352− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
353− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
355− runCatching { voiceLauncher.launch(intent) }
356− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
359− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
360− LaunchedEffect(Unit) {
361− vm.shareLinkEvents.collect { url ->
362− copyToClipboard(shareContext, "share", url)
363− snackbar.showSnackbar(linkCopiedMsg)
367− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
368− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
369− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
370− // a dropped branch-navigation event in the gap.
371− val branchedMsg = stringResource(R.string.branch_created)
372− LaunchedEffect(Unit) {
373− vm.branchEvents.collect { newId ->
374− showToast(shareContext, branchedMsg)
375− onOpenSession?.invoke(newId)
379− // Stage images shared into the app (via the system share sheet) as attachments.
380− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
381− // while this ChatScreen is already composed — which happens in two-pane mode, where the
382− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
383− // only fire on first composition. consumePendingSharedMedia() atomically drains the
384− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
385− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
386− LaunchedEffect(pendingSharedMedia) {
387− val shared = container.consumePendingSharedMedia()
388− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
392− if (vm.send(draft)) {
393− // TextHandleMove (a light tick) is semantically right for a send commit;
394− // LongPress is reserved for long-press/swipe gestures.
395− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
399− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
402− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
403− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
404− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
405− // typing (and the composer's own Enter-to-send handling) is untouched.
406− modifier = Modifier.onPreviewKeyEvent { ev ->
407− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
409− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
410− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
411− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
412− showStopConfirm = true; true
420− val changeLabel = stringResource(R.string.change_model_agent)
423− .clickable(enabled = models.isNotEmpty(), role = Role.Button) { showModelPicker = true }
424− .semantics(mergeDescendants = true) { contentDescription = changeLabel },
425− verticalAlignment = Alignment.CenterVertically,
427− Column(modifier = Modifier.weight(1f, fill = false)) {
428− // maxLines=1 + Ellipsis so a long session title can't wrap and
429− // push the top bar to multiple lines, shifting the whole layout.
431− sessionTitle ?: sessionLabel,
433− overflow = TextOverflow.Ellipsis,
437− style = MaterialTheme.typography.labelSmall,
438− color = MaterialTheme.colorScheme.onSurfaceVariant,
440− overflow = TextOverflow.Ellipsis,
443− // Visual affordance that the title opens the model picker;
444− // without it the tappable title is indistinguishable from plain
445− // text and the picker is effectively undiscoverable.
446− if (models.isNotEmpty()) {
448− Icons.Filled.KeyboardArrowDown,
449− contentDescription = null,
450− tint = MaterialTheme.colorScheme.onSurfaceVariant,
451− modifier = Modifier.size(20.dp),
457− IconButton(onClick = {
458− if (running) showExitConfirm = true else onBack()
460− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
464− // At-a-glance run status in the top bar. When the user is scrolled
465− // up (jump-to-latest FAB visible), the input-bar Stop button and the
466− // trailing "working…" row are off-screen, so a top-bar spinner is the
467− // only signal the agent is still working.
469− val workingLabel = stringResource(R.string.working)
470− CircularProgressIndicator(
471− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
475− // Manual refresh: forces an SSE reconnect, which re-seeds messages
476− // from REST. A recovery path when the stream silently drops and the
477− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
478− // immediate tap feedback — the SSE reconnect may not visibly change
479− // the connection state when already Connected, so without it the tap
480− // appears to do nothing.
481− val refreshLabel = stringResource(R.string.refresh)
483− onClick = { vm.refreshMessages() },
484− enabled = activeConnection != null && !refreshing,
487− CircularProgressIndicator(
488− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
492− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
495− // Overflow menu consolidates the less-frequent actions (share,
496− // commands, agent, model, rename, delete) so the top bar stays
497− // scannable on narrow phones — previously 5 icons crowded the bar
498− // alongside the back button and tappable title. Catalog-loading
499− // spinners stay inline (next to the overflow) so a load state is
500− // visible without opening the menu.
501− val moreLabel = stringResource(R.string.more)
502− val loadingLabel = stringResource(R.string.loading)
503− val shareLabel = stringResource(R.string.share_conversation)
504− val commandsLabel = stringResource(R.string.commands)
505− val agentLabel = stringResource(R.string.choose_agent)
506− val modelLabel = stringResource(R.string.choose_model)
507− val renameLabel = stringResource(R.string.rename_session_chat)
508− val deleteLabel = stringResource(R.string.delete_session_chat)
509− val createShareLabel = stringResource(R.string.create_share_link)
510− val copyShareLabel = stringResource(R.string.copy_share_link)
511− val stopShareLabel = stringResource(R.string.stop_sharing)
512− val summarizeLabel = stringResource(R.string.summarize_conversation)
513− val initLabel = stringResource(R.string.generate_agents_md)
514− val shellLabel = stringResource(R.string.run_shell_command)
516− IconButton(onClick = { showOverflowMenu = true }) {
517− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
520− expanded = showOverflowMenu,
521− onDismissRequest = { showOverflowMenu = false },
524− text = { Text(shareLabel) },
525− enabled = hasMessages,
527− showOverflowMenu = false
529− val md = withContext(Dispatchers.Default) {
530− buildConversationMarkdown(vm.messages.value, sessionTitle)
532− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
533− type = "text/markdown"
534− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
535− putExtra(android.content.Intent.EXTRA_TEXT, md)
537− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
538− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
543− text = { Text(commandsLabel) },
544− enabled = !commandsLoading || commands.isNotEmpty(),
545− onClick = { showOverflowMenu = false; showCommandPicker = true },
548− text = { Text(agentLabel) },
549− enabled = !agentsLoading || agents.isNotEmpty(),
550− onClick = { showOverflowMenu = false; showAgentPicker = true },
553− text = { Text(modelLabel) },
554− enabled = !modelsLoading || models.isNotEmpty(),
555− onClick = { showOverflowMenu = false; showModelPicker = true },
557− androidx.compose.material3.HorizontalDivider()
558− // Session sharing: create a public link, copy an existing one, or revoke it.
559− if (shareUrl == null) {
561− text = { Text(createShareLabel) },
562− enabled = hasMessages,
563− onClick = { showOverflowMenu = false; vm.shareSession() },
567− text = { Text(copyShareLabel) },
569− showOverflowMenu = false
571− copyToClipboard(shareContext, "share", it)
572− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
577− text = { Text(stopShareLabel) },
578− onClick = { showOverflowMenu = false; vm.unshareSession() },
582− text = { Text(summarizeLabel) },
583− enabled = hasMessages && !running,
584− onClick = { showOverflowMenu = false; vm.summarize() },
587− text = { Text(initLabel) },
589− onClick = { showOverflowMenu = false; vm.initProject() },
592− text = { Text(shellLabel) },
594− onClick = { showOverflowMenu = false; showShellDialog = true },
596− androidx.compose.material3.HorizontalDivider()
598− text = { Text(renameLabel) },
599− onClick = { showOverflowMenu = false; showRenameDialog = true },
602− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
603− onClick = { showOverflowMenu = false; showDeleteDialog = true },
606− // While a catalog is initially loading (empty list + loading flag),
607− // show a tiny inline spinner beside the overflow so the user can see
608− // a load is in progress without opening the menu. Once loaded the
609− // spinner disappears; the menu items are always enabled (tapping a
610− // picker with no items shows the "no models/agents/commands" state).
611− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
612− (agentsLoading && agents.isEmpty()) ||
613− (modelsLoading && models.isEmpty())
614− if (catalogLoading) {
615− CircularProgressIndicator(
617− .align(Alignment.TopEnd)
619− .semantics { contentDescription = loadingLabel },
627− snackbarHost = { SnackbarHost(snackbar) },
629− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
630− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
631− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
632− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
634− // Pinned above the composer so the agent's plan and progress stay visible
635− // while scrolled up mid-run; renders nothing when there's no plan.
636− TodoPlanBar(todoPlan)
637− AnimatedVisibility(visible = reverted) {
638− RevertBanner(onUndo = { vm.unrevert() })
640− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
642− count = queuedOffline.size,
643− sending = outboxSending,
644− onFlush = { vm.flushQueued() },
645− onDiscard = { vm.discardAllQueued() },
650− onValueChange = vm::updateDraft,
652− aborting = aborting,
653− enabled = activeConnection != null,
654− sendOnEnter = sendOnEnter,
656− onAbort = { showStopConfirm = true },
657− queuedFollowUp = queuedFollowUp,
658− onQueueFollowUp = vm::queueFollowUp,
659− onCancelQueue = { vm.queueFollowUp("") },
660− focusRequester = inputFocusRequester,
661− attachments = attachments,
662− onRemoveAttachment = vm::removeAttachment,
665− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
668− onPickFile = { filePicker.launch("*/*") },
669− onCamera = { launchCamera() },
670− onVoice = { launchVoice() },
675− // Collect messages inside the content lambda so streaming token updates
676− // recompose only this subtree, not the top bar / input bar / 20+ other
677− // state reads in the ChatScreen body.
678− val messages by vm.messages.collectAsStateWithLifecycle()
679− val listState = rememberLazyListState()
680− val contentScope = rememberCoroutineScope()
681− val timeTick = rememberRelativeTimeTick()
682− // Group messages by day and interleave date separators so a long conversation
683− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
684− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
685− // outside the PullToRefreshBox so the auto-scroll effects below can reference
686− // the same list the LazyColumn renders (separators shift the indices vs. the
687− // raw messages list, so scroll targets must be in listItems space).
688− val todayLabel = stringResource(R.string.today)
689− val yesterdayLabel = stringResource(R.string.yesterday)
690− val listItems = remember(messages, todayLabel, yesterdayLabel) {
691− buildMessageListItems(messages, todayLabel, yesterdayLabel)
693− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
694− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
695− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
696− // would capture the first composition's list — which is empty, since `messages`
697− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
698− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
699− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
700− // whose value tracks the latest list.
701− val currentListItems by rememberUpdatedState(listItems)
703− val isPinnedToBottom by remember {
705− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
706− // When a run is active, the LazyColumn has one trailing "__typing"
707− // item after the last list item. Account for it so "pinned to bottom"
708− // includes the working indicator — otherwise the pin check targets
709− // listItems.lastIndex, the typing row sits just below the viewport,
710− // and the user never sees the progress indicator even when pinned.
711− val items = currentListItems
712− val effectiveLast = if (running) items.size else items.lastIndex
713− lastVisible >= effectiveLast || items.isEmpty()
717− // Jump to the newest message once, when the conversation first loads. Guarded by a
718− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
719− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
720− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
721− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
722− LaunchedEffect(listItems.isNotEmpty()) {
723− if (listItems.isNotEmpty() && !didInitialScroll) {
724− // When a run is active the LazyColumn has a trailing "__typing" row at
725− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
726− // running session lands truly pinned to bottom and streaming auto-scroll engages.
727− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
728− didInitialScroll = true
732− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
733− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
734− // isPinnedToBottom check flips to false the instant you send — freezing
735− // auto-scroll. If the user was pinned to the last item just before the run
736− // began, bring the typing row into view so the pin (and streaming follow) is
737− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
738− // recomputed to false by now) so we don't scroll when the user had scrolled up.
739− LaunchedEffect(running) {
740− if (running && listItems.isNotEmpty()) {
741− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
742− if (lastVisible >= listItems.lastIndex) {
743− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
748− LaunchedEffect(Unit) {
750− // Track list size + the streaming length of the last part so we auto-scroll
751− // as content arrives, plus the pinned flag. A small data class with primitive
752− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
753− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
754− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
755− // and tool output — not just TextPart — keeps a pinned view following a long
756− // reasoning/tool block while it streams (previously it stalled at 0).
757− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
758− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
759− }.collect { signal ->
760− if (signal.size > 0 && signal.pinned) {
761− // Scroll to the effective last index, including the trailing
762− // "__typing" row when a run is active so the working indicator
763− // is brought into view (not just the last message).
764− val items = currentListItems
765− val target = if (running) items.size else items.lastIndex
766− listState.scrollToItem(target)
771− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
772− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
773− // content padding accounts for the bottomBar's raised height, so the message
774− // list is already above the keyboard. Adding imePadding here would double-apply
775− // the IME inset and push messages too far up.
776− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
777− if (activeConnection == null) {
779− modifier = Modifier.align(Alignment.Center).padding(24.dp),
780− horizontalAlignment = Alignment.CenterHorizontally,
783− stringResource(R.string.not_connected),
784− color = MaterialTheme.colorScheme.error,
786− Spacer(Modifier.size(12.dp))
787− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
789− CircularProgressIndicator(
790− Modifier.size(20.dp),
791− color = MaterialTheme.colorScheme.onPrimary,
795− Text(stringResource(R.string.reconnect))
801− state = connectionState,
802− modifier = Modifier.align(Alignment.TopCenter),
803− isOnline = isOnline,
804− // On a hard failure, retry by forcing an SSE reconnect (which
805− // re-seeds from REST). refreshMessages is the right recovery path
806− // when the connection is present but the stream died; reconnect()
807− // is the path when the whole connection is gone (handled by the
808− // separate "Not connected" state below).
809− onRetry = { vm.refreshMessages() },
811− if (loading && messages.isEmpty()) {
812− val loadingLabel = stringResource(R.string.loading)
813− CircularProgressIndicator(
815− .align(Alignment.Center)
816− .semantics { contentDescription = loadingLabel },
818− } else if (loadError && messages.isEmpty()) {
819− // A failed load with nothing to show. Distinct from the empty
820− // conversation state below — the conversation isn't empty, it
821− // failed to load, and offering "Start a conversation" here is
822− // misleading. Offer a Retry instead, mirroring SessionListScreen.
824− modifier = Modifier.align(Alignment.Center).padding(24.dp),
825− horizontalAlignment = Alignment.CenterHorizontally,
828− stringResource(R.string.load_messages_failed),
829− color = MaterialTheme.colorScheme.error,
831− Spacer(Modifier.size(12.dp))
832− Button(onClick = { vm.refreshMessages() }) {
833− Text(stringResource(R.string.retry))
836− } else if (messages.isEmpty() && running) {
837− // A run just started but no parts have arrived yet — the empty
838− // list with only the trailing "working…" row looks broken, so
839− // surface a clear starting state until the first part streams in.
840− val workingText = stringResource(R.string.working)
842− modifier = Modifier.align(Alignment.Center).padding(24.dp),
843− horizontalAlignment = Alignment.CenterHorizontally,
845− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
846− Spacer(Modifier.size(12.dp))
847− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
849− } else if (messages.isEmpty()) {
853− // Focus the input so the user can edit the suggestion before
854− // sending, instead of having to manually tap the field.
855− runCatching { inputFocusRequester.requestFocus() }
857− modifier = Modifier.align(Alignment.Center),
860− // Pull-to-refresh wraps the message list so the user can force an SSE
861− // reconnect + re-seed with the same gesture they use on the session and
862− // file lists, instead of hunting for the top-bar refresh icon. The empty
863− // / loading / error states above stay outside the PTR box since there's
864− // no list content to pull against.
866− isRefreshing = refreshing,
867− onRefresh = { vm.refreshMessages() },
868− modifier = Modifier.fillMaxSize(),
870− val lastMessageId = messages.lastOrNull()?.info?.id
871− // Text-to-speech for reading assistant replies aloud; shuts down when the
872− // message list leaves composition.
873− val tts = rememberTtsController()
874− val speakingMessageId by tts.speakingId
877− modifier = Modifier.fillMaxSize(),
878− contentPadding = PaddingValues(16.dp),
879− verticalArrangement = Arrangement.spacedBy(16.dp),
884− contentType = { it.contentType },
887− is MessageListItem.Separator -> DateSeparator(item.label)
888− is MessageListItem.Message -> {
889− val message = item.message
890− // Only the last (streaming) message needs isRunning — it drives the
891− // reasoning-block spinner. Passing the live flag to every bubble
892− // makes all visible messages recompose whenever a run starts or stops.
893− val modelLabel = remember(message.info, models) {
894− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
895− ?.let { resolveModelLabel(it, models) }
899− isRunning = running && message.info.id == lastMessageId,
900− imageContext = imageContext,
901− modelLabel = modelLabel,
902− onOpenFile = onOpenFile,
903− onRevert = { vm.revertTo(message.info.id) },
904− onEdit = { text -> vm.editMessage(message.info.id, text) },
905− onSpeak = { text -> tts.toggle(message.info.id, text) },
906− isSpeaking = message.info.id == speakingMessageId,
909− runCatching { inputFocusRequester.requestFocus() }
911− onBranch = { text -> vm.branchFrom(text) },
917− item(key = "__typing") {
918− val workingText = stringResource(R.string.working)
920− verticalAlignment = Alignment.CenterVertically,
921− modifier = Modifier.semantics {
922− contentDescription = workingText
925− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
926− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
932− // Jump-to-latest affordance when the user has scrolled away during a stream.
934− visible = !isPinnedToBottom && listItems.isNotEmpty(),
935− modifier = Modifier.align(Alignment.BottomEnd),
937− ExtendedFloatingActionButton(
939− if (listItems.isNotEmpty()) {
940− // Scroll to the effective last index, including the
941− // trailing "__typing" row when a run is active.
942− val target = if (running) listItems.size else listItems.lastIndex
943− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
946− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(R.string.latest)) },
947− text = { Text(stringResource(R.string.latest)) },
948− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
957− if (showExitConfirm) {
959− onDismissRequest = { showExitConfirm = false },
960− title = { Text(stringResource(R.string.stop_and_exit_title)) },
961− text = { Text(stringResource(R.string.stop_and_exit_text)) },
963− TextButton(onClick = {
964− showExitConfirm = false
965− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
968− }) { Text(stringResource(R.string.stop_and_exit)) }
971− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
976− if (showStopConfirm) {
978− onDismissRequest = { showStopConfirm = false },
979− title = { Text(stringResource(R.string.stop_run_title)) },
980− text = { Text(stringResource(R.string.stop_run_text)) },
982− TextButton(onClick = {
983− showStopConfirm = false
984− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
986− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
989− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
994− if (showRenameDialog) {
995− RenameSessionChatDialog(
996− initialTitle = sessionTitle ?: "",
997− onDismiss = { showRenameDialog = false },
998− onConfirm = { newName ->
999− showRenameDialog = false
1000− vm.renameSession(newName)
1005− if (showDeleteDialog) {
1007− onDismissRequest = { showDeleteDialog = false },
1008− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1009− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1011− TextButton(onClick = {
1012− showDeleteDialog = false
1013− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1015− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1018− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1023− if (showShellDialog) {
1024− ShellCommandDialog(
1025− onDismiss = { showShellDialog = false },
1027− showShellDialog = false
1033− if (showModelPicker) {
1036− selected = selectedModel,
1037− loading = modelsLoading,
1038− error = modelsError,
1039− onSelect = { vm.selectModel(it) },
1040− onRetry = { vm.reloadModels() },
1041− onDismiss = { showModelPicker = false },
1045− if (showAgentPicker) {
1048− selected = selectedAgent,
1049− loading = agentsLoading,
1050− error = agentsError,
1051− onSelect = { vm.selectAgent(it?.name) },
1052− onRetry = { vm.reloadAgents() },
1053− onDismiss = { showAgentPicker = false },
1057− if (showCommandPicker) {
1058− CommandPickerSheet(
1059− commands = commands,
1060− loading = commandsLoading,
1061− error = commandsError,
1062− onSelect = { vm.runCommand(it) },
1063− onRetry = { vm.reloadCommands() },
1064− onDismiss = { showCommandPicker = false },
1068− pendingPermission?.let { permission ->
1070− permission = permission,
1071− onRespond = { response -> vm.respondPermission(permission, response) },
1076− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1081−private fun ChatInputBar(
1083− onValueChange: (String) -> Unit,
1087− sendOnEnter: Boolean,
1088− onSend: () -> Unit,
1089− onAbort: () -> Unit,
1090− queuedFollowUp: String?,
1091− onQueueFollowUp: (String) -> Unit,
1092− onCancelQueue: () -> Unit,
1093− focusRequester: androidx.compose.ui.focus.FocusRequester,
1094− attachments: List<PendingAttachment>,
1095− onRemoveAttachment: (String) -> Unit,
1096− onPickPhoto: () -> Unit,
1097− onPickFile: () -> Unit,
1098− onCamera: () -> Unit,
1099− onVoice: () -> Unit,
1101− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1102− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1103− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1104− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1105− // A queued follow-up replaces the Stop button with a "queued" chip so the
1106− // user sees their message will be sent when the run finishes, and can cancel.
1107− if (queuedFollowUp != null) {
1109− modifier = Modifier
1111− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1112− verticalAlignment = Alignment.CenterVertically,
1114− Column(modifier = Modifier.weight(1f)) {
1116− stringResource(R.string.queued),
1117− style = MaterialTheme.typography.labelSmall,
1118− color = MaterialTheme.colorScheme.onSurfaceVariant,
1122− style = MaterialTheme.typography.bodySmall,
1123− color = MaterialTheme.colorScheme.onSurfaceVariant,
1125− overflow = TextOverflow.Ellipsis,
1128− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1129− Text(stringResource(R.string.cancel))
1133− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1134− AttachmentStrip(attachments, onRemove = onRemoveAttachment)
1136− modifier = Modifier.fillMaxWidth().padding(8.dp),
1137− verticalAlignment = Alignment.Bottom,
1139− // Attach menu: photo picker, camera, or any file.
1140− var showAttachMenu by remember { mutableStateOf(false) }
1142− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1143− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1145− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1147− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1148− text = { Text(stringResource(R.string.attach_photo)) },
1149− onClick = { showAttachMenu = false; onPickPhoto() },
1152− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1153− text = { Text(stringResource(R.string.attach_camera)) },
1154− onClick = { showAttachMenu = false; onCamera() },
1157− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1158− text = { Text(stringResource(R.string.attach_file)) },
1159− onClick = { showAttachMenu = false; onPickFile() },
1163− // Voice dictation: appends recognized speech to the draft.
1164− IconButton(onClick = onVoice, enabled = enabled) {
1165− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1169− onValueChange = { v ->
1170− // Cap input length so a huge paste can't stall the UI. Shares are
1171− // capped separately in MainActivity; this guards typed/pasted drafts.
1172− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1174− modifier = Modifier
1176− .focusRequester(focusRequester)
1177− .testTag("chat_input")
1178− .onPreviewKeyEvent { event ->
1179− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1180− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1181− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1182− val send = enterShouldSend(
1184− hasContent = hasContent,
1185− sendOnEnter = sendOnEnter,
1186− shift = event.isShiftPressed,
1187− ctrl = event.isCtrlPressed,
1190− if (running) onQueueFollowUp(value) else onSend()
1196− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1199− // Show a "N / max" countdown once the draft crosses a high fraction of
1200− // the cap, so the user knows a paste is about to be truncated instead
1201− // of being silently cut off. Hidden for normal short prompts to avoid
1202− // clutter under a typical one-line message.
1204− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1205− if (value.length >= threshold) {
1208− R.string.draft_chars_remaining,
1209− NetworkConfig.maxDraftLengthChars - value.length,
1210− NetworkConfig.maxDraftLengthChars,
1212− style = MaterialTheme.typography.labelSmall,
1213− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1214− else MaterialTheme.colorScheme.onSurfaceVariant,
1218− keyboardOptions = KeyboardOptions(
1219− // With send-on-Enter off, expose the platform default action so the soft
1220− // keyboard shows a newline key (this is a multi-line field) instead of a
1221− // Send action — otherwise the setting has no effect on soft keyboards and
1222− // there's no way to type a newline. Hardware Enter is handled separately.
1223− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1224− capitalization = KeyboardCapitalization.Sentences,
1226− keyboardActions = KeyboardActions(onSend = {
1227− if (enabled && hasContent) {
1228− if (running) onQueueFollowUp(value) else onSend()
1232− ComposerTrailingButton(
1234− aborting = aborting,
1235− canSend = enabled && hasContent,
1238− onQueue = { onQueueFollowUp(value) },
1245−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1246− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1247−private fun enterShouldSend(
1249− hasContent: Boolean,
1250− sendOnEnter: Boolean,
1254− !enabled || !hasContent -> false
1255− sendOnEnter -> !shift
1259−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1260− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1261− * [ChatInputBar] stays under the complexity threshold. */
1263−private fun ComposerTrailingButton(
1267− onSend: () -> Unit,
1268− onAbort: () -> Unit,
1269− onQueue: () -> Unit,
1272− Row(verticalAlignment = Alignment.CenterVertically) {
1273− // While a run is active the trailing action is Stop, so the only send affordance is
1274− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1275− // That leaves a touch-only user with the setting off no way to queue a follow-up
1276− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1277− // there's typed content so queuing is always reachable, without changing the user's
1278− // Enter-inserts-a-newline preference.
1282− modifier = Modifier.testTag("queue_button"),
1285− Icons.AutoMirrored.Filled.Send,
1286− contentDescription = stringResource(R.string.queue_followup),
1290− // Show a spinner while the abort REST call is in flight so the user sees the stop
1291− // was sent, and disable to prevent a double-tap.
1294− enabled = !aborting,
1295− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1298− val stopLabel = stringResource(R.string.stop)
1299− CircularProgressIndicator(
1300− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1301− strokeWidth = 2.dp,
1304− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1312− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1314− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1319−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1321−private fun EmptyConversation(
1322− onSuggestion: (String) -> Unit,
1323− modifier: Modifier = Modifier,
1325− // A few example prompts so a first-time user has a one-tap path to their first
1326− // message instead of staring at a blank input. Tapping a chip fills the draft
1327− // (without sending) so the user can edit it before sending.
1328− val suggestions = remember {
1330− R.string.empty_chat_suggest_1,
1331− R.string.empty_chat_suggest_2,
1332− R.string.empty_chat_suggest_3,
1336− modifier = modifier.padding(32.dp),
1337− horizontalAlignment = Alignment.CenterHorizontally,
1340− Icons.Filled.AutoAwesome,
1341− contentDescription = null,
1342− modifier = Modifier.size(48.dp),
1343− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1345− Spacer(Modifier.size(16.dp))
1347− stringResource(R.string.empty_chat_title),
1348− style = MaterialTheme.typography.titleMedium,
1350− Spacer(Modifier.size(8.dp))
1352− stringResource(R.string.empty_chat_hint),
1353− style = MaterialTheme.typography.bodyMedium,
1354− color = MaterialTheme.colorScheme.onSurfaceVariant,
1356− Spacer(Modifier.size(20.dp))
1357− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1358− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1360− modifier = Modifier.fillMaxWidth(),
1361− horizontalArrangement = Arrangement.spacedBy(8.dp),
1362− verticalArrangement = Arrangement.spacedBy(8.dp),
1364− suggestions.forEach { resId ->
1365− val text = stringResource(resId)
1366− androidx.compose.material3.AssistChip(
1367− onClick = { onSuggestion(text) },
1368− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1375−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1377−private fun RevertBanner(onUndo: () -> Unit) {
1379− color = MaterialTheme.colorScheme.tertiaryContainer,
1380− tonalElevation = 2.dp,
1381− modifier = Modifier.fillMaxWidth(),
1384− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1385− verticalAlignment = Alignment.CenterVertically,
1386− horizontalArrangement = Arrangement.SpaceBetween,
1388− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1390− Icons.Filled.Restore,
1391− contentDescription = null,
1392− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1393− modifier = Modifier.size(18.dp),
1396− stringResource(R.string.reverted_banner),
1397− style = MaterialTheme.typography.bodySmall,
1398− color = MaterialTheme.colorScheme.onTertiaryContainer,
1399− modifier = Modifier.padding(start = 8.dp),
1402− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1407−/** A banner shown while messages composed offline are queued in the outbox, with a
1408− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1410−private fun OutboxBanner(
1413− onFlush: () -> Unit,
1414− onDiscard: () -> Unit,
1417− color = MaterialTheme.colorScheme.secondaryContainer,
1418− tonalElevation = 2.dp,
1419− modifier = Modifier.fillMaxWidth(),
1422− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1423− verticalAlignment = Alignment.CenterVertically,
1424− horizontalArrangement = Arrangement.SpaceBetween,
1426− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1428− CircularProgressIndicator(
1429− Modifier.size(16.dp),
1430− strokeWidth = 2.dp,
1431− color = MaterialTheme.colorScheme.onSecondaryContainer,
1433− Spacer(Modifier.size(8.dp))
1437− stringResource(R.string.outbox_sending)
1439− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1440− stringResource(res, count)
1442− style = MaterialTheme.typography.bodySmall,
1443− color = MaterialTheme.colorScheme.onSecondaryContainer,
1447− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1448− TextButton(onClick = onDiscard) {
1449− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1456−/** Prompt for a one-off shell command to run in the session's worktree. */
1458−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1459− var command by rememberSaveable { mutableStateOf("") }
1461− onDismissRequest = onDismiss,
1462− title = { Text(stringResource(R.string.run_shell_command)) },
1466− onValueChange = { command = it },
1467− modifier = Modifier.fillMaxWidth(),
1468− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1469− label = { Text(stringResource(R.string.shell_command_label)) },
1471− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1472− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1477− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1478− enabled = command.isNotBlank(),
1479− ) { Text(stringResource(R.string.run)) }
1481− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1486− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1487− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1488− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1490−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1492−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1493− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1494− * streaming, not just plain assistant text. O(1). */
1495−private fun streamingContentLength(part: Part?): Int = when (part) {
1496− is TextPart -> part.text.length
1497− is ReasoningPart -> part.text.length
1498− is ToolPart -> when (val st = part.state) {
1499− is ToolCompleted -> st.output?.length ?: 0
1500− is ToolError -> st.error?.length ?: 0
1501− is ToolRunning -> st.title?.length ?: 0
1507−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1508− * dialog but lives in the chat screen so the user can rename without backing out to
1509− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1511−private fun RenameSessionChatDialog(
1512− initialTitle: String,
1513− onDismiss: () -> Unit,
1514− onConfirm: (String) -> Unit,
1516− // Seed the field once (no key input) so a later external title change — e.g. opencode
1517− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1518− // doesn't re-initialize the box and discard the user's in-progress edit.
1519− var title by rememberSaveable { mutableStateOf(initialTitle) }
1521− onDismissRequest = onDismiss,
1522− title = { Text(stringResource(R.string.rename_session_chat)) },
1526− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1527− modifier = Modifier.fillMaxWidth(),
1528− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1529− label = { Text(stringResource(R.string.rename_session_chat)) },
1531− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1532− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1536− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1537− Text(stringResource(R.string.save))
1541− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1547− * A single item in the chat message list — either a [Message] bubble or a day
1548− * [Separator] inserted before the first message of a new day. The separator shifts
1549− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1550− * the [List] of these items (not `messages.size`/`lastIndex`).
1552−private sealed interface MessageListItem {
1554− val contentType: Any
1556− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1557− override val contentType: Any get() = message.info::class
1560− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1561− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1562− // can share a label (e.g. an untimestamped message — empty label — between two
1563− // same-day messages, or two untimestamped groups), and a label-only key would
1564− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1565− // stable for a given message ordering so slots aren't needlessly recreated.
1566− override val key: Any get() = "sep_${ordinal}_$label"
1567− // Separators share a contentType so the LazyColumn can recycle their slots.
1568− override val contentType: Any get() = "separator"
1573− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1574− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1575− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1576− * Messages with no timestamp are grouped under an empty-label separator only if they
1577− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1579− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1580− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1581− * labels; older days fall back to a locale-stable medium-date format.
1583−private fun buildMessageListItems(
1584− messages: List<MessageWithParts>,
1585− todayLabel: String,
1586− yesterdayLabel: String,
1587−): List<MessageListItem> {
1588− if (messages.isEmpty()) return emptyList()
1589− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1590− val dateFmt = mediumDateFormat()
1591− val result = ArrayList<MessageListItem>(messages.size + 4)
1592− val seenKeys = HashSet<String>(messages.size * 2)
1593− var lastDayKey: String? = null
1595− var emptyIdOrdinal = 0
1596− for (message in messages) {
1597− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1598− val dayKey = ts?.let { dayKey(it) } ?: ""
1599− if (dayKey != lastDayKey) {
1600− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1601− lastDayKey = dayKey
1603− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1604− // empty id — and the reducer intentionally keeps several such messages as distinct
1605− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1606− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1607− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1608− if (!seenKeys.add(key)) {
1610− while (!seenKeys.add("$key#$suffix")) suffix++
1611− key = "$key#$suffix"
1613− result.add(MessageListItem.Message(message, key))
1619− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1621− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1622− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1623− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1624− * every message on every token. Message timestamps are immutable once assigned, so we
1625− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1626− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1627− * thread during composition, so the coarse lock is uncontended.
1629−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1630− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1633−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1634− dayKeyCache.getOrPut(epochMillis) {
1635− java.time.Instant.ofEpochMilli(epochMillis)
1636− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1640−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1641−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1642−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1643−private var cachedDateFmt: java.text.DateFormat? = null
1644−private var cachedDateFmtLocale: java.util.Locale? = null
1646−private fun mediumDateFormat(): java.text.DateFormat {
1647− val locale = java.util.Locale.getDefault()
1648− val existing = cachedDateFmt
1649− if (existing != null && cachedDateFmtLocale == locale) return existing
1650− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1652− cachedDateFmtLocale = locale
1657− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1658− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1659− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1662−private fun dayLabel(
1665− today: java.time.LocalDate,
1666− todayLabel: String,
1667− yesterdayLabel: String,
1668− dateFmt: java.text.DateFormat,
1670− if (dayKey.isEmpty()) return ""
1671− val epochDay = dayKey.toLongOrNull() ?: return ""
1672− val date = java.time.LocalDate.ofEpochDay(epochDay)
1674− date == today -> todayLabel
1675− date == today.minusDays(1) -> yesterdayLabel
1676− else -> dateFmt.format(java.util.Date(ts))
1681− * A centered day divider in the message list. Renders nothing for an empty label
1682− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1685−private fun DateSeparator(label: String) {
1686− if (label.isBlank()) return
1688− modifier = Modifier.fillMaxWidth(),
1689− horizontalArrangement = Arrangement.Center,
1692− color = MaterialTheme.colorScheme.surfaceVariant,
1693− shape = MaterialTheme.shapes.small,
1697− style = MaterialTheme.typography.labelSmall,
1698− color = MaterialTheme.colorScheme.onSurfaceVariant,
1699− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),