@@ -1,1991 +0,0 @@
1−@file:Suppress("TooManyFunctions")
2−
3−package soy.iko.opencode.ui.chat
4−
5−import android.app.Activity
6−import android.content.Intent
7−import android.net.Uri
8−import android.speech.RecognizerIntent
9−import androidx.activity.compose.BackHandler
10−import androidx.activity.compose.rememberLauncherForActivityResult
11−import androidx.activity.result.PickVisualMediaRequest
12−import androidx.activity.result.contract.ActivityResultContracts
13−import androidx.compose.animation.AnimatedVisibility
14−import androidx.compose.foundation.clickable
15−import androidx.compose.foundation.layout.Arrangement
16−import androidx.compose.foundation.layout.Box
17−import androidx.compose.foundation.layout.Column
18−import androidx.compose.foundation.layout.FlowRow
19−import androidx.compose.foundation.layout.PaddingValues
20−import androidx.compose.foundation.layout.Row
21−import androidx.compose.foundation.layout.Spacer
22−import androidx.compose.foundation.layout.WindowInsets
23−import androidx.compose.foundation.layout.fillMaxSize
24−import androidx.compose.foundation.layout.fillMaxWidth
25−import androidx.compose.foundation.layout.imePadding
26−import androidx.compose.foundation.layout.navigationBars
27−import androidx.compose.foundation.layout.padding
28−import androidx.compose.foundation.layout.size
29−import androidx.compose.foundation.layout.union
30−import androidx.compose.foundation.layout.widthIn
31−import androidx.compose.foundation.layout.windowInsetsPadding
32−import androidx.compose.foundation.layout.wrapContentWidth
33−import androidx.compose.foundation.lazy.LazyColumn
34−import androidx.compose.foundation.lazy.items
35−import androidx.compose.foundation.lazy.rememberLazyListState
36−import androidx.compose.material.icons.Icons
37−import androidx.compose.material.icons.automirrored.filled.ArrowBack
38−import androidx.compose.material.icons.automirrored.filled.Send
39−import androidx.compose.material.icons.filled.Add
40−import androidx.compose.material.icons.filled.AutoAwesome
41−import androidx.compose.material.icons.filled.Delete
42−import androidx.compose.material.icons.filled.Description
43−import androidx.compose.material.icons.filled.Edit
44−import androidx.compose.material.icons.filled.Expand
45−import androidx.compose.material.icons.filled.KeyboardArrowDown
46−import androidx.compose.material.icons.filled.KeyboardArrowUp
47−import androidx.compose.material.icons.filled.Mic
48−import androidx.compose.material.icons.filled.MoreVert
49−import androidx.compose.material.icons.filled.PhotoCamera
50−import androidx.compose.material.icons.filled.PhotoLibrary
51−import androidx.compose.material.icons.filled.Refresh
52−import androidx.compose.material.icons.filled.Restore
53−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
54−import androidx.compose.material.icons.filled.Schedule
55−import androidx.compose.material.icons.filled.Stop
56−import androidx.compose.material3.AlertDialog
57−import androidx.compose.material3.Badge
58−import androidx.compose.material3.BadgedBox
59−import androidx.compose.material3.Button
60−import androidx.compose.material3.CircularProgressIndicator
61−import androidx.compose.material3.SmallFloatingActionButton
62−import androidx.compose.material3.DropdownMenu
63−import androidx.compose.material3.DropdownMenuItem
64−import androidx.compose.material3.ExperimentalMaterial3Api
65−import androidx.compose.material3.ExtendedFloatingActionButton
66−import androidx.compose.material3.FloatingActionButton
67−import androidx.compose.material3.Icon
68−import androidx.compose.material3.IconButton
69−import androidx.compose.material3.MaterialTheme
70−import androidx.compose.material3.OutlinedTextField
71−import androidx.compose.material3.Scaffold
72−import androidx.compose.material3.SnackbarHost
73−import androidx.compose.material3.SnackbarHostState
74−import androidx.compose.material3.Surface
75−import androidx.compose.material3.Text
76−import androidx.compose.material3.TextButton
77−import androidx.compose.material3.TopAppBar
78−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
79−import androidx.compose.runtime.Composable
80−import androidx.compose.runtime.CompositionLocalProvider
81−import androidx.compose.runtime.DisposableEffect
82−import androidx.compose.runtime.LaunchedEffect
83−import androidx.compose.runtime.derivedStateOf
84−import androidx.compose.runtime.getValue
85−import androidx.compose.runtime.mutableStateOf
86−import androidx.compose.runtime.remember
87−import androidx.compose.runtime.rememberCoroutineScope
88−import androidx.compose.runtime.rememberUpdatedState
89−import androidx.compose.runtime.saveable.rememberSaveable
90−import androidx.compose.runtime.setValue
91−import androidx.compose.runtime.snapshotFlow
92−import androidx.compose.foundation.text.KeyboardActions
93−import androidx.compose.foundation.text.KeyboardOptions
94−import androidx.compose.ui.text.input.KeyboardCapitalization
95−import androidx.compose.ui.Alignment
96−import androidx.compose.ui.Modifier
97−import androidx.compose.ui.focus.focusRequester
98−import androidx.compose.ui.input.key.Key
99−import androidx.compose.ui.input.key.KeyEventType
100−import androidx.compose.ui.input.key.isCtrlPressed
101−import androidx.compose.ui.input.key.isShiftPressed
102−import androidx.compose.ui.input.key.key
103−import androidx.compose.ui.input.key.onPreviewKeyEvent
104−import androidx.compose.ui.input.key.type
105−import androidx.compose.ui.platform.LocalContext
106−import androidx.compose.ui.platform.LocalHapticFeedback
107−import androidx.compose.ui.platform.LocalView
108−import androidx.compose.ui.platform.testTag
109−import androidx.compose.ui.res.stringResource
110−import androidx.compose.ui.semantics.Role
111−import androidx.compose.ui.semantics.contentDescription
112−import androidx.compose.ui.semantics.semantics
113−import androidx.compose.ui.text.input.ImeAction
114−import androidx.compose.ui.text.style.TextOverflow
115−import androidx.compose.ui.unit.dp
116−import androidx.lifecycle.compose.collectAsStateWithLifecycle
117−import androidx.lifecycle.viewmodel.compose.viewModel
118−import kotlinx.coroutines.Dispatchers
119−import kotlinx.coroutines.flow.distinctUntilChanged
120−import kotlinx.coroutines.launch
121−import kotlinx.coroutines.withContext
122−import soy.iko.opencode.data.model.Part
123−import soy.iko.opencode.data.model.MessageWithParts
124−import soy.iko.opencode.data.model.ReasoningPart
125−import soy.iko.opencode.data.model.TextPart
126−import soy.iko.opencode.data.model.ToolCompleted
127−import soy.iko.opencode.data.model.ToolError
128−import soy.iko.opencode.data.model.ToolPart
129−import soy.iko.opencode.data.model.ToolRunning
130−import soy.iko.opencode.data.network.EventStreamClient
131−import soy.iko.opencode.data.network.NetworkConfig
132−import soy.iko.opencode.di.AppContainer
133−import soy.iko.opencode.R
134−import soy.iko.opencode.ui.components.CommandPalette
135−import soy.iko.opencode.ui.components.ConnectionBanner
136−import soy.iko.opencode.ui.components.PaletteAction
137−import soy.iko.opencode.ui.components.copyToClipboard
138−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
139−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
140−import soy.iko.opencode.ui.components.showToast
141−import soy.iko.opencode.ui.components.toImageContext
142−import soy.iko.opencode.ui.vmFactory
143−import soy.iko.opencode.util.runCatchingCancellable
144−
145−@OptIn(ExperimentalMaterial3Api::class)
146−@Composable
147−fun ChatScreen(
148− container: AppContainer,
149− sessionId: String,
150− onBack: () -> Unit,
151− onOpenFile: ((String) -> Unit)? = null,
152− onOpenSession: ((String) -> Unit)? = null,
153−) {
154− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
155− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
156− val running by vm.running.collectAsStateWithLifecycle()
157− val aborting by vm.aborting.collectAsStateWithLifecycle()
158− val loading by vm.loading.collectAsStateWithLifecycle()
159− val loadError by vm.loadError.collectAsStateWithLifecycle()
160− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
161− val models by vm.models.collectAsStateWithLifecycle()
162− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
163− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
164− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
165− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
166− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
167− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
168− val agents by vm.agents.collectAsStateWithLifecycle()
169− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
170− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
171− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
172− val commands by vm.commands.collectAsStateWithLifecycle()
173− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
174− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
175− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
176− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
177− val draft by vm.draft.collectAsStateWithLifecycle()
178− val attachments by vm.attachments.collectAsStateWithLifecycle()
179− val reverted by vm.reverted.collectAsStateWithLifecycle()
180− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
181− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
182− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
183− val isOnline by container.isOnline.collectAsStateWithLifecycle()
184− val haptics = LocalHapticFeedback.current
185− val scope = rememberCoroutineScope()
186− val shareContext = LocalContext.current
187− val defaultShareSubject = stringResource(R.string.share_subject)
188− val sessionLabel = stringResource(R.string.session)
189− val defaultModelLabel = stringResource(R.string.default_model)
190− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
191− buildString {
192− append(selectedModel?.modelLabel ?: defaultModelLabel)
193− selectedAgent?.let { append(" · $it") }
194− }
195− }
196−
197− // Connection profile (with auth) for rendering inline image attachments.
198− // Collect as state so a server switch recomposes the image context.
199− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
200− val imageContext = remember(activeConnection?.profile) {
201− activeConnection?.profile?.toImageContext()
202− }
203−
204− // Mark this session as read while the user is viewing it; clear on leave so new
205− // background activity can badge it again.
206− DisposableEffect(sessionId) {
207− container.setCurrentSession(sessionId)
208− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
209− }
210−
211− // Navigate away when the session is deleted via SSE so the user isn't left
212− // on a zombie screen showing a conversation that no longer exists. Surface a
213− // toast (not a snackbar) because the screen is about to be popped — a snackbar
214− // would be torn down before the user could read it, while a toast survives.
215− // Covers both SSE-driven deletion (deleted on another device) and a user-
216− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
217− // sets the same flag on success).
218− val deletedContext = LocalContext.current
219− LaunchedEffect(sessionDeleted) {
220− if (sessionDeleted) {
221− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
222− onBack()
223− }
224− }
225−
226− val snackbar = remember { SnackbarHostState() }
227− val retryLabel = stringResource(R.string.retry)
228− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
229− var showModelPicker by rememberSaveable { mutableStateOf(false) }
230− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
231− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
232− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
233− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
234− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
235− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
236− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
237− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
238− var showShellDialog by rememberSaveable { mutableStateOf(false) }
239− var showPalette by rememberSaveable { mutableStateOf(false) }
240− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
241− // a confirmation dialog (from both the overflow menu and the command palette).
242− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
243− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
244−
245− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
246− // action list doesn't need a Composable context. Actions map to the same handlers the
247− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
248− val paletteModelLabel = stringResource(R.string.palette_switch_model)
249− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
250− val paletteCommandLabel = stringResource(R.string.palette_run_command)
251− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
252− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
253− val paletteShellLabel = stringResource(R.string.run_shell_command)
254− val paletteActions = remember(
255− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
256− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
257− ) {
258− buildList {
259− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
260− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
261− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
262− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
263− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
264− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
265− }
266− }
267−
268− // Keep the screen awake while the agent is working in *this* session. The foreground
269− // service that holds process priority during a run is managed app-wide off
270− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
271− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
272− // SSE stream before the completion notification fires.
273− val currentView = LocalView.current
274− val appContext = LocalContext.current.applicationContext
275− DisposableEffect(running) {
276− currentView.keepScreenOn = running
277− onDispose { currentView.keepScreenOn = false }
278− }
279−
280− LaunchedEffect(Unit) {
281− vm.errorEvents.collect { event ->
282− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
283− // message-load failure) would silently re-submit the last prompt on tap.
284− val result = if (event.retryable) {
285− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
286− } else {
287− snackbar.showSnackbar(event.message)
288− }
289− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
290− }
291− }
292−
293− // --- Attachments, voice, and share-link plumbing ---
294− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
295− val attachFailedMsg = stringResource(R.string.attachment_failed)
296− val attachLimitMsg = stringResource(R.string.attachment_limit)
297− val noCameraMsg = stringResource(R.string.no_camera_app)
298− val noVoiceMsg = stringResource(R.string.no_voice_app)
299− val voicePrompt = stringResource(R.string.voice_prompt)
300− val linkCopiedMsg = stringResource(R.string.link_copied)
301−
302− // Count of picks currently being read + base64-encoded off the main thread, so the
303− // composer can show a staging placeholder immediately (chips only materialize once done).
304− var stagingCount by remember { mutableStateOf(0) }
305−
306− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
307− // per-prompt count cap and surfacing per-file errors without aborting the batch.
308− fun stageUris(uris: List<Uri>) {
309− if (uris.isEmpty()) return
310− scope.launch {
311− stagingCount++
312− try {
313− for (uri in uris) {
314− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
315− snackbar.showSnackbar(attachLimitMsg)
316− break
317− }
318− when (val result = uri.toAttachmentResult(appContext)) {
319− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
320− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
321− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
322− }
323− }
324− } finally {
325− stagingCount--
326− }
327− }
328− }
329−
330− val photoPicker = rememberLauncherForActivityResult(
331− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
332− ) { uris -> stageUris(uris) }
333−
334− val filePicker = rememberLauncherForActivityResult(
335− ActivityResultContracts.GetMultipleContents(),
336− ) { uris -> stageUris(uris) }
337−
338− // Uri survives a config change mid-capture so the TakePicture result still resolves.
339− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
340− val cameraLauncher = rememberLauncherForActivityResult(
341− ActivityResultContracts.TakePicture(),
342− ) { success ->
343− val uri = pendingCaptureUri
344− pendingCaptureUri = null
345− if (success && uri != null) stageUris(listOf(uri))
346− }
347−
348− val voiceLauncher = rememberLauncherForActivityResult(
349− ActivityResultContracts.StartActivityForResult(),
350− ) { result ->
351− if (result.resultCode == Activity.RESULT_OK) {
352− val spoken = result.data
353− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
354− ?.firstOrNull()
355− ?.takeIf { it.isNotBlank() }
356− if (spoken != null) {
357− // Append to the existing draft rather than replacing, so dictation adds to
358− // whatever the user already typed.
359− val current = vm.draft.value
360− val combined = if (current.isBlank()) spoken else "$current $spoken"
361− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
362− }
363− }
364− }
365−
366− fun launchCamera() {
367− val uri = newCameraCaptureUri(appContext)
368− if (uri == null) {
369− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
370− return
371− }
372− pendingCaptureUri = uri
373− runCatching { cameraLauncher.launch(uri) }
374− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
375− }
376−
377− fun launchVoice() {
378− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
379− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
380− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
381− }
382− runCatching { voiceLauncher.launch(intent) }
383− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
384− }
385−
386− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
387− LaunchedEffect(Unit) {
388− vm.shareLinkEvents.collect { url ->
389− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
390− snackbar.showSnackbar(linkCopiedMsg)
391− }
392− }
393−
394− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
395− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
396− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
397− // a dropped branch-navigation event in the gap.
398− val branchedMsg = stringResource(R.string.branch_created)
399− LaunchedEffect(Unit) {
400− vm.branchEvents.collect { newId ->
401− showToast(shareContext, branchedMsg)
402− onOpenSession?.invoke(newId)
403− }
404− }
405−
406− // Stage images shared into the app (via the system share sheet) as attachments.
407− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
408− // while this ChatScreen is already composed — which happens in two-pane mode, where the
409− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
410− // only fire on first composition. consumePendingSharedMedia() atomically drains the
411− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
412− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
413− LaunchedEffect(pendingSharedMedia) {
414− val shared = container.consumePendingSharedMedia()
415− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
416− }
417−
418− fun doSend() {
419− if (vm.send(draft)) {
420− // TextHandleMove (a light tick) is semantically right for a send commit;
421− // LongPress is reserved for long-press/swipe gestures.
422− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
423− }
424− }
425−
426− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
427−
428− Scaffold(
429− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
430− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
431− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
432− // typing (and the composer's own Enter-to-send handling) is untouched.
433− modifier = Modifier.onPreviewKeyEvent { ev ->
434− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
435− when {
436− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
437− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
438− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
439− showStopConfirm = true; true
440− }
441− else -> false
442− }
443− },
444− topBar = {
445− TopAppBar(
446− title = {
447− val changeLabel = stringResource(R.string.change_model_agent)
448− // The subtitle reads "model · agent", so tapping the title offers *both*
449− // — a small menu picks which picker to open. Previously the tap went
450− // straight to the model picker, leaving the agent changeable only via
451− // the overflow menu despite the title implying otherwise.
452− Box {
453− Row(
454− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
455− // node; the click label rides on `clickable` (onClickLabel) instead of
456− // an explicit contentDescription, which would have SUPPRESSED the child
457− // Texts and announced only "Change model and agent".
458− modifier = Modifier
459− .clickable(
460− enabled = models.isNotEmpty(),
461− role = Role.Button,
462− onClickLabel = changeLabel,
463− ) { showTitleMenu = true }
464− .semantics(mergeDescendants = true) {},
465− verticalAlignment = Alignment.CenterVertically,
466− ) {
467− Column(modifier = Modifier.weight(1f, fill = false)) {
468− // maxLines=1 + Ellipsis so a long session title can't wrap and
469− // push the top bar to multiple lines, shifting the whole layout.
470− Text(
471− sessionTitle ?: sessionLabel,
472− maxLines = 1,
473− overflow = TextOverflow.Ellipsis,
474− )
475− Text(
476− subtitle,
477− style = MaterialTheme.typography.labelSmall,
478− color = MaterialTheme.colorScheme.onSurfaceVariant,
479− maxLines = 1,
480− overflow = TextOverflow.Ellipsis,
481− )
482− }
483− // Visual affordance that the title is tappable; without it the
484− // title is indistinguishable from plain text and the pickers are
485− // effectively undiscoverable.
486− if (models.isNotEmpty()) {
487− Icon(
488− Icons.Filled.KeyboardArrowDown,
489− contentDescription = null,
490− tint = MaterialTheme.colorScheme.onSurfaceVariant,
491− modifier = Modifier.size(20.dp),
492− )
493− }
494− }
495− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
496− DropdownMenuItem(
497− text = { Text(stringResource(R.string.palette_switch_model)) },
498− enabled = !modelsLoading || models.isNotEmpty(),
499− onClick = { showTitleMenu = false; showModelPicker = true },
500− )
501− DropdownMenuItem(
502− text = { Text(stringResource(R.string.palette_choose_agent)) },
503− enabled = !agentsLoading || agents.isNotEmpty(),
504− onClick = { showTitleMenu = false; showAgentPicker = true },
505− )
506− }
507− }
508− },
509− navigationIcon = {
510− IconButton(onClick = {
511− if (running) showExitConfirm = true else onBack()
512− }) {
513− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
514− }
515− },
516− actions = {
517− // At-a-glance run status in the top bar. When the user is scrolled
518− // up (jump-to-latest FAB visible), the input-bar Stop button and the
519− // trailing "working…" row are off-screen, so a top-bar spinner is the
520− // only signal the agent is still working.
521− if (running) {
522− val workingLabel = stringResource(R.string.working)
523− CircularProgressIndicator(
524− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
525− strokeWidth = 2.dp,
526− )
527− }
528− // Manual refresh: forces an SSE reconnect, which re-seeds messages
529− // from REST. A recovery path when the stream silently drops and the
530− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
531− // immediate tap feedback — the SSE reconnect may not visibly change
532− // the connection state when already Connected, so without it the tap
533− // appears to do nothing.
534− val refreshLabel = stringResource(R.string.refresh)
535− IconButton(
536− onClick = { vm.refreshMessages() },
537− enabled = activeConnection != null && !refreshing,
538− ) {
539− if (refreshing) {
540− CircularProgressIndicator(
541− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
542− strokeWidth = 2.dp,
543− )
544− } else {
545− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
546− }
547− }
548− // Overflow menu consolidates the less-frequent actions (share,
549− // commands, agent, model, rename, delete) so the top bar stays
550− // scannable on narrow phones — previously 5 icons crowded the bar
551− // alongside the back button and tappable title. Catalog-loading
552− // spinners stay inline (next to the overflow) so a load state is
553− // visible without opening the menu.
554− val moreLabel = stringResource(R.string.more)
555− val loadingLabel = stringResource(R.string.loading)
556− val shareLabel = stringResource(R.string.share_conversation)
557− val commandsLabel = stringResource(R.string.commands)
558− val renameLabel = stringResource(R.string.rename_session_chat)
559− val deleteLabel = stringResource(R.string.delete_session_chat)
560− val createShareLabel = stringResource(R.string.create_share_link)
561− val copyShareLabel = stringResource(R.string.copy_share_link)
562− val stopShareLabel = stringResource(R.string.stop_sharing)
563− val summarizeLabel = stringResource(R.string.summarize_conversation)
564− val initLabel = stringResource(R.string.generate_agents_md)
565− val shellLabel = stringResource(R.string.run_shell_command)
566− Box {
567− IconButton(onClick = { showOverflowMenu = true }) {
568− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
569− }
570− DropdownMenu(
571− expanded = showOverflowMenu,
572− onDismissRequest = { showOverflowMenu = false },
573− ) {
574− DropdownMenuItem(
575− text = { Text(shareLabel) },
576− enabled = hasMessages,
577− onClick = {
578− showOverflowMenu = false
579− scope.launch {
580− val md = withContext(Dispatchers.Default) {
581− buildConversationMarkdown(vm.messages.value, sessionTitle)
582− }
583− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
584− type = "text/markdown"
585− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
586− putExtra(android.content.Intent.EXTRA_TEXT, md)
587− }
588− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
589− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
590− }
591− },
592− )
593− DropdownMenuItem(
594− text = { Text(commandsLabel) },
595− enabled = !commandsLoading || commands.isNotEmpty(),
596− onClick = { showOverflowMenu = false; showCommandPicker = true },
597− )
598− androidx.compose.material3.HorizontalDivider()
599− // Session sharing: create a public link, copy an existing one, or revoke it.
600− if (shareUrl == null) {
601− DropdownMenuItem(
602− text = { Text(createShareLabel) },
603− enabled = hasMessages,
604− onClick = { showOverflowMenu = false; vm.shareSession() },
605− )
606− } else {
607− DropdownMenuItem(
608− text = { Text(copyShareLabel) },
609− onClick = {
610− showOverflowMenu = false
611− shareUrl?.let {
612− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
613− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
614− }
615− },
616− )
617− DropdownMenuItem(
618− text = { Text(stopShareLabel) },
619− onClick = { showOverflowMenu = false; vm.unshareSession() },
620− )
621− }
622− DropdownMenuItem(
623− text = { Text(summarizeLabel) },
624− enabled = hasMessages && !running,
625− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
626− )
627− DropdownMenuItem(
628− text = { Text(initLabel) },
629− enabled = !running,
630− onClick = { showOverflowMenu = false; showInitConfirm = true },
631− )
632− DropdownMenuItem(
633− text = { Text(shellLabel) },
634− enabled = !running,
635− onClick = { showOverflowMenu = false; showShellDialog = true },
636− )
637− androidx.compose.material3.HorizontalDivider()
638− DropdownMenuItem(
639− text = { Text(renameLabel) },
640− onClick = { showOverflowMenu = false; showRenameDialog = true },
641− )
642− DropdownMenuItem(
643− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
644− onClick = { showOverflowMenu = false; showDeleteDialog = true },
645− )
646− }
647− // While a catalog is initially loading (empty list + loading flag),
648− // show a tiny inline spinner beside the overflow so the user can see
649− // a load is in progress without opening the menu. Once loaded the
650− // spinner disappears; the menu items are always enabled (tapping a
651− // picker with no items shows the "no models/agents/commands" state).
652− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
653− (agentsLoading && agents.isEmpty()) ||
654− (modelsLoading && models.isEmpty())
655− if (catalogLoading) {
656− CircularProgressIndicator(
657− Modifier
658− .align(Alignment.TopEnd)
659− .size(10.dp)
660− .semantics { contentDescription = loadingLabel },
661− strokeWidth = 1.dp,
662− )
663− }
664− }
665− },
666− )
667− },
668− snackbarHost = { SnackbarHost(snackbar) },
669− bottomBar = {
670− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
671− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
672− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
673− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
674− Column {
675− // Pinned above the composer so the agent's plan and progress stay visible
676− // while scrolled up mid-run; renders nothing when there's no plan.
677− TodoPlanBar(todoPlan)
678− AnimatedVisibility(visible = reverted) {
679− RevertBanner(onUndo = { vm.unrevert() })
680− }
681− AnimatedVisibility(visible = queuedOffline.isNotEmpty()) {
682− OutboxBanner(
683− count = queuedOffline.size,
684− sending = outboxSending,
685− onFlush = { vm.flushQueued() },
686− onDiscard = { vm.discardAllQueued() },
687− )
688− }
689− ChatInputBar(
690− value = draft,
691− onValueChange = vm::updateDraft,
692− running = running,
693− aborting = aborting,
694− enabled = activeConnection != null,
695− sendOnEnter = sendOnEnter,
696− onSend = ::doSend,
697− onAbort = { showStopConfirm = true },
698− queuedFollowUp = queuedFollowUp,
699− onQueueFollowUp = vm::queueFollowUp,
700− onCancelQueue = { vm.queueFollowUp("") },
701− focusRequester = inputFocusRequester,
702− attachments = attachments,
703− staging = stagingCount > 0,
704− onRemoveAttachment = vm::removeAttachment,
705− onPickPhoto = {
706− photoPicker.launch(
707− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
708− )
709− },
710− onPickFile = { filePicker.launch("*/*") },
711− onCamera = { launchCamera() },
712− onVoice = { launchVoice() },
713− )
714− }
715− },
716− ) { padding ->
717− // Collect messages inside the content lambda so streaming token updates
718− // recompose only this subtree, not the top bar / input bar / 20+ other
719− // state reads in the ChatScreen body.
720− val messages by vm.messages.collectAsStateWithLifecycle()
721− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
722− val listState = rememberLazyListState()
723− val contentScope = rememberCoroutineScope()
724− val timeTick = rememberRelativeTimeTick()
725− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
726− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
727− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
728− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
729− androidx.compose.runtime.LaunchedEffect(listState) {
730− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
731− .distinctUntilChanged()
732− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
733− } // Group messages by day and interleave date separators so a long conversation
734− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
735− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
736− // outside the PullToRefreshBox so the auto-scroll effects below can reference
737− // the same list the LazyColumn renders (separators shift the indices vs. the
738− // raw messages list, so scroll targets must be in listItems space).
739− val todayLabel = stringResource(R.string.today)
740− val yesterdayLabel = stringResource(R.string.yesterday)
741− val listItems = remember(messages, todayLabel, yesterdayLabel) {
742− buildMessageListItems(messages, todayLabel, yesterdayLabel)
743− }
744− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
745− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
746− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
747− // would capture the first composition's list — which is empty, since `messages`
748− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
749− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
750− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
751− // whose value tracks the latest list.
752− val currentListItems by rememberUpdatedState(listItems)
753−
754− // New-content signal for the jump-to-latest FAB: set when content grows while the user
755− // is scrolled away from the bottom, cleared once they return (see the collector below).
756− var hasNewContent by remember { mutableStateOf(false) }
757−
758− val isPinnedToBottom by remember {
759− derivedStateOf {
760− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
761− // When a run is active, the LazyColumn has one trailing "__typing"
762− // item after the last list item. Account for it so "pinned to bottom"
763− // includes the working indicator — otherwise the pin check targets
764− // listItems.lastIndex, the typing row sits just below the viewport,
765− // and the user never sees the progress indicator even when pinned.
766− val items = currentListItems
767− val effectiveLast = if (running) items.size else items.lastIndex
768− lastVisible >= effectiveLast || items.isEmpty()
769− }
770− }
771−
772− // Jump to the newest message once, when the conversation first loads. Guarded by a
773− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
774− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
775− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
776− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
777− LaunchedEffect(listItems.isNotEmpty()) {
778− if (listItems.isNotEmpty() && !didInitialScroll) {
779− // When a run is active the LazyColumn has a trailing "__typing" row at
780− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
781− // running session lands truly pinned to bottom and streaming auto-scroll engages.
782− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
783− didInitialScroll = true
784− }
785− }
786−
787− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
788− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
789− // isPinnedToBottom check flips to false the instant you send — freezing
790− // auto-scroll. If the user was pinned to the last item just before the run
791− // began, bring the typing row into view so the pin (and streaming follow) is
792− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
793− // recomputed to false by now) so we don't scroll when the user had scrolled up.
794− LaunchedEffect(running) {
795− if (running && listItems.isNotEmpty()) {
796− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
797− if (lastVisible >= listItems.lastIndex) {
798− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
799− }
800− }
801− }
802−
803− LaunchedEffect(Unit) {
804− var prevSize = 0
805− var prevLen = 0
806− snapshotFlow {
807− // Track list size + the streaming length of the last part so we auto-scroll
808− // as content arrives, plus the pinned flag. A small data class with primitive
809− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
810− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
811− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
812− // and tool output — not just TextPart — keeps a pinned view following a long
813− // reasoning/tool block while it streams (previously it stalled at 0).
814− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
815− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
816− }.collect { signal ->
817− if (signal.pinned) {
818− // Back at the bottom: clear the new-content badge.
819− hasNewContent = false
820− if (signal.size > 0) {
821− // Scroll to the effective last index, including the trailing
822− // "__typing" row when a run is active so the working indicator
823− // is brought into view (not just the last message).
824− val items = currentListItems
825− val target = if (running) items.size else items.lastIndex
826− listState.scrollToItem(target)
827− }
828− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
829− // Content arrived while scrolled up — badge the jump-to-latest FAB.
830− hasNewContent = true
831− }
832− prevSize = signal.size
833− prevLen = signal.lastTextLength
834− }
835− }
836−
837− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
838− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
839− // content padding accounts for the bottomBar's raised height, so the message
840− // list is already above the keyboard. Adding imePadding here would double-apply
841− // the IME inset and push messages too far up.
842− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
843− if (activeConnection == null) {
844− Column(
845− modifier = Modifier.align(Alignment.Center).padding(24.dp),
846− horizontalAlignment = Alignment.CenterHorizontally,
847− ) {
848− Text(
849− stringResource(R.string.not_connected),
850− color = MaterialTheme.colorScheme.error,
851− )
852− Spacer(Modifier.size(12.dp))
853− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
854− if (reconnecting) {
855− CircularProgressIndicator(
856− Modifier.size(20.dp),
857− color = MaterialTheme.colorScheme.onPrimary,
858− strokeWidth = 2.dp,
859− )
860− } else {
861− Text(stringResource(R.string.reconnect))
862− }
863− }
864− }
865− } else {
866− ConnectionBanner(
867− state = connectionState,
868− modifier = Modifier.align(Alignment.TopCenter),
869− isOnline = isOnline,
870− // On a hard failure, retry by forcing an SSE reconnect (which
871− // re-seeds from REST). refreshMessages is the right recovery path
872− // when the connection is present but the stream died; reconnect()
873− // is the path when the whole connection is gone (handled by the
874− // separate "Not connected" state below).
875− onRetry = { vm.refreshMessages() },
876− )
877− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
878− // recovery is a swipe away everywhere — not just when the message list is
879− // populated. Previously PTR was only around the populated list, leaving the
880− // error/loading states reachable only via a button tap.
881− PullToRefreshBox(
882− isRefreshing = refreshing,
883− onRefresh = { vm.refreshMessages() },
884− // Cap width and center on large screens for readability — full-width
885− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
886− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
887− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
888− ) {
889− // Reserve top space when the banner is visible so it doesn't overlap the
890− // first message / state content.
891− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
892− val topPad = if (bannerVisible) 44.dp else 16.dp
893− if (loading && messages.isEmpty()) {
894− val loadingLabel = stringResource(R.string.loading)
895− // Attach the a11y label directly to the spinner (a detached zero-size Box
896− // isn't reliably focused/announced by TalkBack) and show a visible label so
897− // sighted users get "Loading…" rather than a bare spinner.
898− Column(
899− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
900− horizontalAlignment = Alignment.CenterHorizontally,
901− ) {
902− CircularProgressIndicator(
903− Modifier.semantics { contentDescription = loadingLabel },
904− strokeWidth = 2.dp,
905− )
906− Spacer(Modifier.size(8.dp))
907− Text(
908− loadingLabel,
909− style = MaterialTheme.typography.labelMedium,
910− color = MaterialTheme.colorScheme.onSurfaceVariant,
911− )
912− }
913− } else if (loadError && messages.isEmpty()) {
914− // A failed load with nothing to show. Distinct from the empty
915− // conversation state below — the conversation isn't empty, it
916− // failed to load, and offering "Start a conversation" here is
917− // misleading. Offer a Retry instead, mirroring SessionListScreen.
918− Column(
919− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
920− horizontalAlignment = Alignment.CenterHorizontally,
921− ) {
922− Text(
923− stringResource(R.string.load_messages_failed),
924− color = MaterialTheme.colorScheme.error,
925− )
926− Spacer(Modifier.size(12.dp))
927− Button(onClick = { vm.refreshMessages() }) {
928− Text(stringResource(R.string.retry))
929− }
930− }
931− } else if (messages.isEmpty() && running) {
932− // A run just started but no parts have arrived yet — the empty
933− // list with only the trailing "working…" row looks broken, so
934− // surface a clear starting state until the first part streams in.
935− val workingText = stringResource(R.string.working)
936− Column(
937− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
938− horizontalAlignment = Alignment.CenterHorizontally,
939− ) {
940− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
941− Spacer(Modifier.size(12.dp))
942− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
943− }
944− } else if (messages.isEmpty()) {
945− EmptyConversation(
946− onSuggestion = {
947− vm.updateDraft(it)
948− // Focus the input so the user can edit the suggestion before
949− // sending, instead of having to manually tap the field.
950− runCatching { inputFocusRequester.requestFocus() }
951− },
952− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
953− )
954− } else {
955− val lastMessageId = messages.lastOrNull()?.info?.id
956− // Text-to-speech for reading assistant replies aloud; shuts down when the
957− // message list leaves composition.
958− val tts = rememberTtsController()
959− val speakingMessageId by tts.speakingId
960− LazyColumn(
961− state = listState,
962− modifier = Modifier.fillMaxSize(),
963− // Extra bottom padding reserves room for the jump-to-latest FAB so it
964− // never floats over the last message. Top padding grows when the
965− // connection banner is visible so it doesn't overlap the first message.
966− contentPadding = PaddingValues(
967− start = 16.dp,
968− top = topPad,
969− end = 16.dp,
970− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
971− ),
972− verticalArrangement = Arrangement.spacedBy(16.dp),
973− ) {
974− items(
975− items = listItems,
976− key = { it.key },
977− contentType = { it.contentType },
978− ) { item ->
979− // Default placement animation so inserted/moved rows glide in. Kept to the
980− // default (no heavy fade spec) so a streaming message growing in place
981− // doesn't animate on every token.
982− Box(Modifier.animateItem()) {
983− when (item) {
984− is MessageListItem.Separator -> DateSeparator(item.label)
985− is MessageListItem.Message -> {
986− val message = item.message
987− // Only the last (streaming) message needs isRunning — it drives the
988− // reasoning-block spinner. Passing the live flag to every bubble
989− // makes all visible messages recompose whenever a run starts or stops.
990− val modelLabel = remember(message.info, models) {
991− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
992− ?.let { resolveModelLabel(it, models) }
993− }
994− MessageBubble(
995− message,
996− isRunning = running && message.info.id == lastMessageId,
997− imageContext = imageContext,
998− modelLabel = modelLabel,
999− onOpenFile = onOpenFile,
1000− onRevert = { vm.revertTo(message.info.id) },
1001− onEdit = { text ->
1002− // editMessage reverts to before this message (hiding it and
1003− // everything after); the revert banner surfaces the rewind
1004− // with an Undo. Focus + scroll the composer into view like the
1005− // Quote action so the prefilled draft isn't off-screen.
1006− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1007− vm.editMessage(message.info.id, text)
1008− runCatching { inputFocusRequester.requestFocus() }
1009− contentScope.launch {
1010− runCatchingCancellable {
1011− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1012− }
1013− }
1014− },
1015− onSpeak = { text -> tts.toggle(message.info.id, text) },
1016− isSpeaking = message.info.id == speakingMessageId,
1017− onQuote = { text ->
1018− vm.quoteReply(text)
1019− runCatching { inputFocusRequester.requestFocus() }
1020− },
1021− onBranch = { text -> vm.branchFrom(text) },
1022− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1023− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1024− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1025− },
1026− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1027− onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1028− if (failed) {
1029− { vm.retryOptimisticMessage(message.info.id) }
1030− } else {
1031− null
1032− }
1033− },
1034− onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1035− if (failed) {
1036− { vm.dismissOptimistic(message.info.id) }
1037− } else {
1038− null
1039− }
1040− },
1041− )
1042− }
1043− }
1044− }
1045− }
1046− if (running) {
1047− item(key = "__typing") {
1048− val workingText = stringResource(R.string.working)
1049− Row(
1050− verticalAlignment = Alignment.CenterVertically,
1051− modifier = Modifier.semantics {
1052− contentDescription = workingText
1053− },
1054− ) {
1055− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1056− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1057− }
1058− }
1059− }
1060− }
1061− }
1062− }
1063− // Jump-to-latest affordance when the user has scrolled away during a stream.
1064− AnimatedVisibility(
1065− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1066− modifier = Modifier.align(Alignment.BottomEnd),
1067− ) {
1068− // Badge the FAB when new content arrived while the user was scrolled up, so
1069− // they know there's something new to jump to (cleared once back at bottom).
1070− BadgedBox(
1071− badge = {
1072− if (hasNewContent) {
1073− val newContentLabel = stringResource(R.string.new_messages)
1074− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel })
1075− }
1076− },
1077− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1078− ) {
1079− ExtendedFloatingActionButton(
1080− onClick = {
1081− hasNewContent = false
1082− if (listItems.isNotEmpty()) {
1083− // Scroll to the effective last index, including the
1084− // trailing "__typing" row when a run is active.
1085− val target = if (running) listItems.size else listItems.lastIndex
1086− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1087− }
1088− },
1089− // contentDescription null: the visible "Latest" text already labels
1090− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1091− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1092− text = { Text(stringResource(R.string.latest)) },
1093− )
1094− }
1095− }
1096− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1097− // user has scrolled down past the first few messages. Symmetric to the
1098− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1099− val scrolledDown by remember {
1100− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1101− }
1102− AnimatedVisibility(
1103− visible = scrolledDown && listItems.size > 4,
1104− modifier = Modifier.align(Alignment.BottomStart),
1105− ) {
1106− SmallFloatingActionButton(
1107− onClick = {
1108− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1109− },
1110− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1111− ) {
1112− Icon(
1113− Icons.Filled.KeyboardArrowUp,
1114− contentDescription = stringResource(R.string.scroll_to_top),
1115− )
1116− }
1117− }
1118− }
1119− }
1120− }
1121− }
1122−
1123− if (showExitConfirm) {
1124− AlertDialog(
1125− onDismissRequest = { showExitConfirm = false },
1126− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1127− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1128− confirmButton = {
1129− TextButton(onClick = {
1130− showExitConfirm = false
1131− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1132− vm.abort()
1133− onBack()
1134− }) { Text(stringResource(R.string.stop_and_exit)) }
1135− },
1136− dismissButton = {
1137− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1138− },
1139− )
1140− }
1141−
1142− if (showStopConfirm) {
1143− AlertDialog(
1144− onDismissRequest = { showStopConfirm = false },
1145− title = { Text(stringResource(R.string.stop_run_title)) },
1146− text = { Text(stringResource(R.string.stop_run_text)) },
1147− confirmButton = {
1148− TextButton(onClick = {
1149− showStopConfirm = false
1150− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1151− vm.abort()
1152− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1153− },
1154− dismissButton = {
1155− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1156− },
1157− )
1158− }
1159−
1160− if (showSummarizeConfirm) {
1161− AlertDialog(
1162− onDismissRequest = { showSummarizeConfirm = false },
1163− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1164− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1165− confirmButton = {
1166− TextButton(onClick = {
1167− showSummarizeConfirm = false
1168− vm.summarize()
1169− }) { Text(stringResource(R.string.action_continue)) }
1170− },
1171− dismissButton = {
1172− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1173− },
1174− )
1175− }
1176−
1177− if (showInitConfirm) {
1178− AlertDialog(
1179− onDismissRequest = { showInitConfirm = false },
1180− title = { Text(stringResource(R.string.init_confirm_title)) },
1181− text = { Text(stringResource(R.string.init_confirm_text)) },
1182− confirmButton = {
1183− TextButton(onClick = {
1184− showInitConfirm = false
1185− vm.initProject()
1186− }) { Text(stringResource(R.string.action_continue)) }
1187− },
1188− dismissButton = {
1189− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1190− },
1191− )
1192− }
1193−
1194− if (showRenameDialog) {
1195− RenameSessionChatDialog(
1196− initialTitle = sessionTitle ?: "",
1197− onDismiss = { showRenameDialog = false },
1198− onConfirm = { newName ->
1199− showRenameDialog = false
1200− vm.renameSession(newName)
1201− },
1202− )
1203− }
1204−
1205− if (showDeleteDialog) {
1206− AlertDialog(
1207− onDismissRequest = { showDeleteDialog = false },
1208− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1209− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1210− confirmButton = {
1211− TextButton(onClick = {
1212− showDeleteDialog = false
1213− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1214− vm.deleteSession()
1215− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1216− },
1217− dismissButton = {
1218− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1219− },
1220− )
1221− }
1222−
1223− if (showShellDialog) {
1224− ShellCommandDialog(
1225− onDismiss = { showShellDialog = false },
1226− onRun = { cmd ->
1227− showShellDialog = false
1228− vm.runShell(cmd)
1229− },
1230− )
1231− }
1232−
1233− if (showModelPicker) {
1234− ModelPickerSheet(
1235− options = models,
1236− selected = selectedModel,
1237− loading = modelsLoading,
1238− error = modelsError,
1239− onSelect = { vm.selectModel(it) },
1240− onRetry = { vm.reloadModels() },
1241− onDismiss = { showModelPicker = false },
1242− )
1243− }
1244−
1245− if (showAgentPicker) {
1246− AgentPickerSheet(
1247− agents = agents,
1248− selected = selectedAgent,
1249− loading = agentsLoading,
1250− error = agentsError,
1251− onSelect = { vm.selectAgent(it?.name) },
1252− onRetry = { vm.reloadAgents() },
1253− onDismiss = { showAgentPicker = false },
1254− )
1255− }
1256−
1257− if (showCommandPicker) {
1258− CommandPickerSheet(
1259− commands = commands,
1260− loading = commandsLoading,
1261− error = commandsError,
1262− onSelect = { vm.runCommand(it) },
1263− onRetry = { vm.reloadCommands() },
1264− onDismiss = { showCommandPicker = false },
1265− )
1266− }
1267−
1268− pendingPermission?.let { permission ->
1269− PermissionDialog(
1270− permission = permission,
1271− position = permissionProgress.position,
1272− total = permissionProgress.total,
1273− onRespond = { response -> vm.respondPermission(permission, response) },
1274− )
1275− }
1276−
1277− if (showPalette) {
1278− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1279− }
1280−}
1281−
1282−@Composable
1283−private fun ChatInputBar(
1284− value: String,
1285− onValueChange: (String) -> Unit,
1286− running: Boolean,
1287− aborting: Boolean,
1288− enabled: Boolean,
1289− sendOnEnter: Boolean,
1290− onSend: () -> Unit,
1291− onAbort: () -> Unit,
1292− queuedFollowUp: String?,
1293− onQueueFollowUp: (String) -> Unit,
1294− onCancelQueue: () -> Unit,
1295− focusRequester: androidx.compose.ui.focus.FocusRequester,
1296− attachments: List<PendingAttachment>,
1297− staging: Boolean,
1298− onRemoveAttachment: (String) -> Unit,
1299− onPickPhoto: () -> Unit,
1300− onPickFile: () -> Unit,
1301− onCamera: () -> Unit,
1302− onVoice: () -> Unit,
1303−) {
1304− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1305− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1306− // Full-screen editor state: opened when the user wants more space for a long prompt.
1307− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1308− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1309− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1310− // A queued follow-up replaces the Stop button with a "queued" chip so the
1311− // user sees their message will be sent when the run finishes, and can cancel.
1312− if (queuedFollowUp != null) {
1313− Row(
1314− modifier = Modifier
1315− .fillMaxWidth()
1316− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1317− verticalAlignment = Alignment.CenterVertically,
1318− ) {
1319− Column(modifier = Modifier.weight(1f)) {
1320− Text(
1321− stringResource(R.string.queued),
1322− style = MaterialTheme.typography.labelSmall,
1323− color = MaterialTheme.colorScheme.onSurfaceVariant,
1324− )
1325− Text(
1326− queuedFollowUp,
1327− style = MaterialTheme.typography.bodySmall,
1328− color = MaterialTheme.colorScheme.onSurfaceVariant,
1329− maxLines = 1,
1330− overflow = TextOverflow.Ellipsis,
1331− )
1332− }
1333− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1334− Text(stringResource(R.string.cancel))
1335− }
1336− }
1337− }
1338− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1339− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1340− Row(
1341− modifier = Modifier.fillMaxWidth().padding(8.dp),
1342− verticalAlignment = Alignment.Bottom,
1343− ) {
1344− // Attach menu: photo picker, camera, or any file.
1345− var showAttachMenu by remember { mutableStateOf(false) }
1346− Box {
1347− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1348− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1349− }
1350− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1351− DropdownMenuItem(
1352− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1353− text = { Text(stringResource(R.string.attach_photo)) },
1354− onClick = { showAttachMenu = false; onPickPhoto() },
1355− )
1356− DropdownMenuItem(
1357− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1358− text = { Text(stringResource(R.string.attach_camera)) },
1359− onClick = { showAttachMenu = false; onCamera() },
1360− )
1361− DropdownMenuItem(
1362− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1363− text = { Text(stringResource(R.string.attach_file)) },
1364− onClick = { showAttachMenu = false; onPickFile() },
1365− )
1366− }
1367− }
1368− // Voice dictation: appends recognized speech to the draft.
1369− IconButton(onClick = onVoice, enabled = enabled) {
1370− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1371− }
1372− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1373− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1374− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1375− }
1376− OutlinedTextField(
1377− value = value,
1378− onValueChange = { v ->
1379− // Cap input length so a huge paste can't stall the UI. Shares are
1380− // capped separately in MainActivity; this guards typed/pasted drafts.
1381− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1382− },
1383− modifier = Modifier
1384− .weight(1f)
1385− .focusRequester(focusRequester)
1386− .testTag("chat_input")
1387− .onPreviewKeyEvent { event ->
1388− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1389− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1390− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1391− val send = enterShouldSend(
1392− enabled = enabled,
1393− hasContent = hasContent,
1394− sendOnEnter = sendOnEnter,
1395− shift = event.isShiftPressed,
1396− ctrl = event.isCtrlPressed,
1397− )
1398− if (send) {
1399− if (running) onQueueFollowUp(value) else onSend()
1400− true
1401− } else {
1402− false
1403− }
1404− },
1405− // While a run is active a typed message only queues (sends after the run), so
1406− // the placeholder says so instead of the plain "Message…".
1407− placeholder = {
1408− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1409− },
1410− enabled = enabled,
1411− maxLines = 6,
1412− // Show a "N / max" countdown once the draft crosses a high fraction of
1413− // the cap, so the user knows a paste is about to be truncated instead
1414− // of being silently cut off. Hidden for normal short prompts to avoid
1415− // clutter under a typical one-line message.
1416− supportingText = {
1417− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1418− if (value.length >= threshold) {
1419− Text(
1420− stringResource(
1421− R.string.draft_chars_remaining,
1422− NetworkConfig.maxDraftLengthChars - value.length,
1423− NetworkConfig.maxDraftLengthChars,
1424− ),
1425− style = MaterialTheme.typography.labelSmall,
1426− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1427− else MaterialTheme.colorScheme.onSurfaceVariant,
1428− )
1429− }
1430− },
1431− keyboardOptions = KeyboardOptions(
1432− // When "Send on Enter" is on, expose ImeAction.Send so the soft
1433− // keyboard shows a send key — matching the setting's intent and
1434− // giving touch-only users a keyboard send affordance. When off,
1435− // ImeAction.Default keeps the enter/newline key for multi-line input.
1436− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1437− capitalization = KeyboardCapitalization.Sentences,
1438− ),
1439− keyboardActions = KeyboardActions(
1440− onSend = {
1441− if (enabled && hasContent) onSend()
1442− },
1443− ),
1444− )
1445− ComposerTrailingButton(
1446− running = running,
1447− aborting = aborting,
1448− canSend = enabled && hasContent,
1449− canQueue = enabled && value.isNotBlank(),
1450− onSend = onSend,
1451− onAbort = onAbort,
1452− onQueue = { onQueueFollowUp(value) },
1453− )
1454− }
1455− }
1456− if (showFullScreenEditor) {
1457− FullScreenEditor(
1458− value = value,
1459− onValueChange = onValueChange,
1460− onDismiss = { showFullScreenEditor = false },
1461− onSend = { showFullScreenEditor = false; onSend() },
1462− canSend = enabled && hasContent,
1463− )
1464− }
1465− }
1466−}
1467−
1468−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1469− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1470−@OptIn(ExperimentalMaterial3Api::class)
1471−@Composable
1472−private fun FullScreenEditor(
1473− value: String,
1474− onValueChange: (String) -> Unit,
1475− onDismiss: () -> Unit,
1476− onSend: () -> Unit,
1477− canSend: Boolean,
1478−) {
1479− androidx.compose.ui.window.Dialog(
1480− onDismissRequest = onDismiss,
1481− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1482− ) {
1483− Scaffold(
1484− topBar = {
1485− androidx.compose.material3.TopAppBar(
1486− title = { Text(stringResource(R.string.message_placeholder)) },
1487− navigationIcon = {
1488− androidx.compose.material3.TextButton(onClick = onDismiss) {
1489− Text(stringResource(R.string.collapse_editor))
1490− }
1491− },
1492− )
1493− },
1494− bottomBar = {
1495− Surface(tonalElevation = 3.dp) {
1496− Row(
1497− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1498− horizontalArrangement = Arrangement.End,
1499− ) {
1500− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1501− Text(stringResource(R.string.send))
1502− }
1503− }
1504− }
1505− },
1506− ) { padding ->
1507− OutlinedTextField(
1508− value = value,
1509− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1510− modifier = Modifier.fillMaxSize().padding(padding),
1511− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1512− maxLines = Int.MAX_VALUE,
1513− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1514− )
1515− }
1516− }
1517−}
1518−
1519−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1520− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1521−private fun enterShouldSend(
1522− enabled: Boolean,
1523− hasContent: Boolean,
1524− sendOnEnter: Boolean,
1525− shift: Boolean,
1526− ctrl: Boolean,
1527−): Boolean = when {
1528− !enabled || !hasContent -> false
1529− sendOnEnter -> !shift
1530− else -> ctrl
1531−}
1532−
1533−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1534− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1535− * [ChatInputBar] stays under the complexity threshold. */
1536−@Composable
1537−private fun ComposerTrailingButton(
1538− running: Boolean,
1539− aborting: Boolean,
1540− canSend: Boolean,
1541− canQueue: Boolean,
1542− onSend: () -> Unit,
1543− onAbort: () -> Unit,
1544− onQueue: () -> Unit,
1545−) {
1546− if (running) {
1547− Row(verticalAlignment = Alignment.CenterVertically) {
1548− // While a run is active the trailing action is Stop, so the only send affordance is
1549− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1550− // That leaves a touch-only user with the setting off no way to queue a follow-up
1551− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1552− // there's typed TEXT so queuing is always reachable, without changing the user's
1553− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1554− // canSend, which is also true for an attachment-only composer — because queuing "" just
1555− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1556− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1557− if (canQueue) {
1558− IconButton(
1559− onClick = onQueue,
1560− modifier = Modifier.testTag("queue_button"),
1561− ) {
1562− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1563− // icon (which can be read as "snooze" or "later"), and isn't confused with
1564− // the Send action sitting right beside the Stop button.
1565− Icon(
1566− Icons.AutoMirrored.Filled.PlaylistAdd,
1567− contentDescription = stringResource(R.string.queue_followup),
1568− )
1569− }
1570− }
1571− // Show a spinner while the abort REST call is in flight so the user sees the stop
1572− // was sent, and disable to prevent a double-tap.
1573− IconButton(
1574− onClick = onAbort,
1575− enabled = !aborting,
1576− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1577− ) {
1578− if (aborting) {
1579− val stopLabel = stringResource(R.string.stop)
1580− CircularProgressIndicator(
1581− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1582− strokeWidth = 2.dp,
1583− )
1584− } else {
1585− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1586− }
1587− }
1588− }
1589− } else {
1590− IconButton(
1591− onClick = onSend,
1592− enabled = canSend,
1593− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1594− ) {
1595− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1596− }
1597− }
1598−}
1599−
1600−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1601−@Composable
1602−private fun EmptyConversation(
1603− onSuggestion: (String) -> Unit,
1604− modifier: Modifier = Modifier,
1605−) {
1606− // A few example prompts so a first-time user has a one-tap path to their first
1607− // message instead of staring at a blank input. Tapping a chip fills the draft
1608− // (without sending) so the user can edit it before sending.
1609− val suggestions = remember {
1610− listOf(
1611− R.string.empty_chat_suggest_1,
1612− R.string.empty_chat_suggest_2,
1613− R.string.empty_chat_suggest_3,
1614− )
1615− }
1616− Column(
1617− modifier = modifier.padding(32.dp),
1618− horizontalAlignment = Alignment.CenterHorizontally,
1619− ) {
1620− Icon(
1621− Icons.Filled.AutoAwesome,
1622− contentDescription = null,
1623− modifier = Modifier.size(48.dp),
1624− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1625− )
1626− Spacer(Modifier.size(16.dp))
1627− Text(
1628− stringResource(R.string.empty_chat_title),
1629− style = MaterialTheme.typography.titleMedium,
1630− )
1631− Spacer(Modifier.size(8.dp))
1632− Text(
1633− stringResource(R.string.empty_chat_hint),
1634− style = MaterialTheme.typography.bodyMedium,
1635− color = MaterialTheme.colorScheme.onSurfaceVariant,
1636− )
1637− Spacer(Modifier.size(20.dp))
1638− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
1639− // so a longer localized prompt doesn't push the chips off-screen on a phone.
1640− FlowRow(
1641− modifier = Modifier.fillMaxWidth(),
1642− horizontalArrangement = Arrangement.spacedBy(8.dp),
1643− verticalArrangement = Arrangement.spacedBy(8.dp),
1644− ) {
1645− suggestions.forEach { resId ->
1646− val text = stringResource(resId)
1647− androidx.compose.material3.AssistChip(
1648− onClick = { onSuggestion(text) },
1649− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
1650− )
1651− }
1652− }
1653− }
1654−}
1655−
1656−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
1657−@Composable
1658−private fun RevertBanner(onUndo: () -> Unit) {
1659− Surface(
1660− color = MaterialTheme.colorScheme.tertiaryContainer,
1661− tonalElevation = 2.dp,
1662− modifier = Modifier.fillMaxWidth(),
1663− ) {
1664− Row(
1665− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1666− verticalAlignment = Alignment.CenterVertically,
1667− horizontalArrangement = Arrangement.SpaceBetween,
1668− ) {
1669− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1670− Icon(
1671− Icons.Filled.Restore,
1672− contentDescription = null,
1673− tint = MaterialTheme.colorScheme.onTertiaryContainer,
1674− modifier = Modifier.size(18.dp),
1675− )
1676− Text(
1677− stringResource(R.string.reverted_banner),
1678− style = MaterialTheme.typography.bodySmall,
1679− color = MaterialTheme.colorScheme.onTertiaryContainer,
1680− modifier = Modifier.padding(start = 8.dp),
1681− )
1682− }
1683− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
1684− }
1685− }
1686−}
1687−
1688−/** A banner shown while messages composed offline are queued in the outbox, with a
1689− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
1690−@Composable
1691−private fun OutboxBanner(
1692− count: Int,
1693− sending: Boolean,
1694− onFlush: () -> Unit,
1695− onDiscard: () -> Unit,
1696−) {
1697− Surface(
1698− color = MaterialTheme.colorScheme.secondaryContainer,
1699− tonalElevation = 2.dp,
1700− modifier = Modifier.fillMaxWidth(),
1701− ) {
1702− Row(
1703− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
1704− verticalAlignment = Alignment.CenterVertically,
1705− horizontalArrangement = Arrangement.SpaceBetween,
1706− ) {
1707− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
1708− if (sending) {
1709− CircularProgressIndicator(
1710− Modifier.size(16.dp),
1711− strokeWidth = 2.dp,
1712− color = MaterialTheme.colorScheme.onSecondaryContainer,
1713− )
1714− Spacer(Modifier.size(8.dp))
1715− }
1716− Text(
1717− if (sending) {
1718− stringResource(R.string.outbox_sending)
1719− } else {
1720− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
1721− stringResource(res, count)
1722− },
1723− style = MaterialTheme.typography.bodySmall,
1724− color = MaterialTheme.colorScheme.onSecondaryContainer,
1725− )
1726− }
1727− if (!sending) {
1728− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
1729− TextButton(onClick = onDiscard) {
1730− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
1731− }
1732− }
1733− }
1734− }
1735−}
1736−
1737−/** Prompt for a one-off shell command to run in the session's worktree. */
1738−@Composable
1739−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
1740− var command by rememberSaveable { mutableStateOf("") }
1741− AlertDialog(
1742− onDismissRequest = onDismiss,
1743− title = { Text(stringResource(R.string.run_shell_command)) },
1744− text = {
1745− OutlinedTextField(
1746− value = command,
1747− onValueChange = { command = it },
1748− modifier = Modifier.fillMaxWidth(),
1749− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
1750− label = { Text(stringResource(R.string.shell_command_label)) },
1751− singleLine = true,
1752− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1753− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
1754− )
1755− },
1756− confirmButton = {
1757− TextButton(
1758− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
1759− enabled = command.isNotBlank(),
1760− ) { Text(stringResource(R.string.run)) }
1761− },
1762− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
1763− )
1764−}
1765−
1766−/**
1767− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
1768− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
1769− * equality is structural so `snapshotFlow` emits only when something relevant changes.
1770− */
1771−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
1772−
1773−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
1774− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
1775− * streaming, not just plain assistant text. O(1). */
1776−private fun streamingContentLength(part: Part?): Int = when (part) {
1777− is TextPart -> part.text.length
1778− is ReasoningPart -> part.text.length
1779− is ToolPart -> when (val st = part.state) {
1780− is ToolCompleted -> st.output?.length ?: 0
1781− is ToolError -> st.error?.length ?: 0
1782− is ToolRunning -> st.title?.length ?: 0
1783− else -> 0
1784− }
1785− else -> 0
1786−}
1787−
1788−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
1789− * dialog but lives in the chat screen so the user can rename without backing out to
1790− * the list. Pre-filled with the current title; the cap matches the list dialog. */
1791−@Composable
1792−private fun RenameSessionChatDialog(
1793− initialTitle: String,
1794− onDismiss: () -> Unit,
1795− onConfirm: (String) -> Unit,
1796−) {
1797− // Seed the field once (no key input) so a later external title change — e.g. opencode
1798− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
1799− // doesn't re-initialize the box and discard the user's in-progress edit.
1800− var title by rememberSaveable { mutableStateOf(initialTitle) }
1801− AlertDialog(
1802− onDismissRequest = onDismiss,
1803− title = { Text(stringResource(R.string.rename_session_chat)) },
1804− text = {
1805− OutlinedTextField(
1806− value = title,
1807− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
1808− modifier = Modifier.fillMaxWidth(),
1809− placeholder = { Text(stringResource(R.string.session_title_hint)) },
1810− label = { Text(stringResource(R.string.rename_session_chat)) },
1811− singleLine = true,
1812− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
1813− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
1814− )
1815− },
1816− confirmButton = {
1817− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
1818− Text(stringResource(R.string.save))
1819− }
1820− },
1821− dismissButton = {
1822− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
1823− },
1824− )
1825−}
1826−
1827−/**
1828− * A single item in the chat message list — either a [Message] bubble or a day
1829− * [Separator] inserted before the first message of a new day. The separator shifts
1830− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
1831− * the [List] of these items (not `messages.size`/`lastIndex`).
1832− */
1833−private sealed interface MessageListItem {
1834− val key: Any
1835− val contentType: Any
1836−
1837− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
1838− override val contentType: Any get() = message.info::class
1839− }
1840−
1841− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
1842− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
1843− // can share a label (e.g. an untimestamped message — empty label — between two
1844− // same-day messages, or two untimestamped groups), and a label-only key would
1845− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
1846− // stable for a given message ordering so slots aren't needlessly recreated.
1847− override val key: Any get() = "sep_${ordinal}_$label"
1848− // Separators share a contentType so the LazyColumn can recycle their slots.
1849− override val contentType: Any get() = "separator"
1850− }
1851−}
1852−
1853−/**
1854− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
1855− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
1856− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
1857− * Messages with no timestamp are grouped under an empty-label separator only if they
1858− * start the list, so a server that omits timestamps doesn't suppress the first divider.
1859− *
1860− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
1861− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
1862− * labels; older days fall back to a locale-stable medium-date format.
1863− */
1864−private fun buildMessageListItems(
1865− messages: List<MessageWithParts>,
1866− todayLabel: String,
1867− yesterdayLabel: String,
1868−): List<MessageListItem> {
1869− if (messages.isEmpty()) return emptyList()
1870− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
1871− val dateFmt = mediumDateFormat()
1872− val result = ArrayList<MessageListItem>(messages.size + 4)
1873− val seenKeys = HashSet<String>(messages.size * 2)
1874− var lastDayKey: String? = null
1875− var sepOrdinal = 0
1876− var emptyIdOrdinal = 0
1877− var first = true
1878− for (message in messages) {
1879− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
1880− val dayKey = ts?.let { dayKey(it) } ?: ""
1881− // Emit a separator before the very first message (so a leading un-timestamped message
1882− // still gets the first divider, empty label and all), and thereafter only when crossing
1883− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
1884− // neither emits its own separator nor resets the day — otherwise a following same-day
1885− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
1886− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
1887− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
1888− }
1889− if (dayKey.isNotEmpty()) lastDayKey = dayKey
1890− first = false
1891− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
1892− // empty id — and the reducer intentionally keeps several such messages as distinct
1893− // holders — so give each a stable synthetic key and defensively de-collide any remaining
1894− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
1895− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
1896− if (!seenKeys.add(key)) {
1897− var suffix = 1
1898− while (!seenKeys.add("$key#$suffix")) suffix++
1899− key = "$key#$suffix"
1900− }
1901− result.add(MessageListItem.Message(message, key))
1902− }
1903− return result
1904−}
1905−
1906−/**
1907− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
1908− *
1909− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
1910− * whole `messages` list, which must stay so the live message's fresh parts render), so a
1911− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
1912− * every message on every token. Message timestamps are immutable once assigned, so we
1913− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
1914− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
1915− * thread during composition, so the coarse lock is uncontended.
1916− */
1917−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
1918− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
1919−}
1920−
1921−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
1922− dayKeyCache.getOrPut(epochMillis) {
1923− java.time.Instant.ofEpochMilli(epochMillis)
1924− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
1925− }
1926−}
1927−
1928−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
1929−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
1930−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
1931−private var cachedDateFmt: java.text.DateFormat? = null
1932−private var cachedDateFmtLocale: java.util.Locale? = null
1933−
1934−private fun mediumDateFormat(): java.text.DateFormat {
1935− val locale = java.util.Locale.getDefault()
1936− val existing = cachedDateFmt
1937− if (existing != null && cachedDateFmtLocale == locale) return existing
1938− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
1939− cachedDateFmt = it
1940− cachedDateFmtLocale = locale
1941− }
1942−}
1943−
1944−/**
1945− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
1946− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
1947− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
1948− * messages.
1949− */
1950−private fun dayLabel(
1951− dayKey: String,
1952− ts: Long,
1953− today: java.time.LocalDate,
1954− todayLabel: String,
1955− yesterdayLabel: String,
1956− dateFmt: java.text.DateFormat,
1957−): String {
1958− if (dayKey.isEmpty()) return ""
1959− val epochDay = dayKey.toLongOrNull() ?: return ""
1960− val date = java.time.LocalDate.ofEpochDay(epochDay)
1961− return when {
1962− date == today -> todayLabel
1963− date == today.minusDays(1) -> yesterdayLabel
1964− else -> dateFmt.format(java.util.Date(ts))
1965− }
1966−}
1967−
1968−/**
1969− * A centered day divider in the message list. Renders nothing for an empty label
1970− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
1971− */
1972−@Composable
1973−private fun DateSeparator(label: String) {
1974− if (label.isBlank()) return
1975− Row(
1976− modifier = Modifier.fillMaxWidth(),
1977− horizontalArrangement = Arrangement.Center,
1978− ) {
1979− Surface(
1980− color = MaterialTheme.colorScheme.surfaceVariant,
1981− shape = MaterialTheme.shapes.small,
1982− ) {
1983− Text(
1984− label,
1985− style = MaterialTheme.typography.labelSmall,
1986− color = MaterialTheme.colorScheme.onSurfaceVariant,
1987− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
1988− )
1989− }
1990− }
1991−}