@@ -1,1802 +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.Badge
50−import androidx.compose.material3.BadgedBox
51−import androidx.compose.material3.Button
52−import androidx.compose.material3.CircularProgressIndicator
53−import androidx.compose.material3.DropdownMenu
54−import androidx.compose.material3.DropdownMenuItem
55−import androidx.compose.material3.ExperimentalMaterial3Api
56−import androidx.compose.material3.ExtendedFloatingActionButton
57−import androidx.compose.material3.FloatingActionButton
58−import androidx.compose.material3.Icon
59−import androidx.compose.material3.IconButton
60−import androidx.compose.material3.MaterialTheme
61−import androidx.compose.material3.OutlinedTextField
62−import androidx.compose.material3.Scaffold
63−import androidx.compose.material3.SnackbarHost
64−import androidx.compose.material3.SnackbarHostState
65−import androidx.compose.material3.Surface
66−import androidx.compose.material3.Text
67−import androidx.compose.material3.TextButton
68−import androidx.compose.material3.TopAppBar
69−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
70−import androidx.compose.runtime.Composable
71−import androidx.compose.runtime.CompositionLocalProvider
72−import androidx.compose.runtime.DisposableEffect
73−import androidx.compose.runtime.LaunchedEffect
74−import androidx.compose.runtime.derivedStateOf
75−import androidx.compose.runtime.getValue
76−import androidx.compose.runtime.mutableStateOf
77−import androidx.compose.runtime.remember
78−import androidx.compose.runtime.rememberCoroutineScope
79−import androidx.compose.runtime.rememberUpdatedState
80−import androidx.compose.runtime.saveable.rememberSaveable
81−import androidx.compose.runtime.setValue
82−import androidx.compose.runtime.snapshotFlow
83−import androidx.compose.foundation.text.KeyboardActions
84−import androidx.compose.foundation.text.KeyboardOptions
85−import androidx.compose.ui.text.input.KeyboardCapitalization
86−import androidx.compose.ui.Alignment
87−import androidx.compose.ui.Modifier
88−import androidx.compose.ui.focus.focusRequester
89−import androidx.compose.ui.input.key.Key
90−import androidx.compose.ui.input.key.KeyEventType
91−import androidx.compose.ui.input.key.isCtrlPressed
92−import androidx.compose.ui.input.key.isShiftPressed
93−import androidx.compose.ui.input.key.key
94−import androidx.compose.ui.input.key.onPreviewKeyEvent
95−import androidx.compose.ui.input.key.type
96−import androidx.compose.ui.platform.LocalContext
97−import androidx.compose.ui.platform.LocalHapticFeedback
98−import androidx.compose.ui.platform.LocalView
99−import androidx.compose.ui.platform.testTag
100−import androidx.compose.ui.res.stringResource
101−import androidx.compose.ui.semantics.Role
102−import androidx.compose.ui.semantics.contentDescription
103−import androidx.compose.ui.semantics.semantics
104−import androidx.compose.ui.text.input.ImeAction
105−import androidx.compose.ui.text.style.TextOverflow
106−import androidx.compose.ui.unit.dp
107−import androidx.lifecycle.compose.collectAsStateWithLifecycle
108−import androidx.lifecycle.viewmodel.compose.viewModel
109−import kotlinx.coroutines.Dispatchers
110−import kotlinx.coroutines.launch
111−import kotlinx.coroutines.withContext
112−import soy.iko.opencode.data.model.Part
113−import soy.iko.opencode.data.model.MessageWithParts
114−import soy.iko.opencode.data.model.ReasoningPart
115−import soy.iko.opencode.data.model.TextPart
116−import soy.iko.opencode.data.model.ToolCompleted
117−import soy.iko.opencode.data.model.ToolError
118−import soy.iko.opencode.data.model.ToolPart
119−import soy.iko.opencode.data.model.ToolRunning
120−import soy.iko.opencode.data.network.EventStreamClient
121−import soy.iko.opencode.data.network.NetworkConfig
122−import soy.iko.opencode.di.AppContainer
123−import soy.iko.opencode.R
124−import soy.iko.opencode.ui.components.CommandPalette
125−import soy.iko.opencode.ui.components.ConnectionBanner
126−import soy.iko.opencode.ui.components.PaletteAction
127−import soy.iko.opencode.ui.components.copyToClipboard
128−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
129−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
130−import soy.iko.opencode.ui.components.showToast
131−import soy.iko.opencode.ui.components.toImageContext
132−import soy.iko.opencode.ui.vmFactory
133−import soy.iko.opencode.util.runCatchingCancellable
135−@OptIn(ExperimentalMaterial3Api::class)
138− container: AppContainer,
141− onOpenFile: ((String) -> Unit)? = null,
142− onOpenSession: ((String) -> Unit)? = null,
144− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
145− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
146− val running by vm.running.collectAsStateWithLifecycle()
147− val aborting by vm.aborting.collectAsStateWithLifecycle()
148− val loading by vm.loading.collectAsStateWithLifecycle()
149− val loadError by vm.loadError.collectAsStateWithLifecycle()
150− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
151− val models by vm.models.collectAsStateWithLifecycle()
152− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
153− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
154− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
155− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
156− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
157− val agents by vm.agents.collectAsStateWithLifecycle()
158− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
159− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
160− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
161− val commands by vm.commands.collectAsStateWithLifecycle()
162− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
163− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
164− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
165− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
166− val draft by vm.draft.collectAsStateWithLifecycle()
167− val attachments by vm.attachments.collectAsStateWithLifecycle()
168− val reverted by vm.reverted.collectAsStateWithLifecycle()
169− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
170− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
171− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
172− val isOnline by container.isOnline.collectAsStateWithLifecycle()
173− val haptics = LocalHapticFeedback.current
174− val scope = rememberCoroutineScope()
175− val shareContext = LocalContext.current
176− val defaultShareSubject = stringResource(R.string.share_subject)
177− val sessionLabel = stringResource(R.string.session)
178− val defaultModelLabel = stringResource(R.string.default_model)
179− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
181− append(selectedModel?.modelLabel ?: defaultModelLabel)
182− selectedAgent?.let { append(" · $it") }
186− // Connection profile (with auth) for rendering inline image attachments.
187− // Collect as state so a server switch recomposes the image context.
188− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
189− val imageContext = remember(activeConnection?.profile) {
190− activeConnection?.profile?.toImageContext()
193− // Mark this session as read while the user is viewing it; clear on leave so new
194− // background activity can badge it again.
195− DisposableEffect(sessionId) {
196− container.setCurrentSession(sessionId)
197− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
200− // Navigate away when the session is deleted via SSE so the user isn't left
201− // on a zombie screen showing a conversation that no longer exists. Surface a
202− // toast (not a snackbar) because the screen is about to be popped — a snackbar
203− // would be torn down before the user could read it, while a toast survives.
204− // Covers both SSE-driven deletion (deleted on another device) and a user-
205− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
206− // sets the same flag on success).
207− val deletedContext = LocalContext.current
208− LaunchedEffect(sessionDeleted) {
209− if (sessionDeleted) {
210− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
215− val snackbar = remember { SnackbarHostState() }
216− val retryLabel = stringResource(R.string.retry)
217− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
218− var showModelPicker by rememberSaveable { mutableStateOf(false) }
219− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
220− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
221− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
222− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
223− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
224− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
225− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
226− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
227− var showShellDialog by rememberSaveable { mutableStateOf(false) }
228− var showPalette by rememberSaveable { mutableStateOf(false) }
230− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
231− // action list doesn't need a Composable context. Actions map to the same handlers the
232− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
233− val paletteModelLabel = stringResource(R.string.palette_switch_model)
234− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
235− val paletteCommandLabel = stringResource(R.string.palette_run_command)
236− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
237− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
238− val paletteShellLabel = stringResource(R.string.run_shell_command)
239− val paletteActions = remember(
240− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
241− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
244− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
245− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
246− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
247− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { vm.summarize() })
248− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
249− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
253− // Keep the screen awake while the agent is working in *this* session. The foreground
254− // service that holds process priority during a run is managed app-wide off
255− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
256− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
257− // SSE stream before the completion notification fires.
258− val currentView = LocalView.current
259− val appContext = LocalContext.current.applicationContext
260− DisposableEffect(running) {
261− currentView.keepScreenOn = running
262− onDispose { currentView.keepScreenOn = false }
265− LaunchedEffect(Unit) {
266− vm.errorEvents.collect { event ->
267− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
268− // message-load failure) would silently re-submit the last prompt on tap.
269− val result = if (event.retryable) {
270− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
272− snackbar.showSnackbar(event.message)
274− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
278− // --- Attachments, voice, and share-link plumbing ---
279− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
280− val attachFailedMsg = stringResource(R.string.attachment_failed)
281− val attachLimitMsg = stringResource(R.string.attachment_limit)
282− val noCameraMsg = stringResource(R.string.no_camera_app)
283− val noVoiceMsg = stringResource(R.string.no_voice_app)
284− val voicePrompt = stringResource(R.string.voice_prompt)
285− val linkCopiedMsg = stringResource(R.string.link_copied)
287− // Count of picks currently being read + base64-encoded off the main thread, so the
288− // composer can show a staging placeholder immediately (chips only materialize once done).
289− var stagingCount by remember { mutableStateOf(0) }
291− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
292− // per-prompt count cap and surfacing per-file errors without aborting the batch.
293− fun stageUris(uris: List<Uri>) {
294− if (uris.isEmpty()) return
299− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
300− snackbar.showSnackbar(attachLimitMsg)
303− when (val result = uri.toAttachmentResult(appContext)) {
304− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
305− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
306− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
315− val photoPicker = rememberLauncherForActivityResult(
316− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
317− ) { uris -> stageUris(uris) }
319− val filePicker = rememberLauncherForActivityResult(
320− ActivityResultContracts.GetMultipleContents(),
321− ) { uris -> stageUris(uris) }
323− // Uri survives a config change mid-capture so the TakePicture result still resolves.
324− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
325− val cameraLauncher = rememberLauncherForActivityResult(
326− ActivityResultContracts.TakePicture(),
328− val uri = pendingCaptureUri
329− pendingCaptureUri = null
330− if (success && uri != null) stageUris(listOf(uri))
333− val voiceLauncher = rememberLauncherForActivityResult(
334− ActivityResultContracts.StartActivityForResult(),
336− if (result.resultCode == Activity.RESULT_OK) {
337− val spoken = result.data
338− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
340− ?.takeIf { it.isNotBlank() }
341− if (spoken != null) {
342− // Append to the existing draft rather than replacing, so dictation adds to
343− // whatever the user already typed.
344− val current = vm.draft.value
345− val combined = if (current.isBlank()) spoken else "$current $spoken"
346− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
351− fun launchCamera() {
352− val uri = newCameraCaptureUri(appContext)
354− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
357− pendingCaptureUri = uri
358− runCatching { cameraLauncher.launch(uri) }
359− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
363− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
364− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
365− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
367− runCatching { voiceLauncher.launch(intent) }
368− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
371− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
372− LaunchedEffect(Unit) {
373− vm.shareLinkEvents.collect { url ->
374− copyToClipboard(shareContext, "share", url)
375− snackbar.showSnackbar(linkCopiedMsg)
379− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
380− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
381− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
382− // a dropped branch-navigation event in the gap.
383− val branchedMsg = stringResource(R.string.branch_created)
384− LaunchedEffect(Unit) {
385− vm.branchEvents.collect { newId ->
386− showToast(shareContext, branchedMsg)
387− onOpenSession?.invoke(newId)
391− // Stage images shared into the app (via the system share sheet) as attachments.
392− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
393− // while this ChatScreen is already composed — which happens in two-pane mode, where the
394− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
395− // only fire on first composition. consumePendingSharedMedia() atomically drains the
396− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
397− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
398− LaunchedEffect(pendingSharedMedia) {
399− val shared = container.consumePendingSharedMedia()
400− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
404− if (vm.send(draft)) {
405− // TextHandleMove (a light tick) is semantically right for a send commit;
406− // LongPress is reserved for long-press/swipe gestures.
407− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
411− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
414− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
415− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
416− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
417− // typing (and the composer's own Enter-to-send handling) is untouched.
418− modifier = Modifier.onPreviewKeyEvent { ev ->
419− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
421− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
422− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
423− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
424− showStopConfirm = true; true
432− val changeLabel = stringResource(R.string.change_model_agent)
433− // The subtitle reads "model · agent", so tapping the title offers *both*
434− // — a small menu picks which picker to open. Previously the tap went
435− // straight to the model picker, leaving the agent changeable only via
436− // the overflow menu despite the title implying otherwise.
440− .clickable(enabled = models.isNotEmpty(), role = Role.Button) { showTitleMenu = true }
441− .semantics(mergeDescendants = true) { contentDescription = changeLabel },
442− verticalAlignment = Alignment.CenterVertically,
444− Column(modifier = Modifier.weight(1f, fill = false)) {
445− // maxLines=1 + Ellipsis so a long session title can't wrap and
446− // push the top bar to multiple lines, shifting the whole layout.
448− sessionTitle ?: sessionLabel,
450− overflow = TextOverflow.Ellipsis,
454− style = MaterialTheme.typography.labelSmall,
455− color = MaterialTheme.colorScheme.onSurfaceVariant,
457− overflow = TextOverflow.Ellipsis,
460− // Visual affordance that the title is tappable; without it the
461− // title is indistinguishable from plain text and the pickers are
462− // effectively undiscoverable.
463− if (models.isNotEmpty()) {
465− Icons.Filled.KeyboardArrowDown,
466− contentDescription = null,
467− tint = MaterialTheme.colorScheme.onSurfaceVariant,
468− modifier = Modifier.size(20.dp),
472− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
474− text = { Text(stringResource(R.string.palette_switch_model)) },
475− enabled = !modelsLoading || models.isNotEmpty(),
476− onClick = { showTitleMenu = false; showModelPicker = true },
479− text = { Text(stringResource(R.string.palette_choose_agent)) },
480− enabled = !agentsLoading || agents.isNotEmpty(),
481− onClick = { showTitleMenu = false; showAgentPicker = true },
487− IconButton(onClick = {
488− if (running) showExitConfirm = true else onBack()
490− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
494− // At-a-glance run status in the top bar. When the user is scrolled
495− // up (jump-to-latest FAB visible), the input-bar Stop button and the
496− // trailing "working…" row are off-screen, so a top-bar spinner is the
497− // only signal the agent is still working.
499− val workingLabel = stringResource(R.string.working)
500− CircularProgressIndicator(
501− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
505− // Manual refresh: forces an SSE reconnect, which re-seeds messages
506− // from REST. A recovery path when the stream silently drops and the
507− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
508− // immediate tap feedback — the SSE reconnect may not visibly change
509− // the connection state when already Connected, so without it the tap
510− // appears to do nothing.
511− val refreshLabel = stringResource(R.string.refresh)
513− onClick = { vm.refreshMessages() },
514− enabled = activeConnection != null && !refreshing,
517− CircularProgressIndicator(
518− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
522− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
525− // Overflow menu consolidates the less-frequent actions (share,
526− // commands, agent, model, rename, delete) so the top bar stays
527− // scannable on narrow phones — previously 5 icons crowded the bar
528− // alongside the back button and tappable title. Catalog-loading
529− // spinners stay inline (next to the overflow) so a load state is
530− // visible without opening the menu.
531− val moreLabel = stringResource(R.string.more)
532− val loadingLabel = stringResource(R.string.loading)
533− val shareLabel = stringResource(R.string.share_conversation)
534− val commandsLabel = stringResource(R.string.commands)
535− val agentLabel = stringResource(R.string.choose_agent)
536− val modelLabel = stringResource(R.string.choose_model)
537− val renameLabel = stringResource(R.string.rename_session_chat)
538− val deleteLabel = stringResource(R.string.delete_session_chat)
539− val createShareLabel = stringResource(R.string.create_share_link)
540− val copyShareLabel = stringResource(R.string.copy_share_link)
541− val stopShareLabel = stringResource(R.string.stop_sharing)
542− val summarizeLabel = stringResource(R.string.summarize_conversation)
543− val initLabel = stringResource(R.string.generate_agents_md)
544− val shellLabel = stringResource(R.string.run_shell_command)
546− IconButton(onClick = { showOverflowMenu = true }) {
547− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
550− expanded = showOverflowMenu,
551− onDismissRequest = { showOverflowMenu = false },
554− text = { Text(shareLabel) },
555− enabled = hasMessages,
557− showOverflowMenu = false
559− val md = withContext(Dispatchers.Default) {
560− buildConversationMarkdown(vm.messages.value, sessionTitle)
562− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
563− type = "text/markdown"
564− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
565− putExtra(android.content.Intent.EXTRA_TEXT, md)
567− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
568− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
573− text = { Text(commandsLabel) },
574− enabled = !commandsLoading || commands.isNotEmpty(),
575− onClick = { showOverflowMenu = false; showCommandPicker = true },
578− text = { Text(agentLabel) },
579− enabled = !agentsLoading || agents.isNotEmpty(),
580− onClick = { showOverflowMenu = false; showAgentPicker = true },
583− text = { Text(modelLabel) },
584− enabled = !modelsLoading || models.isNotEmpty(),
585− onClick = { showOverflowMenu = false; showModelPicker = true },
587− androidx.compose.material3.HorizontalDivider()
588− // Session sharing: create a public link, copy an existing one, or revoke it.
589− if (shareUrl == null) {
591− text = { Text(createShareLabel) },
592− enabled = hasMessages,
593− onClick = { showOverflowMenu = false; vm.shareSession() },
597− text = { Text(copyShareLabel) },
599− showOverflowMenu = false
601− copyToClipboard(shareContext, "share", it)
602− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
607− text = { Text(stopShareLabel) },
608− onClick = { showOverflowMenu = false; vm.unshareSession() },
612− text = { Text(summarizeLabel) },
613− enabled = hasMessages && !running,
614− onClick = { showOverflowMenu = false; vm.summarize() },
617− text = { Text(initLabel) },
619− onClick = { showOverflowMenu = false; vm.initProject() },
622− text = { Text(shellLabel) },
624− onClick = { showOverflowMenu = false; showShellDialog = true },
626− androidx.compose.material3.HorizontalDivider()
628− text = { Text(renameLabel) },
629− onClick = { showOverflowMenu = false; showRenameDialog = true },
632− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
633− onClick = { showOverflowMenu = false; showDeleteDialog = true },
636− // While a catalog is initially loading (empty list + loading flag),
637− // show a tiny inline spinner beside the overflow so the user can see
638− // a load is in progress without opening the menu. Once loaded the
639− // spinner disappears; the menu items are always enabled (tapping a
640− // picker with no items shows the "no models/agents/commands" state).
641− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
642− (agentsLoading && agents.isEmpty()) ||
643− (modelsLoading && models.isEmpty())
644− if (catalogLoading) {
645− CircularProgressIndicator(
647− .align(Alignment.TopEnd)
649− .semantics { contentDescription = loadingLabel },
657− snackbarHost = { SnackbarHost(snackbar) },
659− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
660− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
661− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
662− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
664− // Pinned above the composer so the agent's plan and progress stay visible
665− // while scrolled up mid-run; renders nothing when there's no plan.
666− TodoPlanBar(todoPlan)
667− AnimatedVisibility(visible = reverted) {
668− RevertBanner(onUndo = { vm.unrevert() })
670− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
672− count = queuedOffline.size,
673− sending = outboxSending,
674− onFlush = { vm.flushQueued() },
675− onDiscard = { vm.discardAllQueued() },
680− onValueChange = vm::updateDraft,
682− aborting = aborting,
683− enabled = activeConnection != null,
684− sendOnEnter = sendOnEnter,
686− onAbort = { showStopConfirm = true },
687− queuedFollowUp = queuedFollowUp,
688− onQueueFollowUp = vm::queueFollowUp,
689− onCancelQueue = { vm.queueFollowUp("") },
690− focusRequester = inputFocusRequester,
691− attachments = attachments,
692− staging = stagingCount > 0,
693− onRemoveAttachment = vm::removeAttachment,
696− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
699− onPickFile = { filePicker.launch("*/*") },
700− onCamera = { launchCamera() },
701− onVoice = { launchVoice() },
706− // Collect messages inside the content lambda so streaming token updates
707− // recompose only this subtree, not the top bar / input bar / 20+ other
708− // state reads in the ChatScreen body.
709− val messages by vm.messages.collectAsStateWithLifecycle()
710− val listState = rememberLazyListState()
711− val contentScope = rememberCoroutineScope()
712− val timeTick = rememberRelativeTimeTick()
713− // Group messages by day and interleave date separators so a long conversation
714− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
715− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
716− // outside the PullToRefreshBox so the auto-scroll effects below can reference
717− // the same list the LazyColumn renders (separators shift the indices vs. the
718− // raw messages list, so scroll targets must be in listItems space).
719− val todayLabel = stringResource(R.string.today)
720− val yesterdayLabel = stringResource(R.string.yesterday)
721− val listItems = remember(messages, todayLabel, yesterdayLabel) {
722− buildMessageListItems(messages, todayLabel, yesterdayLabel)
724− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
725− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
726− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
727− // would capture the first composition's list — which is empty, since `messages`
728− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
729− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
730− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
731− // whose value tracks the latest list.
732− val currentListItems by rememberUpdatedState(listItems)
734− // New-content signal for the jump-to-latest FAB: set when content grows while the user
735− // is scrolled away from the bottom, cleared once they return (see the collector below).
736− var hasNewContent by remember { mutableStateOf(false) }
738− val isPinnedToBottom by remember {
740− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
741− // When a run is active, the LazyColumn has one trailing "__typing"
742− // item after the last list item. Account for it so "pinned to bottom"
743− // includes the working indicator — otherwise the pin check targets
744− // listItems.lastIndex, the typing row sits just below the viewport,
745− // and the user never sees the progress indicator even when pinned.
746− val items = currentListItems
747− val effectiveLast = if (running) items.size else items.lastIndex
748− lastVisible >= effectiveLast || items.isEmpty()
752− // Jump to the newest message once, when the conversation first loads. Guarded by a
753− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
754− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
755− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
756− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
757− LaunchedEffect(listItems.isNotEmpty()) {
758− if (listItems.isNotEmpty() && !didInitialScroll) {
759− // When a run is active the LazyColumn has a trailing "__typing" row at
760− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
761− // running session lands truly pinned to bottom and streaming auto-scroll engages.
762− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
763− didInitialScroll = true
767− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
768− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
769− // isPinnedToBottom check flips to false the instant you send — freezing
770− // auto-scroll. If the user was pinned to the last item just before the run
771− // began, bring the typing row into view so the pin (and streaming follow) is
772− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
773− // recomputed to false by now) so we don't scroll when the user had scrolled up.
774− LaunchedEffect(running) {
775− if (running && listItems.isNotEmpty()) {
776− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
777− if (lastVisible >= listItems.lastIndex) {
778− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
783− LaunchedEffect(Unit) {
787− // Track list size + the streaming length of the last part so we auto-scroll
788− // as content arrives, plus the pinned flag. A small data class with primitive
789− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
790− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
791− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
792− // and tool output — not just TextPart — keeps a pinned view following a long
793− // reasoning/tool block while it streams (previously it stalled at 0).
794− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
795− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
796− }.collect { signal ->
797− if (signal.pinned) {
798− // Back at the bottom: clear the new-content badge.
799− hasNewContent = false
800− if (signal.size > 0) {
801− // Scroll to the effective last index, including the trailing
802− // "__typing" row when a run is active so the working indicator
803− // is brought into view (not just the last message).
804− val items = currentListItems
805− val target = if (running) items.size else items.lastIndex
806− listState.scrollToItem(target)
808− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
809− // Content arrived while scrolled up — badge the jump-to-latest FAB.
810− hasNewContent = true
812− prevSize = signal.size
813− prevLen = signal.lastTextLength
817− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
818− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
819− // content padding accounts for the bottomBar's raised height, so the message
820− // list is already above the keyboard. Adding imePadding here would double-apply
821− // the IME inset and push messages too far up.
822− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
823− if (activeConnection == null) {
825− modifier = Modifier.align(Alignment.Center).padding(24.dp),
826− horizontalAlignment = Alignment.CenterHorizontally,
829− stringResource(R.string.not_connected),
830− color = MaterialTheme.colorScheme.error,
832− Spacer(Modifier.size(12.dp))
833− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
835− CircularProgressIndicator(
836− Modifier.size(20.dp),
837− color = MaterialTheme.colorScheme.onPrimary,
841− Text(stringResource(R.string.reconnect))
847− state = connectionState,
848− modifier = Modifier.align(Alignment.TopCenter),
849− isOnline = isOnline,
850− // On a hard failure, retry by forcing an SSE reconnect (which
851− // re-seeds from REST). refreshMessages is the right recovery path
852− // when the connection is present but the stream died; reconnect()
853− // is the path when the whole connection is gone (handled by the
854− // separate "Not connected" state below).
855− onRetry = { vm.refreshMessages() },
857− if (loading && messages.isEmpty()) {
858− val loadingLabel = stringResource(R.string.loading)
859− CircularProgressIndicator(
861− .align(Alignment.Center)
862− .semantics { contentDescription = loadingLabel },
864− } else if (loadError && messages.isEmpty()) {
865− // A failed load with nothing to show. Distinct from the empty
866− // conversation state below — the conversation isn't empty, it
867− // failed to load, and offering "Start a conversation" here is
868− // misleading. Offer a Retry instead, mirroring SessionListScreen.
870− modifier = Modifier.align(Alignment.Center).padding(24.dp),
871− horizontalAlignment = Alignment.CenterHorizontally,
874− stringResource(R.string.load_messages_failed),
875− color = MaterialTheme.colorScheme.error,
877− Spacer(Modifier.size(12.dp))
878− Button(onClick = { vm.refreshMessages() }) {
879− Text(stringResource(R.string.retry))
882− } else if (messages.isEmpty() && running) {
883− // A run just started but no parts have arrived yet — the empty
884− // list with only the trailing "working…" row looks broken, so
885− // surface a clear starting state until the first part streams in.
886− val workingText = stringResource(R.string.working)
888− modifier = Modifier.align(Alignment.Center).padding(24.dp),
889− horizontalAlignment = Alignment.CenterHorizontally,
891− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
892− Spacer(Modifier.size(12.dp))
893− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
895− } else if (messages.isEmpty()) {
899− // Focus the input so the user can edit the suggestion before
900− // sending, instead of having to manually tap the field.
901− runCatching { inputFocusRequester.requestFocus() }
903− modifier = Modifier.align(Alignment.Center),
906− // Pull-to-refresh wraps the message list so the user can force an SSE
907− // reconnect + re-seed with the same gesture they use on the session and
908− // file lists, instead of hunting for the top-bar refresh icon. The empty
909− // / loading / error states above stay outside the PTR box since there's
910− // no list content to pull against.
912− isRefreshing = refreshing,
913− onRefresh = { vm.refreshMessages() },
914− modifier = Modifier.fillMaxSize(),
916− val lastMessageId = messages.lastOrNull()?.info?.id
917− // Text-to-speech for reading assistant replies aloud; shuts down when the
918− // message list leaves composition.
919− val tts = rememberTtsController()
920− val speakingMessageId by tts.speakingId
923− modifier = Modifier.fillMaxSize(),
924− // Extra bottom padding reserves room for the jump-to-latest FAB so it
925− // never floats over the last message.
926− contentPadding = PaddingValues(
930− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
932− verticalArrangement = Arrangement.spacedBy(16.dp),
937− contentType = { it.contentType },
940− is MessageListItem.Separator -> DateSeparator(item.label)
941− is MessageListItem.Message -> {
942− val message = item.message
943− // Only the last (streaming) message needs isRunning — it drives the
944− // reasoning-block spinner. Passing the live flag to every bubble
945− // makes all visible messages recompose whenever a run starts or stops.
946− val modelLabel = remember(message.info, models) {
947− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
948− ?.let { resolveModelLabel(it, models) }
952− isRunning = running && message.info.id == lastMessageId,
953− imageContext = imageContext,
954− modelLabel = modelLabel,
955− onOpenFile = onOpenFile,
956− onRevert = { vm.revertTo(message.info.id) },
958− // editMessage reverts to before this message (hiding it and
959− // everything after); the revert banner surfaces the rewind
960− // with an Undo. Focus + scroll the composer into view like the
961− // Quote action so the prefilled draft isn't off-screen.
962− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
963− vm.editMessage(message.info.id, text)
964− runCatching { inputFocusRequester.requestFocus() }
965− contentScope.launch {
966− runCatchingCancellable {
967− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
971− onSpeak = { text -> tts.toggle(message.info.id, text) },
972− isSpeaking = message.info.id == speakingMessageId,
975− runCatching { inputFocusRequester.requestFocus() }
977− onBranch = { text -> vm.branchFrom(text) },
983− item(key = "__typing") {
984− val workingText = stringResource(R.string.working)
986− verticalAlignment = Alignment.CenterVertically,
987− modifier = Modifier.semantics {
988− contentDescription = workingText
991− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
992− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
998− // Jump-to-latest affordance when the user has scrolled away during a stream.
1000− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1001− modifier = Modifier.align(Alignment.BottomEnd),
1003− // Badge the FAB when new content arrived while the user was scrolled up, so
1004− // they know there's something new to jump to (cleared once back at bottom).
1007− if (hasNewContent) {
1008− val newContentLabel = stringResource(R.string.new_messages)
1009− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1012− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1014− ExtendedFloatingActionButton(
1016− hasNewContent = false
1017− if (listItems.isNotEmpty()) {
1018− // Scroll to the effective last index, including the
1019− // trailing "__typing" row when a run is active.
1020− val target = if (running) listItems.size else listItems.lastIndex
1021− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1024− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(R.string.latest)) },
1025− text = { Text(stringResource(R.string.latest)) },
1035− if (showExitConfirm) {
1037− onDismissRequest = { showExitConfirm = false },
1038− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1039− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1041− TextButton(onClick = {
1042− showExitConfirm = false
1043− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1046− }) { Text(stringResource(R.string.stop_and_exit)) }
1049− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1054− if (showStopConfirm) {
1056− onDismissRequest = { showStopConfirm = false },
1057− title = { Text(stringResource(R.string.stop_run_title)) },
1058− text = { Text(stringResource(R.string.stop_run_text)) },
1060− TextButton(onClick = {
1061− showStopConfirm = false
1062− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1064− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1067− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1072− if (showRenameDialog) {
1073− RenameSessionChatDialog(
1074− initialTitle = sessionTitle ?: "",
1075− onDismiss = { showRenameDialog = false },
1076− onConfirm = { newName ->
1077− showRenameDialog = false
1078− vm.renameSession(newName)
1083− if (showDeleteDialog) {
1085− onDismissRequest = { showDeleteDialog = false },
1086− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1087− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1089− TextButton(onClick = {
1090− showDeleteDialog = false
1091− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1093− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1096− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1101− if (showShellDialog) {
1102− ShellCommandDialog(
1103− onDismiss = { showShellDialog = false },
1105− showShellDialog = false
1111− if (showModelPicker) {
1114− selected = selectedModel,
1115− loading = modelsLoading,
1116− error = modelsError,
1117− onSelect = { vm.selectModel(it) },
1118− onRetry = { vm.reloadModels() },
1119− onDismiss = { showModelPicker = false },
1123− if (showAgentPicker) {
1126− selected = selectedAgent,
1127− loading = agentsLoading,
1128− error = agentsError,
1129− onSelect = { vm.selectAgent(it?.name) },
1130− onRetry = { vm.reloadAgents() },
1131− onDismiss = { showAgentPicker = false },
1135− if (showCommandPicker) {
1136− CommandPickerSheet(
1137− commands = commands,
1138− loading = commandsLoading,
1139− error = commandsError,
1140− onSelect = { vm.runCommand(it) },
1141− onRetry = { vm.reloadCommands() },
1142− onDismiss = { showCommandPicker = false },
1146− pendingPermission?.let { permission ->
1148− permission = permission,
1149− onRespond = { response -> vm.respondPermission(permission, response) },
1154− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1159−private fun ChatInputBar(
1161− onValueChange: (String) -> Unit,
1165− sendOnEnter: Boolean,
1166− onSend: () -> Unit,
1167− onAbort: () -> Unit,
1168− queuedFollowUp: String?,
1169− onQueueFollowUp: (String) -> Unit,
1170− onCancelQueue: () -> Unit,
1171− focusRequester: androidx.compose.ui.focus.FocusRequester,
1172− attachments: List<PendingAttachment>,
1174− onRemoveAttachment: (String) -> Unit,
1175− onPickPhoto: () -> Unit,
1176− onPickFile: () -> Unit,
1177− onCamera: () -> Unit,
1178− onVoice: () -> Unit,
1180− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1181− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1182− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1183− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1184− // A queued follow-up replaces the Stop button with a "queued" chip so the
1185− // user sees their message will be sent when the run finishes, and can cancel.
1186− if (queuedFollowUp != null) {
1188− modifier = Modifier
1190− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1191− verticalAlignment = Alignment.CenterVertically,
1193− Column(modifier = Modifier.weight(1f)) {
1195− stringResource(R.string.queued),
1196− style = MaterialTheme.typography.labelSmall,
1197− color = MaterialTheme.colorScheme.onSurfaceVariant,
1201− style = MaterialTheme.typography.bodySmall,
1202− color = MaterialTheme.colorScheme.onSurfaceVariant,
1204− overflow = TextOverflow.Ellipsis,
1207− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1208− Text(stringResource(R.string.cancel))
1212− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1213− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1215− modifier = Modifier.fillMaxWidth().padding(8.dp),
1216− verticalAlignment = Alignment.Bottom,
1218− // Attach menu: photo picker, camera, or any file.
1219− var showAttachMenu by remember { mutableStateOf(false) }
1221− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1222− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1224− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1226− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1227− text = { Text(stringResource(R.string.attach_photo)) },
1228− onClick = { showAttachMenu = false; onPickPhoto() },
1231− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1232− text = { Text(stringResource(R.string.attach_camera)) },
1233− onClick = { showAttachMenu = false; onCamera() },
1236− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1237− text = { Text(stringResource(R.string.attach_file)) },
1238− onClick = { showAttachMenu = false; onPickFile() },
1242− // Voice dictation: appends recognized speech to the draft.
1243− IconButton(onClick = onVoice, enabled = enabled) {
1244− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1248− onValueChange = { v ->
1249− // Cap input length so a huge paste can't stall the UI. Shares are
1250− // capped separately in MainActivity; this guards typed/pasted drafts.
1251− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1253− modifier = Modifier
1255− .focusRequester(focusRequester)
1256− .testTag("chat_input")
1257− .onPreviewKeyEvent { event ->
1258− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1259− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1260− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1261− val send = enterShouldSend(
1263− hasContent = hasContent,
1264− sendOnEnter = sendOnEnter,
1265− shift = event.isShiftPressed,
1266− ctrl = event.isCtrlPressed,
1269− if (running) onQueueFollowUp(value) else onSend()
1275− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1278− // Show a "N / max" countdown once the draft crosses a high fraction of
1279− // the cap, so the user knows a paste is about to be truncated instead
1280− // of being silently cut off. Hidden for normal short prompts to avoid
1281− // clutter under a typical one-line message.
1283− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1284− if (value.length >= threshold) {
1287− R.string.draft_chars_remaining,
1288− NetworkConfig.maxDraftLengthChars - value.length,
1289− NetworkConfig.maxDraftLengthChars,
1291− style = MaterialTheme.typography.labelSmall,
1292− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1293− else MaterialTheme.colorScheme.onSurfaceVariant,
1297− keyboardOptions = KeyboardOptions(
1298− // With send-on-Enter off, expose the platform default action so the soft
1299− // keyboard shows a newline key (this is a multi-line field) instead of a
1300− // Send action — otherwise the setting has no effect on soft keyboards and
1301− // there's no way to type a newline. Hardware Enter is handled separately.
1302− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1303− capitalization = KeyboardCapitalization.Sentences,
1305− keyboardActions = KeyboardActions(onSend = {
1307− // During a run the Send IME action queues a follow-up, but only when
1308− // there's typed text — queuing "" would cancel an existing queued
1309− // follow-up (see the Queue button gate). When not running, an
1310− // attachment-only send is valid, so gate that path on hasContent.
1312− if (value.isNotBlank()) onQueueFollowUp(value)
1313− } else if (hasContent) {
1319− ComposerTrailingButton(
1321− aborting = aborting,
1322− canSend = enabled && hasContent,
1323− canQueue = enabled && value.isNotBlank(),
1326− onQueue = { onQueueFollowUp(value) },
1333−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1334− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1335−private fun enterShouldSend(
1337− hasContent: Boolean,
1338− sendOnEnter: Boolean,
1342− !enabled || !hasContent -> false
1343− sendOnEnter -> !shift
1347−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1348− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1349− * [ChatInputBar] stays under the complexity threshold. */
1351−private fun ComposerTrailingButton(
1356− onSend: () -> Unit,
1357− onAbort: () -> Unit,
1358− onQueue: () -> Unit,
1361− Row(verticalAlignment = Alignment.CenterVertically) {
1362− // While a run is active the trailing action is Stop, so the only send affordance is
1363− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1364− // That leaves a touch-only user with the setting off no way to queue a follow-up
1365− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1366− // there's typed TEXT so queuing is always reachable, without changing the user's
1367− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1368− // canSend, which is also true for an attachment-only composer — because queuing "" just
1369− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1370− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1374− modifier = Modifier.testTag("queue_button"),
1377− Icons.AutoMirrored.Filled.Send,
1378− contentDescription = stringResource(R.string.queue_followup),
1382− // Show a spinner while the abort REST call is in flight so the user sees the stop
1383− // was sent, and disable to prevent a double-tap.
1386− enabled = !aborting,
1387− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1390− val stopLabel = stringResource(R.string.stop)
1391− CircularProgressIndicator(
1392− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1393− strokeWidth = 2.dp,
1396− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1404− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1406− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1411−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1413−private fun EmptyConversation(
1414− onSuggestion: (String) -> Unit,
1415− modifier: Modifier = Modifier,
1417− // A few example prompts so a first-time user has a one-tap path to their first
1418− // message instead of staring at a blank input. Tapping a chip fills the draft
1419− // (without sending) so the user can edit it before sending.
1420− val suggestions = remember {
1422− R.string.empty_chat_suggest_1,
1423− R.string.empty_chat_suggest_2,
1424− R.string.empty_chat_suggest_3,
1428− modifier = modifier.padding(32.dp),
1429− horizontalAlignment = Alignment.CenterHorizontally,
1432− Icons.Filled.AutoAwesome,
1433− contentDescription = null,
1434− modifier = Modifier.size(48.dp),
1435− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1437− Spacer(Modifier.size(16.dp))
1439− stringResource(R.string.empty_chat_title),
1440− style = MaterialTheme.typography.titleMedium,
1442− Spacer(Modifier.size(8.dp))
1444− stringResource(R.string.empty_chat_hint),
1445− style = MaterialTheme.typography.bodyMedium,
1446− color = MaterialTheme.colorScheme.onSurfaceVariant,
1448− Spacer(Modifier.size(20.dp))
1449− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1450− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1452− modifier = Modifier.fillMaxWidth(),
1453− horizontalArrangement = Arrangement.spacedBy(8.dp),
1454− verticalArrangement = Arrangement.spacedBy(8.dp),
1456− suggestions.forEach { resId ->
1457− val text = stringResource(resId)
1458− androidx.compose.material3.AssistChip(
1459− onClick = { onSuggestion(text) },
1460− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1467−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1469−private fun RevertBanner(onUndo: () -> Unit) {
1471− color = MaterialTheme.colorScheme.tertiaryContainer,
1472− tonalElevation = 2.dp,
1473− modifier = Modifier.fillMaxWidth(),
1476− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1477− verticalAlignment = Alignment.CenterVertically,
1478− horizontalArrangement = Arrangement.SpaceBetween,
1480− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1482− Icons.Filled.Restore,
1483− contentDescription = null,
1484− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1485− modifier = Modifier.size(18.dp),
1488− stringResource(R.string.reverted_banner),
1489− style = MaterialTheme.typography.bodySmall,
1490− color = MaterialTheme.colorScheme.onTertiaryContainer,
1491− modifier = Modifier.padding(start = 8.dp),
1494− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1499−/** A banner shown while messages composed offline are queued in the outbox, with a
1500− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1502−private fun OutboxBanner(
1505− onFlush: () -> Unit,
1506− onDiscard: () -> Unit,
1509− color = MaterialTheme.colorScheme.secondaryContainer,
1510− tonalElevation = 2.dp,
1511− modifier = Modifier.fillMaxWidth(),
1514− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1515− verticalAlignment = Alignment.CenterVertically,
1516− horizontalArrangement = Arrangement.SpaceBetween,
1518− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1520− CircularProgressIndicator(
1521− Modifier.size(16.dp),
1522− strokeWidth = 2.dp,
1523− color = MaterialTheme.colorScheme.onSecondaryContainer,
1525− Spacer(Modifier.size(8.dp))
1529− stringResource(R.string.outbox_sending)
1531− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1532− stringResource(res, count)
1534− style = MaterialTheme.typography.bodySmall,
1535− color = MaterialTheme.colorScheme.onSecondaryContainer,
1539− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1540− TextButton(onClick = onDiscard) {
1541− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1548−/** Prompt for a one-off shell command to run in the session's worktree. */
1550−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1551− var command by rememberSaveable { mutableStateOf("") }
1553− onDismissRequest = onDismiss,
1554− title = { Text(stringResource(R.string.run_shell_command)) },
1558− onValueChange = { command = it },
1559− modifier = Modifier.fillMaxWidth(),
1560− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1561− label = { Text(stringResource(R.string.shell_command_label)) },
1563− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1564− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1569− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1570− enabled = command.isNotBlank(),
1571− ) { Text(stringResource(R.string.run)) }
1573− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1578− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1579− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1580− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1582−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1584−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1585− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1586− * streaming, not just plain assistant text. O(1). */
1587−private fun streamingContentLength(part: Part?): Int = when (part) {
1588− is TextPart -> part.text.length
1589− is ReasoningPart -> part.text.length
1590− is ToolPart -> when (val st = part.state) {
1591− is ToolCompleted -> st.output?.length ?: 0
1592− is ToolError -> st.error?.length ?: 0
1593− is ToolRunning -> st.title?.length ?: 0
1599−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1600− * dialog but lives in the chat screen so the user can rename without backing out to
1601− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1603−private fun RenameSessionChatDialog(
1604− initialTitle: String,
1605− onDismiss: () -> Unit,
1606− onConfirm: (String) -> Unit,
1608− // Seed the field once (no key input) so a later external title change — e.g. opencode
1609− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1610− // doesn't re-initialize the box and discard the user's in-progress edit.
1611− var title by rememberSaveable { mutableStateOf(initialTitle) }
1613− onDismissRequest = onDismiss,
1614− title = { Text(stringResource(R.string.rename_session_chat)) },
1618− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1619− modifier = Modifier.fillMaxWidth(),
1620− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1621− label = { Text(stringResource(R.string.rename_session_chat)) },
1623− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1624− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1628− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1629− Text(stringResource(R.string.save))
1633− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1639− * A single item in the chat message list — either a [Message] bubble or a day
1640− * [Separator] inserted before the first message of a new day. The separator shifts
1641− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1642− * the [List] of these items (not `messages.size`/`lastIndex`).
1644−private sealed interface MessageListItem {
1646− val contentType: Any
1648− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1649− override val contentType: Any get() = message.info::class
1652− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1653− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1654− // can share a label (e.g. an untimestamped message — empty label — between two
1655− // same-day messages, or two untimestamped groups), and a label-only key would
1656− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1657− // stable for a given message ordering so slots aren't needlessly recreated.
1658− override val key: Any get() = "sep_${ordinal}_$label"
1659− // Separators share a contentType so the LazyColumn can recycle their slots.
1660− override val contentType: Any get() = "separator"
1665− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1666− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1667− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1668− * Messages with no timestamp are grouped under an empty-label separator only if they
1669− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1671− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1672− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1673− * labels; older days fall back to a locale-stable medium-date format.
1675−private fun buildMessageListItems(
1676− messages: List<MessageWithParts>,
1677− todayLabel: String,
1678− yesterdayLabel: String,
1679−): List<MessageListItem> {
1680− if (messages.isEmpty()) return emptyList()
1681− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1682− val dateFmt = mediumDateFormat()
1683− val result = ArrayList<MessageListItem>(messages.size + 4)
1684− val seenKeys = HashSet<String>(messages.size * 2)
1685− var lastDayKey: String? = null
1687− var emptyIdOrdinal = 0
1689− for (message in messages) {
1690− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1691− val dayKey = ts?.let { dayKey(it) } ?: ""
1692− // Emit a separator before the very first message (so a leading un-timestamped message
1693− // still gets the first divider, empty label and all), and thereafter only when crossing
1694− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1695− // neither emits its own separator nor resets the day — otherwise a following same-day
1696− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1697− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1698− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1700− if (dayKey.isNotEmpty()) lastDayKey = dayKey
1702− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1703− // empty id — and the reducer intentionally keeps several such messages as distinct
1704− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1705− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1706− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1707− if (!seenKeys.add(key)) {
1709− while (!seenKeys.add("$key#$suffix")) suffix++
1710− key = "$key#$suffix"
1712− result.add(MessageListItem.Message(message, key))
1718− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1720− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1721− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1722− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1723− * every message on every token. Message timestamps are immutable once assigned, so we
1724− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1725− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1726− * thread during composition, so the coarse lock is uncontended.
1728−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1729− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1732−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1733− dayKeyCache.getOrPut(epochMillis) {
1734− java.time.Instant.ofEpochMilli(epochMillis)
1735− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1739−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1740−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1741−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1742−private var cachedDateFmt: java.text.DateFormat? = null
1743−private var cachedDateFmtLocale: java.util.Locale? = null
1745−private fun mediumDateFormat(): java.text.DateFormat {
1746− val locale = java.util.Locale.getDefault()
1747− val existing = cachedDateFmt
1748− if (existing != null && cachedDateFmtLocale == locale) return existing
1749− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1751− cachedDateFmtLocale = locale
1756− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1757− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1758− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1761−private fun dayLabel(
1764− today: java.time.LocalDate,
1765− todayLabel: String,
1766− yesterdayLabel: String,
1767− dateFmt: java.text.DateFormat,
1769− if (dayKey.isEmpty()) return ""
1770− val epochDay = dayKey.toLongOrNull() ?: return ""
1771− val date = java.time.LocalDate.ofEpochDay(epochDay)
1773− date == today -> todayLabel
1774− date == today.minusDays(1) -> yesterdayLabel
1775− else -> dateFmt.format(java.util.Date(ts))
1780− * A centered day divider in the message list. Renders nothing for an empty label
1781− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1784−private fun DateSeparator(label: String) {
1785− if (label.isBlank()) return
1787− modifier = Modifier.fillMaxWidth(),
1788− horizontalArrangement = Arrangement.Center,
1791− color = MaterialTheme.colorScheme.surfaceVariant,
1792− shape = MaterialTheme.shapes.small,
1796− style = MaterialTheme.typography.labelSmall,
1797− color = MaterialTheme.colorScheme.onSurfaceVariant,
1798− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),