@@ -1,1783 +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 showCommandPicker by rememberSaveable { mutableStateOf(false) }
221− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
222− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
223− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
224− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
225− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
226− var showShellDialog by rememberSaveable { mutableStateOf(false) }
227− var showPalette by rememberSaveable { mutableStateOf(false) }
229− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
230− // action list doesn't need a Composable context. Actions map to the same handlers the
231− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
232− val paletteModelLabel = stringResource(R.string.palette_switch_model)
233− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
234− val paletteCommandLabel = stringResource(R.string.palette_run_command)
235− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
236− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
237− val paletteShellLabel = stringResource(R.string.run_shell_command)
238− val paletteActions = remember(
239− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
240− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
243− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
244− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
245− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
246− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { vm.summarize() })
247− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
248− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
252− // Keep the screen awake while the agent is working in *this* session. The foreground
253− // service that holds process priority during a run is managed app-wide off
254− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
255− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
256− // SSE stream before the completion notification fires.
257− val currentView = LocalView.current
258− val appContext = LocalContext.current.applicationContext
259− DisposableEffect(running) {
260− currentView.keepScreenOn = running
261− onDispose { currentView.keepScreenOn = false }
264− LaunchedEffect(Unit) {
265− vm.errorEvents.collect { event ->
266− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
267− // message-load failure) would silently re-submit the last prompt on tap.
268− val result = if (event.retryable) {
269− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
271− snackbar.showSnackbar(event.message)
273− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
277− // --- Attachments, voice, and share-link plumbing ---
278− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
279− val attachFailedMsg = stringResource(R.string.attachment_failed)
280− val attachLimitMsg = stringResource(R.string.attachment_limit)
281− val noCameraMsg = stringResource(R.string.no_camera_app)
282− val noVoiceMsg = stringResource(R.string.no_voice_app)
283− val voicePrompt = stringResource(R.string.voice_prompt)
284− val linkCopiedMsg = stringResource(R.string.link_copied)
286− // Count of picks currently being read + base64-encoded off the main thread, so the
287− // composer can show a staging placeholder immediately (chips only materialize once done).
288− var stagingCount by remember { mutableStateOf(0) }
290− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
291− // per-prompt count cap and surfacing per-file errors without aborting the batch.
292− fun stageUris(uris: List<Uri>) {
293− if (uris.isEmpty()) return
298− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
299− snackbar.showSnackbar(attachLimitMsg)
302− when (val result = uri.toAttachmentResult(appContext)) {
303− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
304− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
305− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
314− val photoPicker = rememberLauncherForActivityResult(
315− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
316− ) { uris -> stageUris(uris) }
318− val filePicker = rememberLauncherForActivityResult(
319− ActivityResultContracts.GetMultipleContents(),
320− ) { uris -> stageUris(uris) }
322− // Uri survives a config change mid-capture so the TakePicture result still resolves.
323− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
324− val cameraLauncher = rememberLauncherForActivityResult(
325− ActivityResultContracts.TakePicture(),
327− val uri = pendingCaptureUri
328− pendingCaptureUri = null
329− if (success && uri != null) stageUris(listOf(uri))
332− val voiceLauncher = rememberLauncherForActivityResult(
333− ActivityResultContracts.StartActivityForResult(),
335− if (result.resultCode == Activity.RESULT_OK) {
336− val spoken = result.data
337− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
339− ?.takeIf { it.isNotBlank() }
340− if (spoken != null) {
341− // Append to the existing draft rather than replacing, so dictation adds to
342− // whatever the user already typed.
343− val current = vm.draft.value
344− val combined = if (current.isBlank()) spoken else "$current $spoken"
345− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
350− fun launchCamera() {
351− val uri = newCameraCaptureUri(appContext)
353− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
356− pendingCaptureUri = uri
357− runCatching { cameraLauncher.launch(uri) }
358− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
362− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
363− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
364− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
366− runCatching { voiceLauncher.launch(intent) }
367− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
370− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
371− LaunchedEffect(Unit) {
372− vm.shareLinkEvents.collect { url ->
373− copyToClipboard(shareContext, "share", url)
374− snackbar.showSnackbar(linkCopiedMsg)
378− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
379− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
380− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
381− // a dropped branch-navigation event in the gap.
382− val branchedMsg = stringResource(R.string.branch_created)
383− LaunchedEffect(Unit) {
384− vm.branchEvents.collect { newId ->
385− showToast(shareContext, branchedMsg)
386− onOpenSession?.invoke(newId)
390− // Stage images shared into the app (via the system share sheet) as attachments.
391− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
392− // while this ChatScreen is already composed — which happens in two-pane mode, where the
393− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
394− // only fire on first composition. consumePendingSharedMedia() atomically drains the
395− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
396− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
397− LaunchedEffect(pendingSharedMedia) {
398− val shared = container.consumePendingSharedMedia()
399− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
403− if (vm.send(draft)) {
404− // TextHandleMove (a light tick) is semantically right for a send commit;
405− // LongPress is reserved for long-press/swipe gestures.
406− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
410− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
413− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
414− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
415− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
416− // typing (and the composer's own Enter-to-send handling) is untouched.
417− modifier = Modifier.onPreviewKeyEvent { ev ->
418− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
420− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
421− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
422− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
423− showStopConfirm = true; true
431− val changeLabel = stringResource(R.string.change_model_agent)
434− .clickable(enabled = models.isNotEmpty(), role = Role.Button) { showModelPicker = true }
435− .semantics(mergeDescendants = true) { contentDescription = changeLabel },
436− verticalAlignment = Alignment.CenterVertically,
438− Column(modifier = Modifier.weight(1f, fill = false)) {
439− // maxLines=1 + Ellipsis so a long session title can't wrap and
440− // push the top bar to multiple lines, shifting the whole layout.
442− sessionTitle ?: sessionLabel,
444− overflow = TextOverflow.Ellipsis,
448− style = MaterialTheme.typography.labelSmall,
449− color = MaterialTheme.colorScheme.onSurfaceVariant,
451− overflow = TextOverflow.Ellipsis,
454− // Visual affordance that the title opens the model picker;
455− // without it the tappable title is indistinguishable from plain
456− // text and the picker is effectively undiscoverable.
457− if (models.isNotEmpty()) {
459− Icons.Filled.KeyboardArrowDown,
460− contentDescription = null,
461− tint = MaterialTheme.colorScheme.onSurfaceVariant,
462− modifier = Modifier.size(20.dp),
468− IconButton(onClick = {
469− if (running) showExitConfirm = true else onBack()
471− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
475− // At-a-glance run status in the top bar. When the user is scrolled
476− // up (jump-to-latest FAB visible), the input-bar Stop button and the
477− // trailing "working…" row are off-screen, so a top-bar spinner is the
478− // only signal the agent is still working.
480− val workingLabel = stringResource(R.string.working)
481− CircularProgressIndicator(
482− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
486− // Manual refresh: forces an SSE reconnect, which re-seeds messages
487− // from REST. A recovery path when the stream silently drops and the
488− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
489− // immediate tap feedback — the SSE reconnect may not visibly change
490− // the connection state when already Connected, so without it the tap
491− // appears to do nothing.
492− val refreshLabel = stringResource(R.string.refresh)
494− onClick = { vm.refreshMessages() },
495− enabled = activeConnection != null && !refreshing,
498− CircularProgressIndicator(
499− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
503− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
506− // Overflow menu consolidates the less-frequent actions (share,
507− // commands, agent, model, rename, delete) so the top bar stays
508− // scannable on narrow phones — previously 5 icons crowded the bar
509− // alongside the back button and tappable title. Catalog-loading
510− // spinners stay inline (next to the overflow) so a load state is
511− // visible without opening the menu.
512− val moreLabel = stringResource(R.string.more)
513− val loadingLabel = stringResource(R.string.loading)
514− val shareLabel = stringResource(R.string.share_conversation)
515− val commandsLabel = stringResource(R.string.commands)
516− val agentLabel = stringResource(R.string.choose_agent)
517− val modelLabel = stringResource(R.string.choose_model)
518− val renameLabel = stringResource(R.string.rename_session_chat)
519− val deleteLabel = stringResource(R.string.delete_session_chat)
520− val createShareLabel = stringResource(R.string.create_share_link)
521− val copyShareLabel = stringResource(R.string.copy_share_link)
522− val stopShareLabel = stringResource(R.string.stop_sharing)
523− val summarizeLabel = stringResource(R.string.summarize_conversation)
524− val initLabel = stringResource(R.string.generate_agents_md)
525− val shellLabel = stringResource(R.string.run_shell_command)
527− IconButton(onClick = { showOverflowMenu = true }) {
528− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
531− expanded = showOverflowMenu,
532− onDismissRequest = { showOverflowMenu = false },
535− text = { Text(shareLabel) },
536− enabled = hasMessages,
538− showOverflowMenu = false
540− val md = withContext(Dispatchers.Default) {
541− buildConversationMarkdown(vm.messages.value, sessionTitle)
543− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
544− type = "text/markdown"
545− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
546− putExtra(android.content.Intent.EXTRA_TEXT, md)
548− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
549− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
554− text = { Text(commandsLabel) },
555− enabled = !commandsLoading || commands.isNotEmpty(),
556− onClick = { showOverflowMenu = false; showCommandPicker = true },
559− text = { Text(agentLabel) },
560− enabled = !agentsLoading || agents.isNotEmpty(),
561− onClick = { showOverflowMenu = false; showAgentPicker = true },
564− text = { Text(modelLabel) },
565− enabled = !modelsLoading || models.isNotEmpty(),
566− onClick = { showOverflowMenu = false; showModelPicker = true },
568− androidx.compose.material3.HorizontalDivider()
569− // Session sharing: create a public link, copy an existing one, or revoke it.
570− if (shareUrl == null) {
572− text = { Text(createShareLabel) },
573− enabled = hasMessages,
574− onClick = { showOverflowMenu = false; vm.shareSession() },
578− text = { Text(copyShareLabel) },
580− showOverflowMenu = false
582− copyToClipboard(shareContext, "share", it)
583− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
588− text = { Text(stopShareLabel) },
589− onClick = { showOverflowMenu = false; vm.unshareSession() },
593− text = { Text(summarizeLabel) },
594− enabled = hasMessages && !running,
595− onClick = { showOverflowMenu = false; vm.summarize() },
598− text = { Text(initLabel) },
600− onClick = { showOverflowMenu = false; vm.initProject() },
603− text = { Text(shellLabel) },
605− onClick = { showOverflowMenu = false; showShellDialog = true },
607− androidx.compose.material3.HorizontalDivider()
609− text = { Text(renameLabel) },
610− onClick = { showOverflowMenu = false; showRenameDialog = true },
613− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
614− onClick = { showOverflowMenu = false; showDeleteDialog = true },
617− // While a catalog is initially loading (empty list + loading flag),
618− // show a tiny inline spinner beside the overflow so the user can see
619− // a load is in progress without opening the menu. Once loaded the
620− // spinner disappears; the menu items are always enabled (tapping a
621− // picker with no items shows the "no models/agents/commands" state).
622− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
623− (agentsLoading && agents.isEmpty()) ||
624− (modelsLoading && models.isEmpty())
625− if (catalogLoading) {
626− CircularProgressIndicator(
628− .align(Alignment.TopEnd)
630− .semantics { contentDescription = loadingLabel },
638− snackbarHost = { SnackbarHost(snackbar) },
640− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
641− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
642− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
643− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
645− // Pinned above the composer so the agent's plan and progress stay visible
646− // while scrolled up mid-run; renders nothing when there's no plan.
647− TodoPlanBar(todoPlan)
648− AnimatedVisibility(visible = reverted) {
649− RevertBanner(onUndo = { vm.unrevert() })
651− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
653− count = queuedOffline.size,
654− sending = outboxSending,
655− onFlush = { vm.flushQueued() },
656− onDiscard = { vm.discardAllQueued() },
661− onValueChange = vm::updateDraft,
663− aborting = aborting,
664− enabled = activeConnection != null,
665− sendOnEnter = sendOnEnter,
667− onAbort = { showStopConfirm = true },
668− queuedFollowUp = queuedFollowUp,
669− onQueueFollowUp = vm::queueFollowUp,
670− onCancelQueue = { vm.queueFollowUp("") },
671− focusRequester = inputFocusRequester,
672− attachments = attachments,
673− staging = stagingCount > 0,
674− onRemoveAttachment = vm::removeAttachment,
677− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
680− onPickFile = { filePicker.launch("*/*") },
681− onCamera = { launchCamera() },
682− onVoice = { launchVoice() },
687− // Collect messages inside the content lambda so streaming token updates
688− // recompose only this subtree, not the top bar / input bar / 20+ other
689− // state reads in the ChatScreen body.
690− val messages by vm.messages.collectAsStateWithLifecycle()
691− val listState = rememberLazyListState()
692− val contentScope = rememberCoroutineScope()
693− val timeTick = rememberRelativeTimeTick()
694− // Group messages by day and interleave date separators so a long conversation
695− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
696− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
697− // outside the PullToRefreshBox so the auto-scroll effects below can reference
698− // the same list the LazyColumn renders (separators shift the indices vs. the
699− // raw messages list, so scroll targets must be in listItems space).
700− val todayLabel = stringResource(R.string.today)
701− val yesterdayLabel = stringResource(R.string.yesterday)
702− val listItems = remember(messages, todayLabel, yesterdayLabel) {
703− buildMessageListItems(messages, todayLabel, yesterdayLabel)
705− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
706− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
707− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
708− // would capture the first composition's list — which is empty, since `messages`
709− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
710− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
711− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
712− // whose value tracks the latest list.
713− val currentListItems by rememberUpdatedState(listItems)
715− // New-content signal for the jump-to-latest FAB: set when content grows while the user
716− // is scrolled away from the bottom, cleared once they return (see the collector below).
717− var hasNewContent by remember { mutableStateOf(false) }
719− val isPinnedToBottom by remember {
721− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
722− // When a run is active, the LazyColumn has one trailing "__typing"
723− // item after the last list item. Account for it so "pinned to bottom"
724− // includes the working indicator — otherwise the pin check targets
725− // listItems.lastIndex, the typing row sits just below the viewport,
726− // and the user never sees the progress indicator even when pinned.
727− val items = currentListItems
728− val effectiveLast = if (running) items.size else items.lastIndex
729− lastVisible >= effectiveLast || items.isEmpty()
733− // Jump to the newest message once, when the conversation first loads. Guarded by a
734− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
735− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
736− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
737− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
738− LaunchedEffect(listItems.isNotEmpty()) {
739− if (listItems.isNotEmpty() && !didInitialScroll) {
740− // When a run is active the LazyColumn has a trailing "__typing" row at
741− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
742− // running session lands truly pinned to bottom and streaming auto-scroll engages.
743− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
744− didInitialScroll = true
748− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
749− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
750− // isPinnedToBottom check flips to false the instant you send — freezing
751− // auto-scroll. If the user was pinned to the last item just before the run
752− // began, bring the typing row into view so the pin (and streaming follow) is
753− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
754− // recomputed to false by now) so we don't scroll when the user had scrolled up.
755− LaunchedEffect(running) {
756− if (running && listItems.isNotEmpty()) {
757− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
758− if (lastVisible >= listItems.lastIndex) {
759− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
764− LaunchedEffect(Unit) {
768− // Track list size + the streaming length of the last part so we auto-scroll
769− // as content arrives, plus the pinned flag. A small data class with primitive
770− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
771− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
772− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
773− // and tool output — not just TextPart — keeps a pinned view following a long
774− // reasoning/tool block while it streams (previously it stalled at 0).
775− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
776− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
777− }.collect { signal ->
778− if (signal.pinned) {
779− // Back at the bottom: clear the new-content badge.
780− hasNewContent = false
781− if (signal.size > 0) {
782− // Scroll to the effective last index, including the trailing
783− // "__typing" row when a run is active so the working indicator
784− // is brought into view (not just the last message).
785− val items = currentListItems
786− val target = if (running) items.size else items.lastIndex
787− listState.scrollToItem(target)
789− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
790− // Content arrived while scrolled up — badge the jump-to-latest FAB.
791− hasNewContent = true
793− prevSize = signal.size
794− prevLen = signal.lastTextLength
798− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
799− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
800− // content padding accounts for the bottomBar's raised height, so the message
801− // list is already above the keyboard. Adding imePadding here would double-apply
802− // the IME inset and push messages too far up.
803− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
804− if (activeConnection == null) {
806− modifier = Modifier.align(Alignment.Center).padding(24.dp),
807− horizontalAlignment = Alignment.CenterHorizontally,
810− stringResource(R.string.not_connected),
811− color = MaterialTheme.colorScheme.error,
813− Spacer(Modifier.size(12.dp))
814− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
816− CircularProgressIndicator(
817− Modifier.size(20.dp),
818− color = MaterialTheme.colorScheme.onPrimary,
822− Text(stringResource(R.string.reconnect))
828− state = connectionState,
829− modifier = Modifier.align(Alignment.TopCenter),
830− isOnline = isOnline,
831− // On a hard failure, retry by forcing an SSE reconnect (which
832− // re-seeds from REST). refreshMessages is the right recovery path
833− // when the connection is present but the stream died; reconnect()
834− // is the path when the whole connection is gone (handled by the
835− // separate "Not connected" state below).
836− onRetry = { vm.refreshMessages() },
838− if (loading && messages.isEmpty()) {
839− val loadingLabel = stringResource(R.string.loading)
840− CircularProgressIndicator(
842− .align(Alignment.Center)
843− .semantics { contentDescription = loadingLabel },
845− } else if (loadError && messages.isEmpty()) {
846− // A failed load with nothing to show. Distinct from the empty
847− // conversation state below — the conversation isn't empty, it
848− // failed to load, and offering "Start a conversation" here is
849− // misleading. Offer a Retry instead, mirroring SessionListScreen.
851− modifier = Modifier.align(Alignment.Center).padding(24.dp),
852− horizontalAlignment = Alignment.CenterHorizontally,
855− stringResource(R.string.load_messages_failed),
856− color = MaterialTheme.colorScheme.error,
858− Spacer(Modifier.size(12.dp))
859− Button(onClick = { vm.refreshMessages() }) {
860− Text(stringResource(R.string.retry))
863− } else if (messages.isEmpty() && running) {
864− // A run just started but no parts have arrived yet — the empty
865− // list with only the trailing "working…" row looks broken, so
866− // surface a clear starting state until the first part streams in.
867− val workingText = stringResource(R.string.working)
869− modifier = Modifier.align(Alignment.Center).padding(24.dp),
870− horizontalAlignment = Alignment.CenterHorizontally,
872− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
873− Spacer(Modifier.size(12.dp))
874− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
876− } else if (messages.isEmpty()) {
880− // Focus the input so the user can edit the suggestion before
881− // sending, instead of having to manually tap the field.
882− runCatching { inputFocusRequester.requestFocus() }
884− modifier = Modifier.align(Alignment.Center),
887− // Pull-to-refresh wraps the message list so the user can force an SSE
888− // reconnect + re-seed with the same gesture they use on the session and
889− // file lists, instead of hunting for the top-bar refresh icon. The empty
890− // / loading / error states above stay outside the PTR box since there's
891− // no list content to pull against.
893− isRefreshing = refreshing,
894− onRefresh = { vm.refreshMessages() },
895− modifier = Modifier.fillMaxSize(),
897− val lastMessageId = messages.lastOrNull()?.info?.id
898− // Text-to-speech for reading assistant replies aloud; shuts down when the
899− // message list leaves composition.
900− val tts = rememberTtsController()
901− val speakingMessageId by tts.speakingId
904− modifier = Modifier.fillMaxSize(),
905− // Extra bottom padding reserves room for the jump-to-latest FAB so it
906− // never floats over the last message.
907− contentPadding = PaddingValues(
911− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
913− verticalArrangement = Arrangement.spacedBy(16.dp),
918− contentType = { it.contentType },
921− is MessageListItem.Separator -> DateSeparator(item.label)
922− is MessageListItem.Message -> {
923− val message = item.message
924− // Only the last (streaming) message needs isRunning — it drives the
925− // reasoning-block spinner. Passing the live flag to every bubble
926− // makes all visible messages recompose whenever a run starts or stops.
927− val modelLabel = remember(message.info, models) {
928− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
929− ?.let { resolveModelLabel(it, models) }
933− isRunning = running && message.info.id == lastMessageId,
934− imageContext = imageContext,
935− modelLabel = modelLabel,
936− onOpenFile = onOpenFile,
937− onRevert = { vm.revertTo(message.info.id) },
939− // editMessage reverts to before this message (hiding it and
940− // everything after); the revert banner surfaces the rewind
941− // with an Undo. Focus + scroll the composer into view like the
942− // Quote action so the prefilled draft isn't off-screen.
943− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
944− vm.editMessage(message.info.id, text)
945− runCatching { inputFocusRequester.requestFocus() }
946− contentScope.launch {
947− runCatchingCancellable {
948− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
952− onSpeak = { text -> tts.toggle(message.info.id, text) },
953− isSpeaking = message.info.id == speakingMessageId,
956− runCatching { inputFocusRequester.requestFocus() }
958− onBranch = { text -> vm.branchFrom(text) },
964− item(key = "__typing") {
965− val workingText = stringResource(R.string.working)
967− verticalAlignment = Alignment.CenterVertically,
968− modifier = Modifier.semantics {
969− contentDescription = workingText
972− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
973− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
979− // Jump-to-latest affordance when the user has scrolled away during a stream.
981− visible = !isPinnedToBottom && listItems.isNotEmpty(),
982− modifier = Modifier.align(Alignment.BottomEnd),
984− // Badge the FAB when new content arrived while the user was scrolled up, so
985− // they know there's something new to jump to (cleared once back at bottom).
988− if (hasNewContent) {
989− val newContentLabel = stringResource(R.string.new_messages)
990− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
993− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
995− ExtendedFloatingActionButton(
997− hasNewContent = false
998− if (listItems.isNotEmpty()) {
999− // Scroll to the effective last index, including the
1000− // trailing "__typing" row when a run is active.
1001− val target = if (running) listItems.size else listItems.lastIndex
1002− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1005− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(R.string.latest)) },
1006− text = { Text(stringResource(R.string.latest)) },
1016− if (showExitConfirm) {
1018− onDismissRequest = { showExitConfirm = false },
1019− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1020− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1022− TextButton(onClick = {
1023− showExitConfirm = false
1024− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1027− }) { Text(stringResource(R.string.stop_and_exit)) }
1030− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1035− if (showStopConfirm) {
1037− onDismissRequest = { showStopConfirm = false },
1038− title = { Text(stringResource(R.string.stop_run_title)) },
1039− text = { Text(stringResource(R.string.stop_run_text)) },
1041− TextButton(onClick = {
1042− showStopConfirm = false
1043− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1045− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1048− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1053− if (showRenameDialog) {
1054− RenameSessionChatDialog(
1055− initialTitle = sessionTitle ?: "",
1056− onDismiss = { showRenameDialog = false },
1057− onConfirm = { newName ->
1058− showRenameDialog = false
1059− vm.renameSession(newName)
1064− if (showDeleteDialog) {
1066− onDismissRequest = { showDeleteDialog = false },
1067− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1068− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1070− TextButton(onClick = {
1071− showDeleteDialog = false
1072− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1074− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1077− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1082− if (showShellDialog) {
1083− ShellCommandDialog(
1084− onDismiss = { showShellDialog = false },
1086− showShellDialog = false
1092− if (showModelPicker) {
1095− selected = selectedModel,
1096− loading = modelsLoading,
1097− error = modelsError,
1098− onSelect = { vm.selectModel(it) },
1099− onRetry = { vm.reloadModels() },
1100− onDismiss = { showModelPicker = false },
1104− if (showAgentPicker) {
1107− selected = selectedAgent,
1108− loading = agentsLoading,
1109− error = agentsError,
1110− onSelect = { vm.selectAgent(it?.name) },
1111− onRetry = { vm.reloadAgents() },
1112− onDismiss = { showAgentPicker = false },
1116− if (showCommandPicker) {
1117− CommandPickerSheet(
1118− commands = commands,
1119− loading = commandsLoading,
1120− error = commandsError,
1121− onSelect = { vm.runCommand(it) },
1122− onRetry = { vm.reloadCommands() },
1123− onDismiss = { showCommandPicker = false },
1127− pendingPermission?.let { permission ->
1129− permission = permission,
1130− onRespond = { response -> vm.respondPermission(permission, response) },
1135− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1140−private fun ChatInputBar(
1142− onValueChange: (String) -> Unit,
1146− sendOnEnter: Boolean,
1147− onSend: () -> Unit,
1148− onAbort: () -> Unit,
1149− queuedFollowUp: String?,
1150− onQueueFollowUp: (String) -> Unit,
1151− onCancelQueue: () -> Unit,
1152− focusRequester: androidx.compose.ui.focus.FocusRequester,
1153− attachments: List<PendingAttachment>,
1155− onRemoveAttachment: (String) -> Unit,
1156− onPickPhoto: () -> Unit,
1157− onPickFile: () -> Unit,
1158− onCamera: () -> Unit,
1159− onVoice: () -> Unit,
1161− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1162− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1163− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1164− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1165− // A queued follow-up replaces the Stop button with a "queued" chip so the
1166− // user sees their message will be sent when the run finishes, and can cancel.
1167− if (queuedFollowUp != null) {
1169− modifier = Modifier
1171− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1172− verticalAlignment = Alignment.CenterVertically,
1174− Column(modifier = Modifier.weight(1f)) {
1176− stringResource(R.string.queued),
1177− style = MaterialTheme.typography.labelSmall,
1178− color = MaterialTheme.colorScheme.onSurfaceVariant,
1182− style = MaterialTheme.typography.bodySmall,
1183− color = MaterialTheme.colorScheme.onSurfaceVariant,
1185− overflow = TextOverflow.Ellipsis,
1188− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1189− Text(stringResource(R.string.cancel))
1193− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1194− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1196− modifier = Modifier.fillMaxWidth().padding(8.dp),
1197− verticalAlignment = Alignment.Bottom,
1199− // Attach menu: photo picker, camera, or any file.
1200− var showAttachMenu by remember { mutableStateOf(false) }
1202− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1203− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1205− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1207− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1208− text = { Text(stringResource(R.string.attach_photo)) },
1209− onClick = { showAttachMenu = false; onPickPhoto() },
1212− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1213− text = { Text(stringResource(R.string.attach_camera)) },
1214− onClick = { showAttachMenu = false; onCamera() },
1217− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1218− text = { Text(stringResource(R.string.attach_file)) },
1219− onClick = { showAttachMenu = false; onPickFile() },
1223− // Voice dictation: appends recognized speech to the draft.
1224− IconButton(onClick = onVoice, enabled = enabled) {
1225− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1229− onValueChange = { v ->
1230− // Cap input length so a huge paste can't stall the UI. Shares are
1231− // capped separately in MainActivity; this guards typed/pasted drafts.
1232− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1234− modifier = Modifier
1236− .focusRequester(focusRequester)
1237− .testTag("chat_input")
1238− .onPreviewKeyEvent { event ->
1239− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1240− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1241− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1242− val send = enterShouldSend(
1244− hasContent = hasContent,
1245− sendOnEnter = sendOnEnter,
1246− shift = event.isShiftPressed,
1247− ctrl = event.isCtrlPressed,
1250− if (running) onQueueFollowUp(value) else onSend()
1256− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1259− // Show a "N / max" countdown once the draft crosses a high fraction of
1260− // the cap, so the user knows a paste is about to be truncated instead
1261− // of being silently cut off. Hidden for normal short prompts to avoid
1262− // clutter under a typical one-line message.
1264− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1265− if (value.length >= threshold) {
1268− R.string.draft_chars_remaining,
1269− NetworkConfig.maxDraftLengthChars - value.length,
1270− NetworkConfig.maxDraftLengthChars,
1272− style = MaterialTheme.typography.labelSmall,
1273− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1274− else MaterialTheme.colorScheme.onSurfaceVariant,
1278− keyboardOptions = KeyboardOptions(
1279− // With send-on-Enter off, expose the platform default action so the soft
1280− // keyboard shows a newline key (this is a multi-line field) instead of a
1281− // Send action — otherwise the setting has no effect on soft keyboards and
1282− // there's no way to type a newline. Hardware Enter is handled separately.
1283− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1284− capitalization = KeyboardCapitalization.Sentences,
1286− keyboardActions = KeyboardActions(onSend = {
1288− // During a run the Send IME action queues a follow-up, but only when
1289− // there's typed text — queuing "" would cancel an existing queued
1290− // follow-up (see the Queue button gate). When not running, an
1291− // attachment-only send is valid, so gate that path on hasContent.
1293− if (value.isNotBlank()) onQueueFollowUp(value)
1294− } else if (hasContent) {
1300− ComposerTrailingButton(
1302− aborting = aborting,
1303− canSend = enabled && hasContent,
1304− canQueue = enabled && value.isNotBlank(),
1307− onQueue = { onQueueFollowUp(value) },
1314−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1315− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1316−private fun enterShouldSend(
1318− hasContent: Boolean,
1319− sendOnEnter: Boolean,
1323− !enabled || !hasContent -> false
1324− sendOnEnter -> !shift
1328−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1329− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1330− * [ChatInputBar] stays under the complexity threshold. */
1332−private fun ComposerTrailingButton(
1337− onSend: () -> Unit,
1338− onAbort: () -> Unit,
1339− onQueue: () -> Unit,
1342− Row(verticalAlignment = Alignment.CenterVertically) {
1343− // While a run is active the trailing action is Stop, so the only send affordance is
1344− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1345− // That leaves a touch-only user with the setting off no way to queue a follow-up
1346− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1347− // there's typed TEXT so queuing is always reachable, without changing the user's
1348− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1349− // canSend, which is also true for an attachment-only composer — because queuing "" just
1350− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1351− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1355− modifier = Modifier.testTag("queue_button"),
1358− Icons.AutoMirrored.Filled.Send,
1359− contentDescription = stringResource(R.string.queue_followup),
1363− // Show a spinner while the abort REST call is in flight so the user sees the stop
1364− // was sent, and disable to prevent a double-tap.
1367− enabled = !aborting,
1368− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1371− val stopLabel = stringResource(R.string.stop)
1372− CircularProgressIndicator(
1373− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1374− strokeWidth = 2.dp,
1377− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1385− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1387− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1392−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1394−private fun EmptyConversation(
1395− onSuggestion: (String) -> Unit,
1396− modifier: Modifier = Modifier,
1398− // A few example prompts so a first-time user has a one-tap path to their first
1399− // message instead of staring at a blank input. Tapping a chip fills the draft
1400− // (without sending) so the user can edit it before sending.
1401− val suggestions = remember {
1403− R.string.empty_chat_suggest_1,
1404− R.string.empty_chat_suggest_2,
1405− R.string.empty_chat_suggest_3,
1409− modifier = modifier.padding(32.dp),
1410− horizontalAlignment = Alignment.CenterHorizontally,
1413− Icons.Filled.AutoAwesome,
1414− contentDescription = null,
1415− modifier = Modifier.size(48.dp),
1416− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1418− Spacer(Modifier.size(16.dp))
1420− stringResource(R.string.empty_chat_title),
1421− style = MaterialTheme.typography.titleMedium,
1423− Spacer(Modifier.size(8.dp))
1425− stringResource(R.string.empty_chat_hint),
1426− style = MaterialTheme.typography.bodyMedium,
1427− color = MaterialTheme.colorScheme.onSurfaceVariant,
1429− Spacer(Modifier.size(20.dp))
1430− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1431− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1433− modifier = Modifier.fillMaxWidth(),
1434− horizontalArrangement = Arrangement.spacedBy(8.dp),
1435− verticalArrangement = Arrangement.spacedBy(8.dp),
1437− suggestions.forEach { resId ->
1438− val text = stringResource(resId)
1439− androidx.compose.material3.AssistChip(
1440− onClick = { onSuggestion(text) },
1441− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1448−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1450−private fun RevertBanner(onUndo: () -> Unit) {
1452− color = MaterialTheme.colorScheme.tertiaryContainer,
1453− tonalElevation = 2.dp,
1454− modifier = Modifier.fillMaxWidth(),
1457− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1458− verticalAlignment = Alignment.CenterVertically,
1459− horizontalArrangement = Arrangement.SpaceBetween,
1461− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1463− Icons.Filled.Restore,
1464− contentDescription = null,
1465− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1466− modifier = Modifier.size(18.dp),
1469− stringResource(R.string.reverted_banner),
1470− style = MaterialTheme.typography.bodySmall,
1471− color = MaterialTheme.colorScheme.onTertiaryContainer,
1472− modifier = Modifier.padding(start = 8.dp),
1475− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1480−/** A banner shown while messages composed offline are queued in the outbox, with a
1481− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1483−private fun OutboxBanner(
1486− onFlush: () -> Unit,
1487− onDiscard: () -> Unit,
1490− color = MaterialTheme.colorScheme.secondaryContainer,
1491− tonalElevation = 2.dp,
1492− modifier = Modifier.fillMaxWidth(),
1495− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1496− verticalAlignment = Alignment.CenterVertically,
1497− horizontalArrangement = Arrangement.SpaceBetween,
1499− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1501− CircularProgressIndicator(
1502− Modifier.size(16.dp),
1503− strokeWidth = 2.dp,
1504− color = MaterialTheme.colorScheme.onSecondaryContainer,
1506− Spacer(Modifier.size(8.dp))
1510− stringResource(R.string.outbox_sending)
1512− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1513− stringResource(res, count)
1515− style = MaterialTheme.typography.bodySmall,
1516− color = MaterialTheme.colorScheme.onSecondaryContainer,
1520− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1521− TextButton(onClick = onDiscard) {
1522− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1529−/** Prompt for a one-off shell command to run in the session's worktree. */
1531−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1532− var command by rememberSaveable { mutableStateOf("") }
1534− onDismissRequest = onDismiss,
1535− title = { Text(stringResource(R.string.run_shell_command)) },
1539− onValueChange = { command = it },
1540− modifier = Modifier.fillMaxWidth(),
1541− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1542− label = { Text(stringResource(R.string.shell_command_label)) },
1544− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1545− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1550− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1551− enabled = command.isNotBlank(),
1552− ) { Text(stringResource(R.string.run)) }
1554− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1559− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1560− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1561− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1563−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1565−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1566− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1567− * streaming, not just plain assistant text. O(1). */
1568−private fun streamingContentLength(part: Part?): Int = when (part) {
1569− is TextPart -> part.text.length
1570− is ReasoningPart -> part.text.length
1571− is ToolPart -> when (val st = part.state) {
1572− is ToolCompleted -> st.output?.length ?: 0
1573− is ToolError -> st.error?.length ?: 0
1574− is ToolRunning -> st.title?.length ?: 0
1580−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1581− * dialog but lives in the chat screen so the user can rename without backing out to
1582− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1584−private fun RenameSessionChatDialog(
1585− initialTitle: String,
1586− onDismiss: () -> Unit,
1587− onConfirm: (String) -> Unit,
1589− // Seed the field once (no key input) so a later external title change — e.g. opencode
1590− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1591− // doesn't re-initialize the box and discard the user's in-progress edit.
1592− var title by rememberSaveable { mutableStateOf(initialTitle) }
1594− onDismissRequest = onDismiss,
1595− title = { Text(stringResource(R.string.rename_session_chat)) },
1599− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1600− modifier = Modifier.fillMaxWidth(),
1601− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1602− label = { Text(stringResource(R.string.rename_session_chat)) },
1604− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1605− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1609− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1610− Text(stringResource(R.string.save))
1614− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1620− * A single item in the chat message list — either a [Message] bubble or a day
1621− * [Separator] inserted before the first message of a new day. The separator shifts
1622− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1623− * the [List] of these items (not `messages.size`/`lastIndex`).
1625−private sealed interface MessageListItem {
1627− val contentType: Any
1629− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1630− override val contentType: Any get() = message.info::class
1633− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1634− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1635− // can share a label (e.g. an untimestamped message — empty label — between two
1636− // same-day messages, or two untimestamped groups), and a label-only key would
1637− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1638− // stable for a given message ordering so slots aren't needlessly recreated.
1639− override val key: Any get() = "sep_${ordinal}_$label"
1640− // Separators share a contentType so the LazyColumn can recycle their slots.
1641− override val contentType: Any get() = "separator"
1646− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1647− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1648− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1649− * Messages with no timestamp are grouped under an empty-label separator only if they
1650− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1652− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1653− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1654− * labels; older days fall back to a locale-stable medium-date format.
1656−private fun buildMessageListItems(
1657− messages: List<MessageWithParts>,
1658− todayLabel: String,
1659− yesterdayLabel: String,
1660−): List<MessageListItem> {
1661− if (messages.isEmpty()) return emptyList()
1662− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1663− val dateFmt = mediumDateFormat()
1664− val result = ArrayList<MessageListItem>(messages.size + 4)
1665− val seenKeys = HashSet<String>(messages.size * 2)
1666− var lastDayKey: String? = null
1668− var emptyIdOrdinal = 0
1670− for (message in messages) {
1671− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1672− val dayKey = ts?.let { dayKey(it) } ?: ""
1673− // Emit a separator before the very first message (so a leading un-timestamped message
1674− // still gets the first divider, empty label and all), and thereafter only when crossing
1675− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1676− // neither emits its own separator nor resets the day — otherwise a following same-day
1677− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1678− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1679− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1681− if (dayKey.isNotEmpty()) lastDayKey = dayKey
1683− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1684− // empty id — and the reducer intentionally keeps several such messages as distinct
1685− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1686− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1687− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1688− if (!seenKeys.add(key)) {
1690− while (!seenKeys.add("$key#$suffix")) suffix++
1691− key = "$key#$suffix"
1693− result.add(MessageListItem.Message(message, key))
1699− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1701− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1702− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1703− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1704− * every message on every token. Message timestamps are immutable once assigned, so we
1705− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1706− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1707− * thread during composition, so the coarse lock is uncontended.
1709−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1710− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1713−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1714− dayKeyCache.getOrPut(epochMillis) {
1715− java.time.Instant.ofEpochMilli(epochMillis)
1716− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1720−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1721−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1722−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1723−private var cachedDateFmt: java.text.DateFormat? = null
1724−private var cachedDateFmtLocale: java.util.Locale? = null
1726−private fun mediumDateFormat(): java.text.DateFormat {
1727− val locale = java.util.Locale.getDefault()
1728− val existing = cachedDateFmt
1729− if (existing != null && cachedDateFmtLocale == locale) return existing
1730− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1732− cachedDateFmtLocale = locale
1737− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1738− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1739− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1742−private fun dayLabel(
1745− today: java.time.LocalDate,
1746− todayLabel: String,
1747− yesterdayLabel: String,
1748− dateFmt: java.text.DateFormat,
1750− if (dayKey.isEmpty()) return ""
1751− val epochDay = dayKey.toLongOrNull() ?: return ""
1752− val date = java.time.LocalDate.ofEpochDay(epochDay)
1754− date == today -> todayLabel
1755− date == today.minusDays(1) -> yesterdayLabel
1756− else -> dateFmt.format(java.util.Date(ts))
1761− * A centered day divider in the message list. Renders nothing for an empty label
1762− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1765−private fun DateSeparator(label: String) {
1766− if (label.isBlank()) return
1768− modifier = Modifier.fillMaxWidth(),
1769− horizontalArrangement = Arrangement.Center,
1772− color = MaterialTheme.colorScheme.surfaceVariant,
1773− shape = MaterialTheme.shapes.small,
1777− style = MaterialTheme.typography.labelSmall,
1778− color = MaterialTheme.colorScheme.onSurfaceVariant,
1779− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),