@@ -1,3396 +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.animation.core.RepeatMode
15−import androidx.compose.animation.core.animateFloat
16−import androidx.compose.animation.core.infiniteRepeatable
17−import androidx.compose.animation.core.rememberInfiniteTransition
18−import androidx.compose.animation.core.tween
19−import androidx.compose.foundation.background
20−import androidx.compose.foundation.clickable
21−import androidx.compose.foundation.content.contentReceiver
22−import androidx.compose.foundation.layout.Arrangement
23−import androidx.compose.foundation.layout.Box
24−import androidx.compose.foundation.layout.Column
25−import androidx.compose.foundation.layout.FlowRow
26−import androidx.compose.foundation.layout.PaddingValues
27−import androidx.compose.foundation.layout.Row
28−import androidx.compose.foundation.layout.Spacer
29−import androidx.compose.foundation.layout.WindowInsets
30−import androidx.compose.foundation.layout.fillMaxSize
31−import androidx.compose.foundation.layout.fillMaxWidth
32−import androidx.compose.foundation.layout.heightIn
33−import androidx.compose.foundation.layout.height
34−import androidx.compose.foundation.layout.imePadding
35−import androidx.compose.foundation.layout.ime
36−import androidx.compose.foundation.layout.navigationBars
37−import androidx.compose.foundation.layout.padding
38−import androidx.compose.foundation.layout.size
39−import androidx.compose.foundation.layout.union
40−import androidx.compose.foundation.layout.widthIn
41−import androidx.compose.foundation.layout.windowInsetsPadding
42−import androidx.compose.foundation.layout.wrapContentWidth
43−import androidx.compose.foundation.lazy.LazyColumn
44−import androidx.compose.foundation.lazy.items
45−import androidx.compose.foundation.lazy.rememberLazyListState
46−import androidx.compose.foundation.shape.RoundedCornerShape
47−import androidx.compose.material.icons.Icons
48−import androidx.compose.material.icons.automirrored.filled.ArrowBack
49−import androidx.compose.material.icons.automirrored.filled.Send
50−import androidx.compose.material.icons.filled.ErrorOutline
51−import androidx.compose.material.icons.filled.Add
52−import androidx.compose.material.icons.filled.AutoAwesome
53−import androidx.compose.material.icons.filled.Delete
54−import androidx.compose.material.icons.filled.Description
55−import androidx.compose.material.icons.filled.Close
56−import androidx.compose.material.icons.filled.Edit
57−import androidx.compose.material.icons.filled.Expand
58−import androidx.compose.material.icons.filled.FormatQuote
59−import androidx.compose.material.icons.filled.ExpandLess
60−import androidx.compose.material.icons.filled.ExpandMore
61−import androidx.compose.material.icons.filled.Search
62−import androidx.compose.material.icons.filled.KeyboardArrowDown
63−import androidx.compose.material.icons.filled.KeyboardArrowUp
64−import androidx.compose.material.icons.filled.Mic
65−import androidx.compose.material.icons.filled.MoreVert
66−import androidx.compose.material.icons.filled.PhotoCamera
67−import androidx.compose.material.icons.filled.PhotoLibrary
68−import androidx.compose.material.icons.filled.Refresh
69−import androidx.compose.material.icons.filled.Restore
70−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
71−import androidx.compose.material.icons.automirrored.filled.Reply
72−import androidx.compose.material.icons.filled.Schedule
73−import androidx.compose.material.icons.filled.Stop
74−import androidx.compose.material3.AlertDialog
75−import androidx.compose.material3.Badge
76−import androidx.compose.material3.BadgedBox
77−import androidx.compose.material3.Button
78−import androidx.compose.material3.CircularProgressIndicator
79−import androidx.compose.material3.SmallFloatingActionButton
80−import androidx.compose.material3.DropdownMenu
81−import androidx.compose.material3.DropdownMenuItem
82−import androidx.compose.material3.ExperimentalMaterial3Api
83−import androidx.compose.material3.ExtendedFloatingActionButton
84−import androidx.compose.material3.FloatingActionButton
85−import androidx.compose.material3.Icon
86−import androidx.compose.material3.IconButton
87−import androidx.compose.material3.MaterialTheme
88−import androidx.compose.material3.OutlinedTextField
89−import androidx.compose.material3.Scaffold
90−import androidx.compose.material3.SnackbarDuration
91−import androidx.compose.material3.SwipeToDismissBox
92−import androidx.compose.material3.SwipeToDismissBoxValue
93−import androidx.compose.material3.rememberSwipeToDismissBoxState
94−import androidx.compose.material3.SnackbarHost
95−import androidx.compose.material3.SnackbarHostState
96−import androidx.compose.material3.SnackbarResult
97−import androidx.compose.material3.Surface
98−import androidx.compose.material3.Text
99−import androidx.compose.material3.TextButton
100−import androidx.compose.material3.TopAppBar
101−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
102−import androidx.compose.runtime.Composable
103−import androidx.compose.runtime.CompositionLocalProvider
104−import androidx.compose.runtime.DisposableEffect
105−import androidx.compose.runtime.LaunchedEffect
106−import androidx.compose.runtime.derivedStateOf
107−import androidx.compose.runtime.getValue
108−import androidx.compose.runtime.mutableIntStateOf
109−import androidx.compose.runtime.mutableLongStateOf
110−import androidx.compose.runtime.mutableStateOf
111−import androidx.compose.runtime.produceState
112−import androidx.compose.runtime.remember
113−import androidx.compose.runtime.rememberCoroutineScope
114−import androidx.compose.runtime.rememberUpdatedState
115−import androidx.compose.runtime.saveable.rememberSaveable
116−import androidx.compose.runtime.setValue
117−import androidx.compose.runtime.snapshotFlow
118−import androidx.compose.foundation.text.KeyboardActions
119−import androidx.compose.foundation.text.KeyboardOptions
120−import androidx.compose.ui.text.input.KeyboardCapitalization
121−import androidx.compose.ui.Alignment
122−import androidx.compose.ui.Modifier
123−import androidx.compose.ui.draw.alpha
124−import androidx.compose.ui.draw.clip
125−import androidx.compose.ui.focus.focusRequester
126−import androidx.compose.ui.input.key.Key
127−import androidx.compose.ui.input.key.KeyEventType
128−import androidx.compose.ui.input.key.isCtrlPressed
129−import androidx.compose.ui.input.key.isShiftPressed
130−import androidx.compose.ui.input.key.key
131−import androidx.compose.ui.input.key.onPreviewKeyEvent
132−import androidx.compose.ui.input.key.type
133−import androidx.compose.ui.layout.onSizeChanged
134−import androidx.compose.ui.platform.LocalContext
135−import androidx.compose.ui.platform.LocalDensity
136−import androidx.compose.ui.platform.LocalHapticFeedback
137−import androidx.compose.ui.platform.LocalLayoutDirection
138−import androidx.compose.ui.platform.LocalView
139−import androidx.compose.ui.platform.testTag
140−import androidx.compose.ui.unit.LayoutDirection
141−import androidx.compose.ui.res.pluralStringResource
142−import androidx.compose.ui.res.stringResource
143−import androidx.compose.ui.semantics.Role
144−import androidx.compose.ui.semantics.contentDescription
145−import androidx.compose.ui.semantics.heading
146−import androidx.compose.ui.semantics.liveRegion
147−import androidx.compose.ui.semantics.LiveRegionMode
148−import androidx.compose.ui.semantics.invisibleToUser
149−import androidx.compose.ui.semantics.semantics
150−import androidx.compose.ui.text.input.ImeAction
151−import androidx.compose.ui.text.style.TextOverflow
152−import androidx.compose.ui.unit.dp
153−import androidx.lifecycle.compose.collectAsStateWithLifecycle
154−import androidx.lifecycle.viewmodel.compose.viewModel
155−import kotlinx.coroutines.Dispatchers
156−import kotlinx.coroutines.coroutineScope
157−import kotlinx.coroutines.delay
158−import kotlinx.coroutines.flow.collectLatest
159−import kotlinx.coroutines.flow.distinctUntilChanged
160−import kotlinx.coroutines.flow.first
161−import kotlinx.coroutines.launch
162−import kotlinx.coroutines.withContext
163−import soy.iko.opencode.data.model.Part
164−import soy.iko.opencode.data.model.MessageWithParts
165−import soy.iko.opencode.data.model.AssistantMessage
166−import soy.iko.opencode.data.model.Command
167−import soy.iko.opencode.data.model.ReasoningPart
168−import soy.iko.opencode.data.model.TextPart
169−import soy.iko.opencode.data.model.ToolCompleted
170−import soy.iko.opencode.data.model.ToolError
171−import soy.iko.opencode.data.model.ToolPart
172−import soy.iko.opencode.data.model.ToolRunning
173−import soy.iko.opencode.data.model.FilePart
174−import soy.iko.opencode.data.model.sourcePath
175−import soy.iko.opencode.data.model.inputElement
176−import soy.iko.opencode.data.network.EventStreamClient
177−import soy.iko.opencode.data.network.NetworkConfig
178−import soy.iko.opencode.di.AppContainer
179−import soy.iko.opencode.R
180−import soy.iko.opencode.ui.components.CommandPalette
181−import soy.iko.opencode.ui.components.ConnectionBanner
182−import soy.iko.opencode.ui.components.DiffView
183−import soy.iko.opencode.ui.components.PaletteAction
184−import soy.iko.opencode.ui.components.LocalReducedMotion
185−import soy.iko.opencode.ui.components.LocalSearchHighlight
186−import soy.iko.opencode.ui.components.reducedMotionAnimateItem
187−import soy.iko.opencode.ui.components.copyToClipboard
188−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
189−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
190−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
191−import soy.iko.opencode.ui.components.showToast
192−import soy.iko.opencode.ui.components.toImageContext
193−import soy.iko.opencode.ui.vmFactory
194−import soy.iko.opencode.util.runCatchingCancellable
195−
196−// Optional message id to scroll to and briefly highlight on first load (from global search).
197−// Consumed once: after the message is scrolled into view and highlighted, the focus is
198−// cleared so subsequent recompositions don't re-trigger the scroll.
199−@OptIn(ExperimentalMaterial3Api::class)
200−@Composable
201−fun ChatScreen(
202− container: AppContainer,
203− sessionId: String,
204− onBack: () -> Unit,
205− onOpenFile: ((String) -> Unit)? = null,
206− onOpenSession: ((String) -> Unit)? = null,
207− focusMessageId: String? = null,
208− onEditProfile: ((String) -> Unit)? = null,
209−) {
210− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
211− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
212− val running by vm.running.collectAsStateWithLifecycle()
213− val streamInterrupted by vm.streamInterrupted.collectAsStateWithLifecycle()
214− val aborting by vm.aborting.collectAsStateWithLifecycle()
215− val loading by vm.loading.collectAsStateWithLifecycle()
216− val loadError by vm.loadError.collectAsStateWithLifecycle()
217− val loadErrorInline by vm.loadErrorInline.collectAsStateWithLifecycle()
218− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
219− val models by vm.models.collectAsStateWithLifecycle()
220− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
221− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
222− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
223− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
224− val reconnectAttempts by vm.reconnectAttempts.collectAsStateWithLifecycle()
225− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
226− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
227− val agents by vm.agents.collectAsStateWithLifecycle()
228− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
229− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
230− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
231− val commands by vm.commands.collectAsStateWithLifecycle()
232− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
233− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
234− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
235− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
236− val draft by vm.draft.collectAsStateWithLifecycle()
237− val pendingQuote by vm.pendingQuote.collectAsStateWithLifecycle()
238− val attachments by vm.attachments.collectAsStateWithLifecycle()
239− val reverted by vm.reverted.collectAsStateWithLifecycle()
240− val editing by vm.editing.collectAsStateWithLifecycle()
241− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
242− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
243− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
244− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
245− val preferredModelId by container.settingsStore.preferredModelId.collectAsStateWithLifecycle(initialValue = "")
246− val recentModelEntries by container.recentModelsStore.entries.collectAsStateWithLifecycle()
247− val compactSpacing by container.settingsStore.compactMessageSpacing.collectAsStateWithLifecycle(initialValue = false)
248− val notifPermission by container.settingsStore.notifPermission.collectAsStateWithLifecycle(initialValue = true)
249− val isOnline by container.isOnline.collectAsStateWithLifecycle()
250− val haptics = LocalHapticFeedback.current
251− val layoutDirection = LocalLayoutDirection.current
252− val scope = rememberCoroutineScope()
253− val shareContext = LocalContext.current
254− val defaultShareSubject = stringResource(R.string.share_subject)
255− val sessionLabel = stringResource(R.string.session)
256− val defaultModelLabel = stringResource(R.string.default_model)
257− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
258− buildString {
259− append(selectedModel?.modelLabel ?: defaultModelLabel)
260− selectedAgent?.let { append(" · $it") }
261− }
262− }
263−
264− // Connection profile (with auth) for rendering inline image attachments.
265− // Collect as state so a server switch recomposes the image context.
266− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
267− val imageContext = remember(activeConnection?.profile) {
268− activeConnection?.profile?.toImageContext()
269− }
270−
271− // Mark this session as read while the user is viewing it; clear on leave so new
272− // background activity can badge it again.
273− DisposableEffect(sessionId) {
274− container.setCurrentSession(sessionId)
275− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
276− }
277−
278− // Navigate away when the session is deleted via SSE so the user isn't left
279− // on a zombie screen showing a conversation that no longer exists. Surface a
280− // toast (not a snackbar) because the screen is about to be popped — a snackbar
281− // would be torn down before the user could read it, while a toast survives.
282− // Covers both SSE-driven deletion (deleted on another device) and a user-
283− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
284− // sets the same flag on success).
285− val deletedContext = LocalContext.current
286− LaunchedEffect(sessionDeleted) {
287− if (sessionDeleted) {
288− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
289− onBack()
290− }
291− }
292−
293− val snackbar = remember { SnackbarHostState() }
294− val retryLabel = stringResource(R.string.retry)
295− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
296− // Dedicated focus requester for the in-conversation search field. The overflow menu's
297− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
298− // (the composer), so typing went to the composer instead of the search field.
299− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
300− var showModelPicker by rememberSaveable { mutableStateOf(false) }
301− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
302− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
303− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
304− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
305− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
306− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
307− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
308− var showShellDialog by rememberSaveable { mutableStateOf(false) }
309− var showPalette by rememberSaveable { mutableStateOf(false) }
310− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
311− var searchActive by rememberSaveable { mutableStateOf(false) }
312− var chatSearch by rememberSaveable { mutableStateOf("") }
313− // Index of the currently-focused in-conversation search match (into the filtered list).
314− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
315− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
316− // required reading each message to find the term).
317− var searchPos by rememberSaveable { mutableIntStateOf(0) }
318− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
319− // a confirmation dialog (from both the overflow menu and the command palette).
320− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
321− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
322−
323− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
324− // action list doesn't need a Composable context. Actions map to the same handlers the
325− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
326− val paletteModelLabel = stringResource(R.string.palette_switch_model)
327− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
328− val paletteCommandLabel = stringResource(R.string.palette_run_command)
329− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
330− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
331− val paletteShellLabel = stringResource(R.string.run_shell_command)
332− val paletteActions = remember(
333− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
334− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
335− ) {
336− buildList {
337− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
338− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
339− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
340− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
341− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
342− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
343− }
344− }
345−
346− // Keep the screen awake while the agent is working in *this* session. The foreground
347− // service that holds process priority during a run is managed app-wide off
348− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
349− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
350− // SSE stream before the completion notification fires.
351− val currentView = LocalView.current
352− val appContext = LocalContext.current.applicationContext
353− DisposableEffect(running) {
354− currentView.keepScreenOn = running
355− onDispose { currentView.keepScreenOn = false }
356− }
357−
358− LaunchedEffect(Unit) {
359− vm.errorEvents.collect { event ->
360− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
361− // message-load failure) would silently re-submit the last prompt on tap.
362− val result = if (event.retryable) {
363− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
364− } else {
365− snackbar.showSnackbar(event.message)
366− }
367− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
368− }
369− }
370−
371− // Stop-undo: abort() emits the last-sent prompt here so this collector can show a
372− // "Stopped — Undo" snackbar. Tapping Undo re-sends the prompt, recovering an accidental
373− // Stop without a confirmation dialog (Stop now happens on first tap).
374− val undoStopLabel = stringResource(R.string.undo)
375− val stoppedLabel = stringResource(R.string.run_stopped_undo)
376− LaunchedEffect(Unit) {
377− vm.stopUndoEvents.collect { prompt ->
378− if (prompt != null) {
379− val result = snackbar.showSnackbar(message = stoppedLabel, actionLabel = undoStopLabel)
380− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.resendLastPrompt()
381− }
382− }
383− }
384−
385− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
386− // window on the container; show the snackbar over the conversation the user is viewing so
387− // they can cancel without being navigated to the session list first. If the window expires
388− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
389− //
390− // collectLatest (not collect): a serialized collect queues each snackbar behind the
391− // previous one's full window, so under a rapid re-delete (delete A, then delete the same
392− // session again, or a delete timed just after the first) the VM delete timer (started at
393− // emit time) fires before the second snackbar is ever shown — a dead Undo button.
394− // collectLatest cancels the current snackbar and shows the newest immediately, keeping its
395− // Undo window aligned with its timer. Tracking `pending` mirrors SessionListScreen: when a
396− // newer delete supersedes the prior snackbar mid-window, the prior session's deferred REST
397− // delete (still scheduled on the container's scope) would fire with no reachable Undo.
398− // Withdrawing it via cancelSessionDelete cancels the timer (no-op if it already fired), so
399− // no session is silently deleted without a chance to undo.
400− val undoLabel = stringResource(R.string.undo)
401− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
402− LaunchedEffect(Unit) {
403− var pending: String? = null
404− vm.deleteUndoEvents.collectLatest { id ->
405− pending?.let { vm.cancelSessionDelete(it) }
406− pending = id
407− coroutineScope {
408− val dismisser = launch {
409− delay(NetworkConfig.undoDeleteDelayMs)
410− snackbar.currentSnackbarData?.dismiss()
411− }
412− val result = snackbar.showSnackbar(
413− message = sessionDeletedLabel,
414− actionLabel = undoLabel,
415− duration = SnackbarDuration.Indefinite,
416− )
417− dismisser.cancel()
418− if (result == SnackbarResult.ActionPerformed) {
419− vm.cancelSessionDelete(id)
420− pending = null
421− }
422− }
423− }
424− }
425−
426− // --- Attachments, voice, and share-link plumbing ---
427− val attachFailedMsg = stringResource(R.string.attachment_failed)
428− val noCameraMsg = stringResource(R.string.no_camera_app)
429− val noVoiceMsg = stringResource(R.string.no_voice_app)
430− val voicePrompt = stringResource(R.string.voice_prompt)
431− val linkCopiedMsg = stringResource(R.string.link_copied)
432− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
433−
434− // Count of picks currently being read + base64-encoded off the main thread, so the
435− // composer can show a staging placeholder immediately (chips only materialize once done).
436− // Backed by the ViewModel (vm.stagingCount / vm.stagingFileTotal) so the staging state
437− // survives a configuration change: the encode work runs on viewModelScope (which
438− // survives rotation), so the counters must live on the VM too — remember { mutableStateOf
439− // } in the composable would reset to 0 on rotation and lose the staging chip mid-encode.
440− val stagingCount by vm.stagingCount.collectAsStateWithLifecycle()
441− val stagingFileTotal by vm.stagingFileTotal.collectAsStateWithLifecycle()
442−
443− // Convert each picked Uri to a base64 attachment on the VM's scope (survives rotation),
444− // honoring the per-prompt count cap and surfacing per-file errors via the VM's errorEvents.
445− fun stageUris(uris: List<Uri>) {
446− vm.stageUris(uris, appContext)
447− }
448−
449− val photoPicker = rememberLauncherForActivityResult(
450− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
451− ) { uris -> stageUris(uris) }
452−
453− val filePicker = rememberLauncherForActivityResult(
454− ActivityResultContracts.GetMultipleContents(),
455− ) { uris -> stageUris(uris) }
456−
457− // Uri survives a config change mid-capture so the TakePicture result still resolves.
458− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
459− val cameraLauncher = rememberLauncherForActivityResult(
460− ActivityResultContracts.TakePicture(),
461− ) { success ->
462− val uri = pendingCaptureUri
463− pendingCaptureUri = null
464− if (success && uri != null) stageUris(listOf(uri))
465− }
466−
467− val voiceLauncher = rememberLauncherForActivityResult(
468− ActivityResultContracts.StartActivityForResult(),
469− ) { result ->
470− if (result.resultCode == Activity.RESULT_OK) {
471− val spoken = result.data
472− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
473− ?.firstOrNull()
474− ?.takeIf { it.isNotBlank() }
475− if (spoken != null) {
476− // Append to the existing draft rather than replacing, so dictation adds to
477− // whatever the user already typed.
478− val current = vm.draft.value
479− val combined = if (current.isBlank()) spoken else "$current $spoken"
480− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
481− }
482− }
483− }
484−
485− fun launchCamera() {
486− val uri = newCameraCaptureUri(appContext)
487− if (uri == null) {
488− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
489− return
490− }
491− pendingCaptureUri = uri
492− runCatching { cameraLauncher.launch(uri) }
493− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
494− }
495−
496− fun launchVoice() {
497− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
498− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
499− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
500− }
501− runCatching { voiceLauncher.launch(intent) }
502− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
503− }
504−
505− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
506− LaunchedEffect(Unit) {
507− vm.shareLinkEvents.collect { url ->
508− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
509− snackbar.showSnackbar(linkCopiedMsg)
510− }
511− }
512−
513− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
514− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
515− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
516− // a dropped branch-navigation event in the gap. The lambda is wrapped in rememberUpdatedState
517− // so the Unit-keyed collector invokes the LATEST lambda instead of the one captured at first
518− // composition — a latent footgun if a future change makes onOpenSession depend on current
519− // Compose state (e.g. pane-aware routing). The collector itself is never cancelled, so no
520− // event is dropped.
521− val branchedMsg = stringResource(R.string.branch_created)
522− val currentOnOpenSession by rememberUpdatedState(onOpenSession)
523− LaunchedEffect(Unit) {
524− vm.branchEvents.collect { newId ->
525− showToast(shareContext, branchedMsg)
526− currentOnOpenSession?.invoke(newId)
527− }
528− }
529−
530− // Stage images shared into the app (via the system share sheet) as attachments.
531− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
532− // while this ChatScreen is already composed — which happens in two-pane mode, where the
533− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
534− // only fire on first composition. consumePendingSharedMedia() atomically drains the
535− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
536− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
537− LaunchedEffect(pendingSharedMedia) {
538− val shared = container.consumePendingSharedMedia()
539− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
540− }
541−
542− fun doSend() {
543− if (vm.send(draft)) {
544− // TextHandleMove (a light tick) is semantically right for a send commit;
545− // LongPress is reserved for long-press/swipe gestures.
546− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
547− }
548− }
549−
550− // The in-conversation search bar is an AnimatedVisibility overlay (not a Dialog/Dropdown),
551− // so it has no built-in back handling. Close it first on back press, before the exit
552− // confirmation or navigation-away can fire — standard Android "back closes the topmost
553− // overlay" behavior. Declared before the exit-confirm BackHandler so it takes precedence
554− // when both could be active (search open + a run in progress).
555− BackHandler(enabled = searchActive) {
556− searchActive = false
557− chatSearch = ""
558− }
559−
560− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker && !searchActive) { showExitConfirm = true }
561−
562− Scaffold(
563− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
564− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
565− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
566− // typing (and the composer's own Enter-to-send handling) is untouched.
567− modifier = Modifier.onPreviewKeyEvent { ev ->
568− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
569− when {
570− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
571− // Ctrl+F opens in-conversation search (the standard find shortcut), focusing
572− // the field so the user can type immediately.
573− ev.isCtrlPressed && ev.key == Key.F -> { searchActive = true; true }
574− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
575− ev.key == Key.Escape && searchActive -> { searchActive = false; chatSearch = ""; true }
576− ev.key == Key.Escape && running && !showExitConfirm -> {
577− vm.abort(); true
578− }
579− else -> false
580− }
581− },
582− topBar = {
583− TopAppBar(
584− title = {
585− val changeLabel = stringResource(R.string.change_model_agent)
586− // The subtitle reads "model · agent", so tapping the title offers *both*
587− // — a small menu picks which picker to open. Previously the tap went
588− // straight to the model picker, leaving the agent changeable only via
589− // the overflow menu despite the title implying otherwise.
590− Box {
591− Row(
592− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
593− // node; the click label rides on `clickable` (onClickLabel) instead of
594− // an explicit contentDescription, which would have SUPPRESSED the child
595− // Texts and announced only "Change model and agent".
596− modifier = Modifier
597− .clickable(
598− role = Role.Button,
599− onClickLabel = changeLabel,
600− ) { showTitleMenu = true }
601− .semantics(mergeDescendants = true) {},
602− verticalAlignment = Alignment.CenterVertically,
603− ) {
604− Column(modifier = Modifier.weight(1f, fill = false)) {
605− // maxLines=1 + Ellipsis so a long session title can't wrap and
606− // push the top bar to multiple lines, shifting the whole layout.
607− Text(
608− sessionTitle ?: sessionLabel,
609− maxLines = 1,
610− overflow = TextOverflow.Ellipsis,
611− )
612− Text(
613− subtitle,
614− style = MaterialTheme.typography.labelSmall,
615− color = MaterialTheme.colorScheme.onSurfaceVariant,
616− maxLines = 1,
617− overflow = TextOverflow.Ellipsis,
618− )
619− }
620− // Always show the affordance so the title reads as tappable even when
621− // the model catalog failed to load (models empty). Without it the title
622− // is indistinguishable from plain text and the pickers are effectively
623− // undiscoverable — and the dropdown items already disable themselves
624− // while a catalog is loading or unavailable.
625− Icon(
626− Icons.Filled.KeyboardArrowDown,
627− contentDescription = null,
628− tint = MaterialTheme.colorScheme.onSurfaceVariant,
629− modifier = Modifier.size(20.dp),
630− )
631− }
632− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
633− DropdownMenuItem(
634− text = { Text(stringResource(R.string.palette_switch_model)) },
635− enabled = !modelsLoading || models.isNotEmpty(),
636− onClick = { showTitleMenu = false; showModelPicker = true },
637− )
638− DropdownMenuItem(
639− text = { Text(stringResource(R.string.palette_choose_agent)) },
640− enabled = !agentsLoading || agents.isNotEmpty(),
641− onClick = { showTitleMenu = false; showAgentPicker = true },
642− )
643− }
644− }
645− },
646− navigationIcon = {
647− IconButton(onClick = {
648− if (running) showExitConfirm = true else onBack()
649− }) {
650− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
651− }
652− },
653− actions = {
654− // At-a-glance run status in the top bar. When the user is scrolled
655− // up (jump-to-latest FAB visible), the input-bar Stop button and the
656− // trailing "working…" row are off-screen, so a top-bar spinner is the
657− // only signal the agent is still working.
658− if (running) {
659− val workingLabel = stringResource(R.string.working)
660− CircularProgressIndicator(
661− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
662− strokeWidth = 2.dp,
663− )
664− }
665− // Manual refresh: forces an SSE reconnect, which re-seeds messages
666− // from REST. A recovery path when the stream silently drops and the
667− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
668− // immediate tap feedback — the SSE reconnect may not visibly change
669− // the connection state when already Connected, so without it the tap
670− // appears to do nothing. Disabled while a run is active: a mid-run
671− // refresh forces a reconnect that can interrupt the streaming reply,
672− // and the working spinner already signals "wait" — the recovery path
673− // is only needed when nothing is actively streaming.
674− val refreshLabel = stringResource(R.string.refresh)
675− IconButton(
676− onClick = { vm.refreshMessages() },
677− enabled = activeConnection != null && !refreshing && !running,
678− ) {
679− if (refreshing) {
680− CircularProgressIndicator(
681− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
682− strokeWidth = 2.dp,
683− )
684− } else {
685− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
686− }
687− }
688− // Overflow menu consolidates the less-frequent actions (share,
689− // commands, agent, model, rename, delete) so the top bar stays
690− // scannable on narrow phones — previously 5 icons crowded the bar
691− // alongside the back button and tappable title. Catalog-loading
692− // spinners stay inline (next to the overflow) so a load state is
693− // visible without opening the menu.
694− val moreLabel = stringResource(R.string.more)
695− val loadingLabel = stringResource(R.string.loading)
696− val shareLabel = stringResource(R.string.share_conversation)
697− val copyAsMarkdownLabel = stringResource(R.string.copy_as_markdown)
698− val shareAsJsonLabel = stringResource(R.string.share_as_json)
699− val copyAsJsonLabel = stringResource(R.string.copy_as_json)
700− val commandsLabel = stringResource(R.string.commands)
701− val renameLabel = stringResource(R.string.rename_session_chat)
702− val deleteLabel = stringResource(R.string.delete_session_chat)
703− val createShareLabel = stringResource(R.string.create_share_link)
704− val copyShareLabel = stringResource(R.string.copy_share_link)
705− val stopShareLabel = stringResource(R.string.stop_sharing)
706− val summarizeLabel = stringResource(R.string.summarize_conversation)
707− val initLabel = stringResource(R.string.generate_agents_md)
708− val shellLabel = stringResource(R.string.run_shell_command)
709− Box {
710− IconButton(onClick = { showOverflowMenu = true }) {
711− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
712− }
713− DropdownMenu(
714− expanded = showOverflowMenu,
715− onDismissRequest = { showOverflowMenu = false },
716− ) {
717− DropdownMenuItem(
718− text = { Text(shareLabel) },
719− enabled = hasMessages,
720− onClick = {
721− showOverflowMenu = false
722− scope.launch {
723− val md = withContext(Dispatchers.Default) {
724− buildConversationMarkdown(vm.messages.value, sessionTitle)
725− }
726− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
727− type = "text/markdown"
728− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
729− putExtra(android.content.Intent.EXTRA_TEXT, md)
730− }
731− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
732− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
733− }
734− },
735− )
736− // Copy the whole conversation as Markdown to the clipboard, so a
737− // user can paste into another app without the share-sheet round-trip.
738− DropdownMenuItem(
739− text = { Text(copyAsMarkdownLabel) },
740− enabled = hasMessages,
741− onClick = {
742− showOverflowMenu = false
743− scope.launch {
744− val md = withContext(Dispatchers.Default) {
745− buildConversationMarkdown(vm.messages.value, sessionTitle)
746− }
747− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
748− }
749− },
750− )
751− // Lossless JSON share: the full List<MessageWithParts> serialized with
752− // the shared OpencodeJson, so tool outputs, file sources, and reasoning
753− // survive verbatim (the Markdown export truncates/summarizes them).
754− DropdownMenuItem(
755− text = { Text(shareAsJsonLabel) },
756− enabled = hasMessages,
757− onClick = {
758− showOverflowMenu = false
759− scope.launch {
760− val json = withContext(Dispatchers.Default) {
761− buildConversationJson(vm.messages.value)
762− }
763− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
764− type = "application/json"
765− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
766− putExtra(android.content.Intent.EXTRA_TEXT, json)
767− }
768− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
769− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
770− }
771− },
772− )
773− DropdownMenuItem(
774− text = { Text(copyAsJsonLabel) },
775− enabled = hasMessages,
776− onClick = {
777− showOverflowMenu = false
778− scope.launch {
779− val json = withContext(Dispatchers.Default) {
780− buildConversationJson(vm.messages.value)
781− }
782− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
783− }
784− },
785− )
786− DropdownMenuItem(
787− text = { Text(commandsLabel) },
788− enabled = !commandsLoading || commands.isNotEmpty(),
789− onClick = { showOverflowMenu = false; showCommandPicker = true },
790− )
791− DropdownMenuItem(
792− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
793− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
794− )
795− DropdownMenuItem(
796− text = { Text(stringResource(R.string.find_in_conversation)) },
797− onClick = {
798− showOverflowMenu = false
799− searchActive = true
800− // Focus is requested by the LaunchedEffect(searchActive)
801− // below, which waits for the search field to be composed
802− // before requesting focus (calling requestFocus here would
803− // target a field that isn't in the composition yet).
804− },
805− )
806− androidx.compose.material3.HorizontalDivider()
807− // Session sharing: create a public link, copy an existing one, or revoke it.
808− if (shareUrl == null) {
809− DropdownMenuItem(
810− text = { Text(createShareLabel) },
811− enabled = hasMessages,
812− onClick = { showOverflowMenu = false; vm.shareSession() },
813− )
814− } else {
815− DropdownMenuItem(
816− text = { Text(copyShareLabel) },
817− onClick = {
818− showOverflowMenu = false
819− shareUrl?.let {
820− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
821− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
822− }
823− },
824− )
825− DropdownMenuItem(
826− text = { Text(stopShareLabel) },
827− onClick = { showOverflowMenu = false; vm.unshareSession() },
828− )
829− }
830− DropdownMenuItem(
831− text = { Text(summarizeLabel) },
832− enabled = hasMessages && !running,
833− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
834− )
835− DropdownMenuItem(
836− text = { Text(initLabel) },
837− enabled = !running,
838− onClick = { showOverflowMenu = false; showInitConfirm = true },
839− )
840− DropdownMenuItem(
841− text = { Text(shellLabel) },
842− enabled = !running,
843− onClick = { showOverflowMenu = false; showShellDialog = true },
844− )
845− androidx.compose.material3.HorizontalDivider()
846− DropdownMenuItem(
847− text = { Text(renameLabel) },
848− onClick = { showOverflowMenu = false; showRenameDialog = true },
849− )
850− DropdownMenuItem(
851− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
852− onClick = { showOverflowMenu = false; showDeleteDialog = true },
853− )
854− }
855− // While a catalog is initially loading (empty list + loading flag),
856− // show a tiny inline spinner beside the overflow so the user can see
857− // a load is in progress without opening the menu. Once loaded the
858− // spinner disappears; the menu items are always enabled (tapping a
859− // picker with no items shows the "no models/agents/commands" state).
860− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
861− (agentsLoading && agents.isEmpty()) ||
862− (modelsLoading && models.isEmpty())
863− if (catalogLoading) {
864− CircularProgressIndicator(
865− Modifier
866− .align(Alignment.TopEnd)
867− .size(10.dp)
868− .semantics { contentDescription = loadingLabel },
869− strokeWidth = 1.dp,
870− )
871− }
872− }
873− },
874− )
875− },
876− snackbarHost = { SnackbarHost(snackbar) },
877− bottomBar = {
878− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
879− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
880− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
881− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
882− Column {
883− // Pinned above the composer so the agent's plan and progress stay visible
884− // while scrolled up mid-run; renders nothing when there's no plan.
885− TodoPlanBar(todoPlan)
886− val bannerMotion = rememberVisibilityTransitions()
887− AnimatedVisibility(
888− visible = reverted,
889− enter = bannerMotion.enter,
890− exit = bannerMotion.exit,
891− ) {
892− RevertBanner(
893− diff = revertDiff,
894− isEditing = editing,
895− onUndo = { vm.unrevert() },
896− )
897− }
898− AnimatedVisibility(
899− visible = queuedOffline.isNotEmpty(),
900− enter = bannerMotion.enter,
901− exit = bannerMotion.exit,
902− ) {
903− OutboxBanner(
904− count = queuedOffline.size,
905− sending = outboxSending,
906− onFlush = { vm.flushQueued() },
907− onDiscard = { vm.discardAllQueued() },
908− )
909− }
910− AnimatedVisibility(
911− visible = pendingQuote != null,
912− enter = bannerMotion.enter,
913− exit = bannerMotion.exit,
914− ) {
915− pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
916− }
917− ChatInputBar(
918− value = draft,
919− onValueChange = vm::updateDraft,
920− running = running,
921− aborting = aborting,
922− enabled = activeConnection != null,
923− sendOnEnter = sendOnEnter,
924− onSend = ::doSend,
925− onAbort = { vm.abort() },
926− queuedFollowUp = queuedFollowUp,
927− onQueueFollowUp = vm::queueFollowUp,
928− onCancelQueue = { vm.queueFollowUp("") },
929− focusRequester = inputFocusRequester,
930− attachments = attachments,
931− staging = stagingCount > 0,
932− stagingFileCount = stagingFileTotal,
933− onRemoveAttachment = vm::removeAttachment,
934− onPickPhoto = {
935− photoPicker.launch(
936− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
937− )
938− },
939− onPickFile = { filePicker.launch("*/*") },
940− onCamera = { launchCamera() },
941− onVoice = { launchVoice() },
942− onPasteImage = { stageUris(it) },
943− commands = commands,
944− onRunCommand = { cmd ->
945− vm.runCommand(cmd)
946− // Clear the draft so the typed /prefix doesn't linger after the
947− // command fires (the command picker confirmation, if any, is
948− // handled inside runCommand).
949− vm.updateDraft("")
950− },
951− )
952− }
953− },
954− ) { padding ->
955− // Collect messages inside the content lambda so streaming token updates
956− // recompose only this subtree, not the top bar / input bar / 20+ other
957− // state reads in the ChatScreen body.
958− val messages by vm.messages.collectAsStateWithLifecycle()
959− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
960− val listState = rememberLazyListState()
961− val contentScope = rememberCoroutineScope()
962− val timeTick = rememberRelativeTimeTick()
963− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
964− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
965− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
966− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
967− androidx.compose.runtime.LaunchedEffect(listState) {
968− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
969− .distinctUntilChanged()
970− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
971− } // Group messages by day and interleave date separators so a long conversation
972− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
973− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
974− // outside the PullToRefreshBox so the auto-scroll effects below can reference
975− // the same list the LazyColumn renders (separators shift the indices vs. the
976− // raw messages list, so scroll targets must be in listItems space).
977− val todayLabel = stringResource(R.string.today)
978− val yesterdayLabel = stringResource(R.string.yesterday)
979− // In-conversation search: when active, narrow to messages whose text contains the query.
980− // Computed on the filtered set so day separators still align with the visible messages.
981− // Debounced + off-main-thread so a keystroke-by-keystroke filter walk over a long
982− // conversation (with many tool parts whose state stringification is non-trivial)
983− // doesn't jank the UI. produceState yields the empty list immediately and publishes
984− // the filtered result once the debounce settles.
985− val searchQuery = chatSearch.trim()
986− // When no search is active, skip the produceState indirection entirely and use the
987− // messages list directly. produceState keyed on (messages, searchQuery) re-launches
988− // its coroutine on every messages emission (every streamed token) even when the
989− // query is empty — the body just re-assigns `value = messages`, but the coroutine
990− // churn (launch + cancel + state write) ~20x/sec is pure overhead. Using `messages`
991− // directly when there's no search avoids that, and `buildMessageListItems` keys its
992− // own remember on the resulting list identity either way.
993− val searchMessages: List<MessageWithParts> = if (searchQuery.isEmpty()) {
994− messages
995− } else {
996− // Capture the messages list via rememberUpdatedState so the latest list is read
997− // when the debounce completes, WITHOUT re-launching the produceState coroutine on
998− // every messages emission. Keying produceState on `messages` restarts the debounce
999− // delay from zero on every streamed token (~20×/sec); if tokens arrive faster than
1000− // the debounce interval the filter never runs and search shows "no matches" for the
1001− // entire run. Keying only on `searchQuery` lets the debounce settle once per query
1002− // while still filtering against the most recent list.
1003− val currentMessages by rememberUpdatedState(messages)
1004− val filtered by produceState(
1005− initialValue = emptyList(),
1006− searchQuery,
1007− ) {
1008− // Debounce: wait for the user to stop typing before running the filter,
1009− // so each keystroke doesn't kick off a fresh scan.
1010− kotlinx.coroutines.delay(NetworkConfig.chatSearchDebounceMs)
1011− // Run the filter off the main thread — the walk stringifies tool state
1012− // and scans every part of every message, which is non-trivial work for a
1013− // long conversation.
1014− value = withContext(Dispatchers.Default) {
1015− currentMessages.filter { m ->
1016− m.parts.any { p ->
1017− when (p) {
1018− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
1019− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
1020− is ToolPart -> {
1021− // Match the tool name plus its running/completed/error text and the
1022− // stringified input, so searching for an error string or a file the
1023− // tool touched actually finds the message it appeared in.
1024− p.tool.contains(searchQuery, ignoreCase = true) ||
1025− (p.state is ToolRunning && p.state.title?.contains(searchQuery, ignoreCase = true) == true) ||
1026− (p.state is ToolCompleted && (p.state.title?.contains(searchQuery, ignoreCase = true) == true ||
1027− p.state.output?.contains(searchQuery, ignoreCase = true) == true)) ||
1028− (p.state is ToolError && p.state.error?.contains(searchQuery, ignoreCase = true) == true) ||
1029− p.state.inputElement()?.toString()?.contains(searchQuery, ignoreCase = true) == true
1030− }
1031− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
1032− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
1033− else -> false
1034− }
1035− }
1036− }
1037− }
1038− }
1039− filtered
1040− }
1041− // Keep the focused-match index in range as the query (and thus the match set) changes.
1042− // A new query resets to the first match (keyed on searchQuery alone so any change —
1043− // even one that still yields enough matches — jumps to index 0 rather than carrying
1044− // the old index over to a semantically unrelated message). A shrunk set clamps to
1045− // the last valid index (keyed on size so a content refresh that shrinks the matches
1046− // without a query change doesn't leave searchPos out of range).
1047− LaunchedEffect(searchQuery) {
1048− searchPos = 0
1049− }
1050− LaunchedEffect(searchMessages.size) {
1051− if (searchPos >= searchMessages.size) searchPos = 0
1052− }
1053− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1054− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1055− }
1056− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1057− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1058− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1059− // would capture the first composition's list — which is empty, since `messages`
1060− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1061− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1062− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1063− // whose value tracks the latest list.
1064− val currentListItems by rememberUpdatedState(listItems)
1065−
1066− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1067− // while the user was scrolled away from the bottom, cleared once they return. A count
1068− // (vs. a bare dot) tells the user how much they missed at a glance.
1069− var newContentCount by remember { mutableIntStateOf(0) }
1070−
1071− val isPinnedToBottom by remember {
1072− derivedStateOf {
1073− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1074− // When a run is active, the LazyColumn has one trailing "__typing"
1075− // item after the last list item. Account for it so "pinned to bottom"
1076− // includes the working indicator — otherwise the pin check targets
1077− // listItems.lastIndex, the typing row sits just below the viewport,
1078− // and the user never sees the progress indicator even when pinned.
1079− val items = currentListItems
1080− val effectiveLast = if (running) items.size else items.lastIndex
1081− lastVisible >= effectiveLast || items.isEmpty()
1082− }
1083− }
1084−
1085− // Jump to the newest message once, when the conversation first loads. Guarded by a
1086− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1087− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1088− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1089− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1090− LaunchedEffect(listItems.isNotEmpty()) {
1091− if (listItems.isNotEmpty() && !didInitialScroll) {
1092− // When a run is active the LazyColumn has a trailing "__typing" row at
1093− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1094− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1095− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1096− didInitialScroll = true
1097− }
1098− }
1099−
1100− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1101− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1102− // isPinnedToBottom check flips to false the instant you send — freezing
1103− // auto-scroll. If the user was pinned to the last item just before the run
1104− // began, bring the typing row into view so the pin (and streaming follow) is
1105− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1106− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1107− LaunchedEffect(running) {
1108− if (running && listItems.isNotEmpty()) {
1109− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1110− if (lastVisible >= listItems.lastIndex) {
1111− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1112− }
1113− }
1114− }
1115−
1116− // Scroll the focused search match into view whenever the user steps through results with
1117− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1118− // includes date separators) and animates there.
1119− LaunchedEffect(searchPos, searchQuery, listItems) {
1120− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1121− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1122− val index = listItems.indexOfFirst {
1123− it is MessageListItem.Message && it.message.info.id == target.info.id
1124− }
1125− if (index >= 0) runCatchingCancellable { listState.animateScrollToItem(index) }
1126− }
1127−
1128− // Global-search deep link: scroll to and briefly highlight the matched message. The
1129− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1130− // clears itself after a short delay so the user can re-read the surrounding context
1131− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1132− //
1133− // Keyed ONLY on focusedMessageId (not listItems): a bare listItems key re-keys on every
1134− // streamed token (the list is rebuilt per snapshot), which cancels the 2.5s delay before
1135− // it can clear the highlight — re-scrolling to the focus on every token and making an
1136− // actively-streaming chat unreadable. snapshotFlow waits for the message to appear in the
1137− // list (it may not be present on the first composition while messages load) without
1138− // re-keying the effect on every list change.
1139− var focusedMessageId by remember(focusMessageId) { mutableStateOf(focusMessageId) }
1140− val currentListItemsForFocus by rememberUpdatedState(listItems)
1141− LaunchedEffect(focusedMessageId) {
1142− val focus = focusedMessageId ?: return@LaunchedEffect
1143− // Wait for the focused message to appear in the list, then resolve its index. A
1144− // first-composition empty list (messages still loading) will populate as the seed
1145− // arrives; snapshotFlow re-evaluates on each list change until the match is found.
1146− val index = snapshotFlow {
1147− currentListItemsForFocus.indexOfFirst {
1148− it is MessageListItem.Message && it.message.info.id == focus
1149− }
1150− }.first { it >= 0 }
1151− runCatchingCancellable { listState.animateScrollToItem(index) }
1152− kotlinx.coroutines.delay(2500)
1153− focusedMessageId = null
1154− }
1155−
1156− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1157− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1158− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1159− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1160− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1161− val density = androidx.compose.ui.platform.LocalDensity.current
1162− var wasImeOpen by remember { mutableStateOf(false) }
1163− val imeBottomPx = WindowInsets.ime.getBottom(density)
1164− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1165− if (listItems.isEmpty()) return@LaunchedEffect
1166− val imeOpen = imeBottomPx > 0
1167− // Scroll to bottom only on the open transition (not close) and only when the user
1168− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1169− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1170− if (shouldScroll) {
1171− runCatchingCancellable {
1172− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1173− }
1174− }
1175− wasImeOpen = imeOpen
1176− }
1177−
1178− LaunchedEffect(Unit) {
1179− var prevSize = 0
1180− var prevLen = 0
1181− snapshotFlow {
1182− // Track list size + the streaming length of the last part so we auto-scroll
1183− // as content arrives, plus the pinned flag. A small data class with primitive
1184− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1185− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1186− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1187− // and tool output — not just TextPart — keeps a pinned view following a long
1188− // reasoning/tool block while it streams (previously it stalled at 0).
1189− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1190− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1191− }.collect { signal ->
1192− if (signal.pinned) {
1193− // Back at the bottom: clear the new-content badge.
1194− newContentCount = 0
1195− if (signal.size > 0) {
1196− // Scroll to the effective last index, including the trailing
1197− // "__typing" row when a run is active so the working indicator
1198− // is brought into view (not just the last message).
1199− val items = currentListItems
1200− val target = if (running) items.size else items.lastIndex
1201− listState.scrollToItem(target)
1202− }
1203− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1204− // Content arrived while scrolled up — increment the jump-to-latest badge.
1205− // Only count whole new items (not per-token growth) so the number reflects
1206− // new messages, not a token count.
1207− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1208− else if (newContentCount == 0) newContentCount = 1
1209− }
1210− prevSize = signal.size
1211− prevLen = signal.lastTextLength
1212− }
1213− }
1214−
1215− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1216− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1217− // content padding accounts for the bottomBar's raised height, so the message
1218− // list is already above the keyboard. Adding imePadding here would double-apply
1219− // the IME inset and push messages too far up.
1220− //
1221− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1222− // message list on wide screens instead of floating at the screen edges — on a
1223− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1224− // The horizontal margin below is applied to the FAB/search containers so they
1225− // track the list's left/right edges.
1226− androidx.compose.foundation.layout.BoxWithConstraints(
1227− modifier = Modifier.fillMaxSize().padding(padding),
1228− ) {
1229− val screenMaxWidth = maxWidth
1230− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1231− // Horizontal margin between the capped list's edge and the screen edge (0 on
1232− // screens narrower than the cap). Applied as start/end padding so the FABs and
1233− // search bar sit at the list's edges, not the screen's.
1234− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1235− if (activeConnection == null) {
1236− Column(
1237− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1238− horizontalAlignment = Alignment.CenterHorizontally,
1239− ) {
1240− Text(
1241− stringResource(R.string.not_connected),
1242− color = MaterialTheme.colorScheme.error,
1243− )
1244− Spacer(Modifier.size(12.dp))
1245− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1246− if (reconnecting) {
1247− CircularProgressIndicator(
1248− Modifier.size(20.dp),
1249− color = MaterialTheme.colorScheme.onPrimary,
1250− strokeWidth = 2.dp,
1251− )
1252− } else {
1253− Text(stringResource(R.string.reconnect))
1254− }
1255− }
1256− }
1257− } else {
1258− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1259− // Measure the banner's actual height instead of hardcoding 44dp. At large
1260− // accessibility font scales the banner's labelMedium text + spinner + Retry
1261− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1262− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1263− // fires while the banner is composed (visible), so gate the inset on
1264− // bannerVisible and fall back to 44dp until the first measurement arrives.
1265− var bannerHeightPx by remember { mutableIntStateOf(0) }
1266− // Track the search bar height so the list's top padding can grow when search
1267− // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1268− // the floating search bar (the "scroll-under-the-search-bar" bug).
1269− var searchbarHeightPx by remember { mutableIntStateOf(0) }
1270− val density = LocalDensity.current
1271− val topPad = if (bannerVisible) {
1272− if (bannerHeightPx > 0) {
1273− with(density) { bannerHeightPx.toDp() } + 4.dp
1274− } else {
1275− 44.dp
1276− }
1277− } else {
1278− 16.dp
1279− } + if (searchActive && searchbarHeightPx > 0) {
1280− with(density) { searchbarHeightPx.toDp() } + 4.dp
1281− } else {
1282− 0.dp
1283− }
1284− ConnectionBanner(
1285− state = connectionState,
1286− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1287− isOnline = isOnline,
1288− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1289− // re-seeds from REST). refreshMessages is the right recovery path
1290− // when the connection is present but the stream died; reconnect()
1291− // is the path when the whole connection is gone (handled by the
1292− // separate "Not connected" state below).
1293− onRetry = { vm.refreshMessages() },
1294− // On an auth failure (401/403), retrying with the same bad credentials
1295− // is futile — offer a one-tap path to edit the active profile's
1296− // credentials instead of making the user hunt for the server list.
1297− onEditCredentials = {
1298− val profileId = activeConnection?.profile?.id
1299− if (profileId != null) onEditProfile?.invoke(profileId)
1300− },
1301− reconnectAttempts = reconnectAttempts,
1302− )
1303− // Persistent inline error banner for a mid-conversation load failure.
1304− // Unlike the one-shot snackbar (which fires once per streak then goes
1305− // silent), this stays visible until the stream recovers, so a persistent
1306− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1307− // Anchored at the top, below the connection banner, so it doesn't overlap
1308− // the message list.
1309− if (loadErrorInline && hasMessages) {
1310− Surface(
1311− color = MaterialTheme.colorScheme.errorContainer,
1312− shape = MaterialTheme.shapes.small,
1313− modifier = Modifier
1314− .align(Alignment.TopCenter)
1315− .padding(top = if (bannerVisible) topPad else 8.dp)
1316− .padding(horizontal = 16.dp)
1317− .semantics { liveRegion = LiveRegionMode.Polite },
1318− ) {
1319− Row(
1320− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1321− verticalAlignment = Alignment.CenterVertically,
1322− horizontalArrangement = Arrangement.spacedBy(8.dp),
1323− ) {
1324− Icon(
1325− Icons.Filled.ErrorOutline,
1326− contentDescription = null,
1327− modifier = Modifier.size(16.dp),
1328− tint = MaterialTheme.colorScheme.onErrorContainer,
1329− )
1330− Text(
1331− stringResource(R.string.load_error_persistent),
1332− style = MaterialTheme.typography.labelMedium,
1333− color = MaterialTheme.colorScheme.onErrorContainer,
1334− modifier = Modifier.weight(1f),
1335− )
1336− TextButton(
1337− onClick = { vm.refreshMessages() },
1338− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1339− ) {
1340− Text(stringResource(R.string.retry))
1341− }
1342− }
1343− }
1344− }
1345− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1346− // recovery is a swipe away everywhere — not just when the message list is
1347− // populated. Previously PTR was only around the populated list, leaving the
1348− // error/loading states reachable only via a button tap.
1349− PullToRefreshBox(
1350− isRefreshing = refreshing,
1351− // Suppress the refresh action while a run is active: a mid-stream
1352− // refresh forces an SSE reconnect that can interrupt the actively
1353− // streaming reply (matching the top-bar refresh button, which is
1354− // also disabled while running). The pull gesture still responds, but
1355− // the release no-ops instead of triggering a disruptive re-seed.
1356− onRefresh = { if (!running) vm.refreshMessages() },
1357− // Cap width and center on large screens for readability — full-width
1358− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1359− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1360− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1361− ) {
1362− // Reserve top space when the banner is visible so it doesn't overlap the
1363− // first message / state content. (topPad computed above.)
1364− if (loading && messages.isEmpty()) {
1365− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1366− // than a bare centered spinner and the first real messages pop into an
1367− // already-shaped list instead of a blank-then-pop.
1368− ChatSkeleton(topPad = topPad)
1369− } else if (loadError && messages.isEmpty()) {
1370− // A failed load with nothing to show. Distinct from the empty
1371− // conversation state below — the conversation isn't empty, it
1372− // failed to load, and offering "Start a conversation" here is
1373− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1374− Column(
1375− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1376− horizontalAlignment = Alignment.CenterHorizontally,
1377− ) {
1378− Text(
1379− stringResource(R.string.load_messages_failed),
1380− color = MaterialTheme.colorScheme.error,
1381− )
1382− Spacer(Modifier.size(12.dp))
1383− Button(onClick = { vm.refreshMessages() }) {
1384− Text(stringResource(R.string.retry))
1385− }
1386− // When the VM's retryWhen loop is actively retrying (loading is true
1387− // on top of the error state), surface a small "retrying…" indicator so
1388− // the user knows the system is working — without it, the static error
1389− // + Retry button reads as "broken, tap to fix", and the user may not
1390− // realize an automatic retry is already in progress.
1391− if (loading) {
1392− Spacer(Modifier.size(12.dp))
1393− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1394− Row(verticalAlignment = Alignment.CenterVertically) {
1395− CircularProgressIndicator(
1396− Modifier.size(14.dp),
1397− strokeWidth = 2.dp,
1398− )
1399− Text(
1400− retryingLabel,
1401− style = MaterialTheme.typography.labelSmall,
1402− color = MaterialTheme.colorScheme.onSurfaceVariant,
1403− modifier = Modifier.padding(start = 6.dp),
1404− )
1405− }
1406− }
1407− }
1408− } else if (messages.isEmpty() && running) {
1409− // A run just started but no parts have arrived yet — the empty list with
1410− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1411− // from the initial-load branch so the perceived start latency is lower and
1412− // the first real assistant part pops into an already-shaped list.
1413− ChatSkeleton(topPad = topPad)
1414− } else if (messages.isEmpty()) {
1415− EmptyConversation(
1416− onSuggestion = {
1417− vm.updateDraft(it)
1418− // Focus the input so the user can edit the suggestion before
1419− // sending, instead of having to manually tap the field.
1420− runCatching { inputFocusRequester.requestFocus() }
1421− },
1422− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1423− )
1424− } else {
1425− val lastMessageId = messages.lastOrNull()?.info?.id
1426− // Text-to-speech for reading assistant replies aloud; shuts down when the
1427− // message list leaves composition.
1428− val tts = rememberTtsController()
1429− val speakingMessageId by tts.speakingId
1430− val ttsState by tts.state
1431− // Provide the in-conversation search query to the markdown renderer so matching
1432− // text spans are highlighted in-place (in addition to the focused-row highlight
1433− // above). Scoped to the list so cleared search stops highlighting immediately.
1434− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1435− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1436− LazyColumn(
1437− state = listState,
1438− modifier = Modifier.fillMaxSize(),
1439− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1440− // never floats over the last message. Top padding grows when the
1441− // connection banner is visible so it doesn't overlap the first message.
1442− contentPadding = PaddingValues(
1443− start = 16.dp,
1444− top = topPad,
1445− end = 16.dp,
1446− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1447− ),
1448− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1449− // more conversation on screen without scrolling as much.
1450− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1451− ) {
1452− items(
1453− items = listItems,
1454− key = { it.key },
1455− contentType = { it.contentType },
1456− ) { item ->
1457− // When in-conversation search is stepping through matches, highlight the
1458− // focused one's row so the user can spot it at a glance among the filtered
1459− // results (full in-text term highlighting would require threading the query
1460− // through the markdown renderer; the row highlight + scroll-to-match covers
1461− // the navigation use case desktop chat apps solve with next/prev).
1462− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1463− searchMessages.getOrNull(searchPos)?.info?.id
1464− } else null
1465− val isFocusedMatch = focusedMatchId != null &&
1466− item is MessageListItem.Message &&
1467− item.message.info.id == focusedMatchId
1468− // Default placement animation so inserted/moved rows glide in. Skipped
1469− // entirely under reduced motion so a streaming message growing in place
1470− // doesn't animate on every token (and respects the a11y preference).
1471− Box(
1472− Modifier
1473− .then(reducedMotionAnimateItem())
1474− .then(
1475− if (isFocusedMatch) {
1476− Modifier.background(
1477− MaterialTheme.colorScheme.secondaryContainer,
1478− MaterialTheme.shapes.medium,
1479− )
1480− } else {
1481− Modifier
1482− },
1483− ),
1484− ) {
1485− when (item) {
1486− is MessageListItem.Separator -> DateSeparator(item.label)
1487− is MessageListItem.Message -> {
1488− val message = item.message
1489− val messageId = message.info.id
1490− // Only the last (streaming) message needs isRunning — it drives the
1491− // reasoning-block spinner. Passing the live flag to every bubble
1492− // makes all visible messages recompose whenever a run starts or stops.
1493− val modelLabel = remember(message.info, models) {
1494− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1495− ?.let { resolveModelLabel(it, models) }
1496− }
1497− // Key agentLabel/quoteText on the message id (not message.parts) so
1498− // the streaming message — whose `parts` list is replaced on every
1499− // token — doesn't re-run filterIsInstance per token for these two
1500− // derived labels. For a non-streaming message, `message.parts` is
1501− // reference-stable anyway, so this is equivalent. For the streaming
1502− // message the label updates as parts change via the message.info/
1503− // parts reference change below — keyed on messageId + a parts-hash
1504− // is overkill; agentLabel/quoteText only need to reflect the latest
1505− // parts, and `remember(messageId, message.parts)` would re-key per
1506− // token. Instead key on `messageId` alone and accept that the label
1507− // lags by one recomposition for the streaming bubble (it stabilizes
1508− // once the stream finishes). This is invisible in practice: agent
1509− // label is set on the first part, quote text grows with text parts
1510− // but is only consumed on a swipe (user-initiated, post-stream).
1511− val agentLabel = remember(messageId) {
1512− message.parts
1513− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1514− .firstOrNull { it.name.isNotBlank() }?.name
1515− }
1516− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1517− // image/code-only messages, which then opt out of the swipe gesture.
1518− val quoteText = remember(messageId) {
1519− message.parts
1520− .filterIsInstance<TextPart>()
1521− .joinToString("\n\n") { it.text }
1522− .trim()
1523− .takeIf { it.isNotEmpty() }
1524− }
1525− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1526− // snapping back (the message isn't dismissed — the quote fills the composer).
1527− // Enabled for non-text messages too (image/tool-only), but the confirm
1528− // callback gives a haptic without triggering reply — so the user gets a
1529− // perceptible "can't quote this" signal instead of a silently dead gesture.
1530− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1531− val undoLabel = stringResource(R.string.undo)
1532− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1533− // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1534− // so it's stable across recompositions (a fresh lambda would force the
1535− // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1536− // derived value that's stable for non-streaming messages.
1537− val swipeState = rememberSwipeToDismissBoxState(
1538− confirmValueChange = remember(messageId, quoteText) {
1539− { value ->
1540− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1541− SwipeToDismissBoxValue.EndToStart
1542− } else {
1543− SwipeToDismissBoxValue.StartToEnd
1544− }
1545− if (value == replyValue) {
1546− if (quoteText != null) {
1547− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1548− vm.quoteReply(quoteText)
1549− runCatching { inputFocusRequester.requestFocus() }
1550− scope.launch {
1551− val res = snackbar.showSnackbar(
1552− message = quoteReplyLabel,
1553− actionLabel = undoLabel,
1554− )
1555− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1556− vm.cancelQuoteReply()
1557− }
1558− }
1559− } else {
1560− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1561− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1562− }
1563− }
1564− false
1565− }
1566− },
1567− )
1568− // In RTL locales, mirror the swipe direction so the reply
1569− // gesture reads naturally (swipe from the trailing edge
1570− // toward the leading edge), matching how LTR users swipe
1571− // left-to-right. Without this, RTL users had no reply swipe.
1572− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1573− // Memoize every MessageBubble lambda on the message id so a recomposition
1574− // triggered by a sibling (e.g. the streaming message's parts changing,
1575− // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1576− // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1577− // many `(() -> Unit)?` params, which Compose treats as unstable), so
1578− // without memoization every visible bubble recomposes on every token,
1579− // defeating the @Immutable MessageWithParts reference-stability the
1580− // reducer's Holder cache provides. This mirrors the SessionListScreen
1581− // per-card lambda memoization pattern.
1582− val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1583− val onEdit = remember(messageId) {
1584− { text: String ->
1585− // editMessage reverts to before this message (hiding it and
1586− // everything after); the revert banner surfaces the rewind
1587− // with an Undo. Focus + scroll the composer into view like the
1588− // Quote action so the prefilled draft isn't off-screen.
1589− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1590− vm.editMessage(messageId, text)
1591− runCatching { inputFocusRequester.requestFocus() }
1592− contentScope.launch {
1593− runCatchingCancellable {
1594− listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1595− }
1596− }
1597− Unit
1598− }
1599− }
1600− val onSpeak = remember(messageId) {
1601− { text: String ->
1602− if (!tts.toggle(messageId, text)) {
1603− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1604− }
1605− Unit
1606− }
1607− }
1608− val onPause = remember { { tts.pause() } }
1609− val onResume = remember { { tts.resume() } }
1610− val onStop = remember { { tts.stop() } }
1611− val onQuote = remember(messageId) {
1612− { text: String ->
1613− vm.quoteReply(text)
1614− runCatching { inputFocusRequester.requestFocus() }
1615− Unit
1616− }
1617− }
1618− val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1619− // Regenerate is only meaningful for a finished assistant reply
1620− // (not the actively-streaming one), so gate it on !running.
1621− val onRegenerate = if (!running) {
1622− remember(messageId) { { vm.regenerate(messageId) } }
1623− } else {
1624− null
1625− }
1626− // Continue: resume a partial reply. Shown only for
1627− // incomplete assistant messages (a partial reply that
1628− // was aborted) and not while a run is active.
1629− val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1630− val onContinue = if (canContinue) {
1631− remember(messageId) { { vm.continueRun(messageId) } }
1632− } else {
1633− null
1634− }
1635− val messageFailed = optimisticStatuses[messageId] == true
1636− val onRetry = if (messageFailed) {
1637− remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1638− } else {
1639− null
1640− }
1641− val onDismiss = if (messageFailed) {
1642− remember(messageId) { { vm.dismissOptimistic(messageId) } }
1643− } else {
1644− null
1645− }
1646− val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1647− {
1648− // Per-message share: build a single-message Markdown
1649− // transcript off-thread and fire ACTION_SEND, mirroring the
1650− // whole-conversation share but scoped to just this message.
1651− scope.launch {
1652− val md = withContext(Dispatchers.Default) {
1653− buildMessageMarkdown(message)
1654− } ?: return@launch
1655− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1656− type = "text/markdown"
1657− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1658− putExtra(android.content.Intent.EXTRA_TEXT, md)
1659− }
1660− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1661− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1662− }
1663− Unit
1664− }
1665− }
1666− SwipeToDismissBox(
1667− state = swipeState,
1668− enableDismissFromEndToStart = !replyFromStartToEnd,
1669− enableDismissFromStartToEnd = replyFromStartToEnd,
1670− backgroundContent = {
1671− Box(
1672− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1673− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1674− ) {
1675− Icon(
1676− Icons.AutoMirrored.Filled.Reply,
1677− contentDescription = null,
1678− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1679− )
1680− }
1681− },
1682− ) {
1683− MessageBubble(
1684− message,
1685− isRunning = running && messageId == lastMessageId,
1686− imageContext = imageContext,
1687− modelLabel = modelLabel,
1688− agentLabel = agentLabel,
1689− onOpenFile = onOpenFile,
1690− onRevert = onRevert,
1691− onEdit = onEdit,
1692− onSpeak = onSpeak,
1693− isSpeaking = messageId == speakingMessageId,
1694− ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1695− onPause = onPause,
1696− onResume = onResume,
1697− onStop = onStop,
1698− onQuote = onQuote,
1699− onBranch = onBranch,
1700− onRegenerate = onRegenerate,
1701− onContinue = onContinue,
1702− sendStatus = optimisticStatuses[messageId]?.let { failed ->
1703− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1704− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1705− },
1706− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1707− onRetry = onRetry,
1708− onDismiss = onDismiss,
1709− onShare = onShare,
1710− isFirstOfSpeaker = item.isFirstOfSpeaker,
1711− highlighted = focusedMessageId != null && messageId == focusedMessageId,
1712− )
1713− }
1714− }
1715− }
1716− }
1717− }
1718− if (running) {
1719− item(key = "__typing") {
1720− val workingText = stringResource(R.string.working)
1721− // When the SSE stream dropped mid-run, show a "reconnecting" label
1722− // instead of the plain "working" text so the user understands the
1723− // run is still active but the stream is reconnecting (not finished).
1724− val reconnectingText = stringResource(R.string.reconnecting)
1725− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1726− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1727− // survives LazyColumn recycling — a local remember reset to 0:00 when
1728− // the row was disposed and scrolled back into view. The VM stamps the
1729− // start on the real false→true transition (send/run/init), not on
1730− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1731− // once per second; the value is decorative (the a11y label is the row's).
1732− // The clock freezes when an abort is confirmed (aborting = true) so the
1733− // user can see how long the run lasted before they stopped it, rather
1734− // than the clock continuing to tick until SessionIdle clears _running.
1735− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1736− // Seed the initial value synchronously from startMs so the timer
1737− // doesn't flash 0:00 when the __typing row is recycled by LazyColumn
1738− // (scrolled out then back in): produceState's coroutine is cancelled on
1739− // disposal and re-launched on re-entry, and a 0L initialValue would
1740− // briefly show "0:00" before the producer's first iteration runs.
1741− val elapsedMs by produceState(
1742− initialValue = if (startMs > 0L) (System.currentTimeMillis() - startMs).coerceAtLeast(0L) else 0L,
1743− startMs, aborting,
1744− ) {
1745− if (startMs == 0L) return@produceState
1746− if (aborting) {
1747− // Freeze at the last-computed value: one final snapshot then stop.
1748− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1749− return@produceState
1750− }
1751− while (true) {
1752− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1753− delay(1000)
1754− }
1755− }
1756− val elapsedText = remember(elapsedMs) {
1757− val total = elapsedMs / 1000
1758− // Locale.US for stable digit formatting: on locales with
1759− // non-ASCII digits (ar-/fa-) the default locale would render
1760− // localized digits inside the Monospace block, breaking the
1761− // fixed-width alignment the monospace family was chosen for.
1762− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1763− }
1764− Row(
1765− verticalAlignment = Alignment.CenterVertically,
1766− // Animate this slot in/out so the working row doesn't pop in and
1767− // jolt the message list when a run starts/stops — matching the
1768− // AnimatedVisibility used by every other transient banner/FAB here.
1769− modifier = Modifier
1770− .then(reducedMotionAnimateItem())
1771− .padding(vertical = 4.dp),
1772− ) {
1773− // Merge the indicator + label + clock into one TalkBack node so
1774− // it's announced once (the working label, then the elapsed time)
1775− // instead of "working… / working… / 0:14" with the label read
1776− // twice. The Stop IconButton below stays separately focusable.
1777− Row(
1778− verticalAlignment = Alignment.CenterVertically,
1779− modifier = Modifier.semantics(mergeDescendants = true) {
1780− contentDescription = "$interruptedLabel $elapsedText"
1781− },
1782− ) {
1783− // Dim the spinner when interrupted so the row reads as
1784− // "paused/reconnecting" rather than actively progressing.
1785− CircularProgressIndicator(
1786− Modifier.size(16.dp),
1787− strokeWidth = 2.dp,
1788− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1789− else MaterialTheme.colorScheme.primary,
1790− )
1791− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1792− Spacer(Modifier.size(8.dp))
1793− Icon(
1794− Icons.Filled.Schedule,
1795− contentDescription = null,
1796− modifier = Modifier.size(14.dp),
1797− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1798− )
1799− Text(
1800− elapsedText,
1801− style = MaterialTheme.typography.labelMedium,
1802− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1803− color = MaterialTheme.colorScheme.onSurfaceVariant,
1804− modifier = Modifier.padding(start = 4.dp),
1805− )
1806− }
1807− // A trailing Stop on the working row so the run can be aborted
1808− // without scrolling back to the composer (which may be off-screen
1809− // while the user reads the streaming output up-thread).
1810− Spacer(Modifier.weight(1f))
1811− val stopLabel = stringResource(R.string.stop)
1812− IconButton(
1813− onClick = { vm.abort() },
1814− modifier = Modifier.semantics { contentDescription = stopLabel },
1815− ) {
1816− Icon(Icons.Filled.Stop, contentDescription = null)
1817− }
1818− }
1819− }
1820− }
1821− }
1822− }
1823− }
1824− }
1825− // Jump-to-latest affordance when the user has scrolled away during a stream.
1826− val fabMotion = rememberVisibilityTransitions()
1827− AnimatedVisibility(
1828− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1829− enter = fabMotion.enter,
1830− exit = fabMotion.exit,
1831− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1832− // edge instead of floating at the screen edge (visually detached on tablets).
1833− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1834− ) {
1835− // Badge the FAB when new content arrived while the user was scrolled up, so
1836− // they know there's something new to jump to (cleared once back at bottom).
1837− BadgedBox(
1838− badge = {
1839− if (newContentCount > 0) {
1840− // Merge the count into the badge announcement so TalkBack reads
1841− // "5 new messages" instead of the bare label and a separate number.
1842− val newContentLabel = pluralStringResource(
1843− R.plurals.plurals_new_messages,
1844− newContentCount,
1845− newContentCount,
1846− )
1847− Badge(
1848− modifier = Modifier.semantics {
1849− contentDescription = newContentLabel
1850− // Announce new-content counts as they change so a
1851− // TalkBack user hears "5 new messages" without having
1852− // to focus the FAB. Polite so it doesn't interrupt an
1853− // in-progress utterance (e.g. streaming token reads).
1854− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1855− },
1856− ) {
1857− Text(
1858− if (newContentCount > 99) "99+" else newContentCount.toString(),
1859− modifier = Modifier.semantics { invisibleToUser() },
1860− )
1861− }
1862− }
1863− },
1864− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1865− ) {
1866− ExtendedFloatingActionButton(
1867− onClick = {
1868− newContentCount = 0
1869− if (listItems.isNotEmpty()) {
1870− // Scroll to the effective last index, including the
1871− // trailing "__typing" row when a run is active.
1872− val target = if (running) listItems.size else listItems.lastIndex
1873− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1874− }
1875− },
1876− // contentDescription null: the visible "Latest" text already labels
1877− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1878− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1879− text = { Text(stringResource(R.string.latest)) },
1880− )
1881− }
1882− }
1883− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1884− // user has scrolled down past the first few messages. Symmetric to the
1885− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1886− val scrolledDown by remember {
1887− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1888− }
1889− AnimatedVisibility(
1890− visible = scrolledDown && listItems.size > 4,
1891− enter = fabMotion.enter,
1892− exit = fabMotion.exit,
1893− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1894− ) {
1895− SmallFloatingActionButton(
1896− onClick = {
1897− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1898− },
1899− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1900− ) {
1901− Icon(
1902− Icons.Filled.KeyboardArrowUp,
1903− contentDescription = stringResource(R.string.scroll_to_top),
1904− )
1905− }
1906− }
1907− // In-conversation search bar. Overlays the list so typing filters messages in
1908− // place; the match count + a no-matches note give immediate feedback.
1909− val searchMotion = rememberVisibilityTransitions()
1910− AnimatedVisibility(
1911− visible = searchActive,
1912− enter = searchMotion.enter,
1913− exit = searchMotion.exit,
1914− // Inset by sideMargin on wide screens so the search bar spans the capped
1915− // list's width, not the full screen width.
1916− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1917− ) {
1918− Surface(
1919− tonalElevation = 3.dp,
1920− modifier = Modifier
1921− .padding(horizontal = 12.dp, vertical = 4.dp)
1922− .fillMaxWidth()
1923− .onSizeChanged { searchbarHeightPx = it.height },
1924− ) {
1925− // Focus the search field when the bar appears (from the overflow menu's
1926− // "Find in conversation" or Ctrl+F), so the user can start typing
1927− // immediately. Runs after the search field enters the composition.
1928− LaunchedEffect(searchActive) {
1929− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1930− }
1931− Row(
1932− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1933− verticalAlignment = Alignment.CenterVertically,
1934− ) {
1935− OutlinedTextField(
1936− value = chatSearch,
1937− onValueChange = { chatSearch = it },
1938− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1939− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1940− singleLine = true,
1941− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1942− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1943− )
1944− // Match counter: "N of M" where N is the focused match (1-based) and
1945− // M is the total matching messages. Only shown when there's a query.
1946− val matchCount = searchMessages.size
1947− Text(
1948− if (searchQuery.isNotEmpty() && matchCount > 0) {
1949− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1950− } else if (searchQuery.isNotEmpty()) {
1951− stringResource(R.string.search_no_matches)
1952− } else "",
1953− style = MaterialTheme.typography.labelSmall,
1954− color = MaterialTheme.colorScheme.onSurfaceVariant,
1955− modifier = Modifier
1956− .padding(horizontal = 4.dp)
1957− // Live region so a TalkBack user hears "3 of 12" / "No
1958− // matches" announce as they step through results, not just
1959− // the sighted user seeing the counter update.
1960− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
1961− )
1962− // Step through matches (Previous / Next), disabled when there are
1963− // fewer than two to navigate. Wrap around at the ends so repeated
1964− // taps cycle through every hit.
1965− val prevLabel = stringResource(R.string.find_previous)
1966− val nextLabel = stringResource(R.string.find_next)
1967− IconButton(
1968− onClick = {
1969− if (matchCount > 0) {
1970− searchPos = (searchPos - 1 + matchCount) % matchCount
1971− }
1972− },
1973− enabled = matchCount > 1,
1974− ) {
1975− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1976− }
1977− IconButton(
1978− onClick = {
1979− if (matchCount > 0) {
1980− searchPos = (searchPos + 1) % matchCount
1981− }
1982− },
1983− enabled = matchCount > 1,
1984− ) {
1985− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
1986− }
1987− IconButton(onClick = {
1988− searchActive = false
1989− chatSearch = ""
1990− }) {
1991− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1992− }
1993− }
1994− }
1995− }
1996− // When a search yields no matches (but the conversation isn't empty), say so
1997− // instead of showing a blank list.
1998− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1999− Text(
2000− stringResource(R.string.search_no_matches),
2001− style = MaterialTheme.typography.bodyMedium,
2002− color = MaterialTheme.colorScheme.onSurfaceVariant,
2003− modifier = Modifier.align(Alignment.Center),
2004− )
2005− }
2006− }
2007− }
2008− }
2009− }
2010−
2011− if (showExitConfirm) {
2012− AlertDialog(
2013− onDismissRequest = { showExitConfirm = false },
2014− title = { Text(stringResource(R.string.stop_and_exit_title)) },
2015− text = { Text(stringResource(R.string.stop_and_exit_text)) },
2016− confirmButton = {
2017− TextButton(onClick = {
2018− showExitConfirm = false
2019− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2020− vm.abort()
2021− onBack()
2022− }) { Text(stringResource(R.string.stop_and_exit)) }
2023− },
2024− dismissButton = {
2025− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
2026− },
2027− )
2028− }
2029−
2030− if (showSummarizeConfirm) {
2031− AlertDialog(
2032− onDismissRequest = { showSummarizeConfirm = false },
2033− title = { Text(stringResource(R.string.summarize_confirm_title)) },
2034− text = { Text(stringResource(R.string.summarize_confirm_text)) },
2035− confirmButton = {
2036− TextButton(onClick = {
2037− showSummarizeConfirm = false
2038− vm.summarize()
2039− }) { Text(stringResource(R.string.action_continue)) }
2040− },
2041− dismissButton = {
2042− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
2043− },
2044− )
2045− }
2046−
2047− if (showInitConfirm) {
2048− AlertDialog(
2049− onDismissRequest = { showInitConfirm = false },
2050− title = { Text(stringResource(R.string.init_confirm_title)) },
2051− text = { Text(stringResource(R.string.init_confirm_text)) },
2052− confirmButton = {
2053− TextButton(onClick = {
2054− showInitConfirm = false
2055− vm.initProject()
2056− }) { Text(stringResource(R.string.action_continue)) }
2057− },
2058− dismissButton = {
2059− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2060− },
2061− )
2062− }
2063−
2064− if (showRenameDialog) {
2065− RenameSessionChatDialog(
2066− initialTitle = sessionTitle ?: "",
2067− onDismiss = { showRenameDialog = false },
2068− onConfirm = { newName ->
2069− showRenameDialog = false
2070− vm.renameSession(newName)
2071− },
2072− )
2073− }
2074−
2075− if (showDeleteDialog) {
2076− AlertDialog(
2077− onDismissRequest = { showDeleteDialog = false },
2078− title = { Text(stringResource(R.string.delete_session_chat_title)) },
2079− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2080− confirmButton = {
2081− TextButton(onClick = {
2082− showDeleteDialog = false
2083− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2084− vm.deleteSession()
2085− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2086− },
2087− dismissButton = {
2088− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2089− },
2090− )
2091− }
2092−
2093− if (showShellDialog) {
2094− ShellCommandDialog(
2095− onDismiss = { showShellDialog = false },
2096− onRun = { cmd ->
2097− showShellDialog = false
2098− vm.runShell(cmd)
2099− },
2100− )
2101− }
2102−
2103− if (showModelPicker) {
2104− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2105− // to, dropping any whose model is no longer offered by the server. Ordered by
2106− // recency (head of the store first).
2107− val recentOptions = remember(models, recentModelEntries) {
2108− val byKey = models.associateBy { it.providerID to it.modelID }
2109− recentModelEntries.mapNotNull { entry ->
2110− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2111− }
2112− }
2113− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2114− // below isn't @Composable, so stringResource can't be called inside it.
2115− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2116− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2117− ModelPickerSheet(
2118− options = models,
2119− selected = selectedModel,
2120− loading = modelsLoading,
2121− error = modelsError,
2122− onSelect = {
2123− vm.selectModel(it)
2124− container.recentModelsStore.add(it.providerID, it.modelID)
2125− },
2126− onRetry = { vm.reloadModels() },
2127− onDismiss = { showModelPicker = false },
2128− preferredModelId = preferredModelId,
2129− onSetPreferredModel = { id ->
2130− scope.launch {
2131− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2132− // Confirm the change with a snackbar so the user sees it took effect —
2133− // the toggle's label flip can be missed, especially when clearing.
2134− val msg = if (id.isEmpty()) {
2135− defaultModelClearedMsg
2136− } else {
2137− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2138− defaultModelSetFmt.format(label)
2139− }
2140− snackbar.showSnackbar(msg)
2141− }
2142− },
2143− recent = recentOptions,
2144− )
2145− }
2146−
2147− if (showAgentPicker) {
2148− AgentPickerSheet(
2149− agents = agents,
2150− selected = selectedAgent,
2151− loading = agentsLoading,
2152− error = agentsError,
2153− onSelect = { vm.selectAgent(it?.name) },
2154− onRetry = { vm.reloadAgents() },
2155− onDismiss = { showAgentPicker = false },
2156− )
2157− }
2158−
2159− if (showCommandPicker) {
2160− CommandPickerSheet(
2161− commands = commands,
2162− loading = commandsLoading,
2163− error = commandsError,
2164− onSelect = { vm.runCommand(it) },
2165− onRetry = { vm.reloadCommands() },
2166− onDismiss = { showCommandPicker = false },
2167− )
2168− }
2169−
2170− pendingPermission?.let { permission ->
2171− PermissionDialog(
2172− permission = permission,
2173− position = permissionProgress.position,
2174− total = permissionProgress.total,
2175− onRespond = { response -> vm.respondPermission(permission, response) },
2176− // On auto-reject timeout, post a notification so a returning user finds a
2177− // persistent record of why the run stopped (the dialog itself is gone).
2178− // Gated by the user's notification setting (notifPermission).
2179− onAutoReject = {
2180− val conn = activeConnection
2181− val ctx = appContext
2182− val title = sessionTitle ?: sessionId
2183− if (notifPermission) {
2184− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2185− ctx, sessionId, title, conn?.profile?.id,
2186− )
2187− }
2188− },
2189− )
2190− }
2191−
2192− if (showPalette) {
2193− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2194− }
2195−
2196− if (showShortcutsDialog) {
2197− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2198− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2199− // depends on the "Send on Enter" setting, noted inline.
2200− AlertDialog(
2201− onDismissRequest = { showShortcutsDialog = false },
2202− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2203− text = {
2204− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2205− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2206− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2207− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2208− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2209− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2210− }
2211− },
2212− confirmButton = {
2213− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2214− },
2215− )
2216− }
2217−}
2218−
2219−@Composable
2220−private fun ShortcutRow(keys: String, desc: String) {
2221− Row(verticalAlignment = Alignment.CenterVertically) {
2222− Text(
2223− keys,
2224− style = MaterialTheme.typography.labelLarge,
2225− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2226− modifier = Modifier.widthIn(min = 160.dp),
2227− )
2228− Text(
2229− desc,
2230− style = MaterialTheme.typography.bodyMedium,
2231− color = MaterialTheme.colorScheme.onSurfaceVariant,
2232− )
2233− }
2234−}
2235−
2236−/**
2237− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2238− * of matching commands above the composer. Tapping a command fires it immediately.
2239− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2240− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2241− */
2242−@Composable
2243−private fun SlashCommandAutocomplete(
2244− value: String,
2245− commands: List<Command>,
2246− running: Boolean,
2247− onRunCommand: (Command) -> Unit,
2248−) {
2249− if (running || commands.isEmpty()) return
2250− val slashQuery = remember(value) {
2251− if (value.startsWith("/")) value.removePrefix("/") else null
2252− } ?: return
2253− val matchingCommands = remember(slashQuery, commands) {
2254− commands.filter { cmd ->
2255− slashQuery.isEmpty() ||
2256− cmd.name.contains(slashQuery, ignoreCase = true) ||
2257− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2258− }.take(8)
2259− }
2260− if (matchingCommands.isNotEmpty()) {
2261− CommandAutocompleteDropdown(
2262− commands = matchingCommands,
2263− onPick = onRunCommand,
2264− )
2265− }
2266−}
2267−
2268−/**
2269− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2270− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2271− * user can discover and invoke commands by typing the conventional "/" prefix instead
2272− * of opening the overflow menu / command palette. Tapping a row fires the command.
2273− */
2274−@Composable
2275−private fun CommandAutocompleteDropdown(
2276− commands: List<Command>,
2277− onPick: (Command) -> Unit,
2278−) {
2279− val haptics = LocalHapticFeedback.current
2280− Surface(
2281− color = MaterialTheme.colorScheme.surface,
2282− tonalElevation = 3.dp,
2283− shape = MaterialTheme.shapes.medium,
2284− modifier = Modifier
2285− .fillMaxWidth()
2286− .padding(horizontal = 8.dp, vertical = 4.dp)
2287− .heightIn(max = 240.dp),
2288− ) {
2289− LazyColumn {
2290− items(
2291− count = commands.size,
2292− key = { commands[it].name },
2293− ) { i ->
2294− val cmd = commands[i]
2295− Row(
2296− modifier = Modifier
2297− .fillMaxWidth()
2298− .clickable(role = Role.Button) {
2299− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2300− onPick(cmd)
2301− }
2302− .padding(horizontal = 16.dp, vertical = 10.dp),
2303− verticalAlignment = Alignment.CenterVertically,
2304− horizontalArrangement = Arrangement.spacedBy(12.dp),
2305− ) {
2306− Text(
2307− "/${cmd.name}",
2308− style = MaterialTheme.typography.labelLarge,
2309− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2310− color = MaterialTheme.colorScheme.primary,
2311− )
2312− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2313− Text(
2314− desc,
2315− style = MaterialTheme.typography.bodySmall,
2316− color = MaterialTheme.colorScheme.onSurfaceVariant,
2317− maxLines = 1,
2318− overflow = TextOverflow.Ellipsis,
2319− )
2320− }
2321− }
2322− }
2323− }
2324− }
2325−}
2326−
2327−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2328−@Suppress("CyclomaticComplexMethod")
2329−@Composable
2330−private fun ChatInputBar(
2331− value: String,
2332− onValueChange: (String) -> Unit,
2333− running: Boolean,
2334− aborting: Boolean,
2335− enabled: Boolean,
2336− sendOnEnter: Boolean,
2337− onSend: () -> Unit,
2338− onAbort: () -> Unit,
2339− queuedFollowUp: String?,
2340− onQueueFollowUp: (String) -> Unit,
2341− onCancelQueue: () -> Unit,
2342− focusRequester: androidx.compose.ui.focus.FocusRequester,
2343− attachments: List<PendingAttachment>,
2344− staging: Boolean,
2345− stagingFileCount: Int,
2346− onRemoveAttachment: (String) -> Unit,
2347− onPickPhoto: () -> Unit,
2348− onPickFile: () -> Unit,
2349− onCamera: () -> Unit,
2350− onVoice: () -> Unit,
2351− onPasteImage: (List<Uri>) -> Unit,
2352− commands: List<Command> = emptyList(),
2353− onRunCommand: (Command) -> Unit = {},
2354−) {
2355− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2356− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2357− val context = LocalContext.current
2358− // Full-screen editor state: opened when the user wants more space for a long prompt.
2359− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2360− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2361− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2362− // A queued follow-up replaces the Stop button with a "queued" chip so the
2363− // user sees their message will be sent when the run finishes, and can cancel.
2364− if (queuedFollowUp != null) {
2365− val editLabel = stringResource(R.string.edit)
2366− Row(
2367− modifier = Modifier
2368− .fillMaxWidth()
2369− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2370− verticalAlignment = Alignment.CenterVertically,
2371− ) {
2372− // Tapping the chip reloads the queued text into the draft (and clears the
2373− // queue) so a typo spotted while queuing can be fixed without retyping.
2374− Column(
2375− modifier = Modifier
2376− .weight(1f)
2377− .clip(MaterialTheme.shapes.small)
2378− .clickable(role = Role.Button, onClickLabel = editLabel) {
2379− onValueChange(queuedFollowUp)
2380− onCancelQueue()
2381− }
2382− .padding(vertical = 4.dp),
2383− ) {
2384− Text(
2385− stringResource(R.string.queued),
2386− style = MaterialTheme.typography.labelSmall,
2387− color = MaterialTheme.colorScheme.onSurfaceVariant,
2388− )
2389− Text(
2390− queuedFollowUp,
2391− style = MaterialTheme.typography.bodySmall,
2392− color = MaterialTheme.colorScheme.onSurfaceVariant,
2393− maxLines = 1,
2394− overflow = TextOverflow.Ellipsis,
2395− )
2396− }
2397− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2398− Text(stringResource(R.string.cancel))
2399− }
2400− }
2401− }
2402− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2403− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2404− // Slash-command autocomplete: extracted to a helper to keep this function's
2405− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2406− // start with "/" or the command catalog is empty.
2407− SlashCommandAutocomplete(
2408− value = value,
2409− commands = commands,
2410− running = running,
2411− onRunCommand = onRunCommand,
2412− )
2413− Row(
2414− modifier = Modifier.fillMaxWidth().padding(8.dp),
2415− verticalAlignment = Alignment.Bottom,
2416− ) {
2417− // Attach menu: photo picker, camera, or any file.
2418− var showAttachMenu by remember { mutableStateOf(false) }
2419− Box {
2420− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2421− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2422− }
2423− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2424− DropdownMenuItem(
2425− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2426− text = { Text(stringResource(R.string.attach_photo)) },
2427− onClick = { showAttachMenu = false; onPickPhoto() },
2428− )
2429− DropdownMenuItem(
2430− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2431− text = { Text(stringResource(R.string.attach_camera)) },
2432− onClick = { showAttachMenu = false; onCamera() },
2433− )
2434− DropdownMenuItem(
2435− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2436− text = { Text(stringResource(R.string.attach_file)) },
2437− onClick = { showAttachMenu = false; onPickFile() },
2438− )
2439− }
2440− }
2441− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2442− // disabled) when the device has no speech-recognition activity, so a user
2443− // without a voice app doesn't get a button that only fails noisily on tap.
2444− val voiceAvailable = remember {
2445− val pm = context.packageManager
2446− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2447− pm.queryIntentActivities(intent, 0).isNotEmpty()
2448− }
2449− if (voiceAvailable) {
2450− IconButton(onClick = onVoice, enabled = enabled) {
2451− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2452− }
2453− }
2454− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2455− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2456− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2457− }
2458− OutlinedTextField(
2459− value = value,
2460− onValueChange = { v ->
2461− // Cap input length so a huge paste can't stall the UI. Shares are
2462− // capped separately in MainActivity; this guards typed/pasted drafts.
2463− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2464− },
2465− modifier = Modifier
2466− .weight(1f)
2467− .focusRequester(focusRequester)
2468− .testTag("chat_input")
2469− // Intercept image content pasted/dropped into the field (keyboard paste
2470− // of a copied screenshot, drag from Files, etc.) and route it through the
2471− // same staging path as the attach menu. Non-image content (text) falls
2472− // through unchanged so normal typing/paste works.
2473− .contentReceiver(
2474− remember {
2475− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2476− val clipData = transferable.clipEntry?.clipData
2477− if (clipData != null) {
2478− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2479− val item = clipData.getItemAt(i)
2480− item.uri?.takeIf { uri ->
2481− item.text == null && uri.toString().let { s ->
2482− s.startsWith("content:") || s.startsWith("file:")
2483− }
2484− }
2485− }
2486− if (imageUris.isNotEmpty()) {
2487− onPasteImage(imageUris)
2488− }
2489− }
2490− transferable
2491− }
2492− },
2493− )
2494− .onPreviewKeyEvent { event ->
2495− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2496− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2497− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2498− val send = enterShouldSend(
2499− enabled = enabled,
2500− hasContent = hasContent,
2501− sendOnEnter = sendOnEnter,
2502− shift = event.isShiftPressed,
2503− ctrl = event.isCtrlPressed,
2504− )
2505− if (send) {
2506− if (running) onQueueFollowUp(value) else onSend()
2507− true
2508− } else {
2509− false
2510− }
2511− },
2512− // While a run is active a typed message only queues (sends after the run), so
2513− // the placeholder says so instead of the plain "Message…".
2514− placeholder = {
2515− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2516− },
2517− enabled = enabled,
2518− maxLines = 6,
2519− // Show a "N / max" countdown once the draft crosses a high fraction of
2520− // the cap, so the user knows a paste is about to be truncated instead
2521− // of being silently cut off. Hidden for normal short prompts to avoid
2522− // clutter under a typical one-line message.
2523− supportingText = {
2524− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2525− if (value.length >= threshold) {
2526− Text(
2527− stringResource(
2528− R.string.draft_chars_remaining,
2529− NetworkConfig.maxDraftLengthChars - value.length,
2530− NetworkConfig.maxDraftLengthChars,
2531− ),
2532− style = MaterialTheme.typography.labelSmall,
2533− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2534− else MaterialTheme.colorScheme.onSurfaceVariant,
2535− )
2536− } else if (value.lines().size > 6) {
2537− // The inline field caps at 6 lines; once the draft crosses that,
2538− // hint that a bigger full-screen editor exists (the Expand icon
2539− // above is easy to miss among the icon row). A tappable label
2540− // would be ideal, but a plain hint is enough to draw attention.
2541− Text(
2542− stringResource(R.string.open_full_editor_hint),
2543− style = MaterialTheme.typography.labelSmall,
2544− color = MaterialTheme.colorScheme.onSurfaceVariant,
2545− )
2546− }
2547− },
2548− keyboardOptions = KeyboardOptions(
2549− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2550− // keyboard shows a send key — matching the setting's intent and
2551− // giving touch-only users a keyboard send affordance. When off,
2552− // ImeAction.Default keeps the enter/newline key for multi-line input.
2553− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2554− capitalization = KeyboardCapitalization.Sentences,
2555− ),
2556− keyboardActions = KeyboardActions(
2557− onSend = {
2558− // Mirror the hardware-Enter handler: during a run the soft-keyboard
2559− // send key must queue the follow-up, not silently drop it. vm.send()
2560− // returns false while a run is active (beginRun() rejects), so calling
2561− // onSend() directly here would lose the typed message with no feedback
2562− // for touch-only users (no hardware Enter path available).
2563− if (enabled && hasContent) {
2564− if (running) onQueueFollowUp(value) else onSend()
2565− }
2566− },
2567− ),
2568− )
2569− ComposerTrailingButton(
2570− running = running,
2571− aborting = aborting,
2572− canSend = enabled && hasContent,
2573− canQueue = enabled && value.isNotBlank(),
2574− onSend = onSend,
2575− onAbort = onAbort,
2576− onQueue = { onQueueFollowUp(value) },
2577− )
2578− }
2579− }
2580− if (showFullScreenEditor) {
2581− FullScreenEditor(
2582− value = value,
2583− onValueChange = onValueChange,
2584− onDismiss = { showFullScreenEditor = false },
2585− onSend = {
2586− showFullScreenEditor = false
2587− // Mirror the inline composer's behavior: while a run is active a send
2588− // can't go immediately, so queue the follow-up instead of silently
2589− // dropping it (vm.send() returns false during a run, which previously
2590− // lost the typed message with no feedback).
2591− if (running) onQueueFollowUp(value) else onSend()
2592− },
2593− canSend = enabled && hasContent,
2594− running = running,
2595− sendOnEnter = sendOnEnter,
2596− attachments = attachments,
2597− onRemoveAttachment = onRemoveAttachment,
2598− staging = staging,
2599− stagingFileCount = stagingFileCount,
2600− )
2601− }
2602− }
2603−}
2604−
2605−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2606− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2607−@OptIn(ExperimentalMaterial3Api::class)
2608−@Composable
2609−private fun FullScreenEditor(
2610− value: String,
2611− onValueChange: (String) -> Unit,
2612− onDismiss: () -> Unit,
2613− onSend: () -> Unit,
2614− canSend: Boolean,
2615− running: Boolean = false,
2616− sendOnEnter: Boolean = false,
2617− attachments: List<PendingAttachment> = emptyList(),
2618− onRemoveAttachment: (String) -> Unit = {},
2619− staging: Boolean = false,
2620− stagingFileCount: Int = 0,
2621−) {
2622− androidx.compose.ui.window.Dialog(
2623− onDismissRequest = onDismiss,
2624− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2625− ) {
2626− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2627− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2628− // gives the available width so we can center a capped-width column.
2629− androidx.compose.foundation.layout.BoxWithConstraints(
2630− modifier = Modifier.fillMaxSize(),
2631− contentAlignment = Alignment.Center,
2632− ) {
2633− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2634− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2635− else 0.dp
2636− Scaffold(
2637− modifier = Modifier.padding(horizontal = hPad),
2638− topBar = {
2639− androidx.compose.material3.TopAppBar(
2640− title = { Text(stringResource(R.string.compose_editor_title)) },
2641− navigationIcon = {
2642− androidx.compose.material3.TextButton(onClick = onDismiss) {
2643− Text(stringResource(R.string.collapse_editor))
2644− }
2645− },
2646− )
2647− },
2648− bottomBar = {
2649− Surface(tonalElevation = 3.dp) {
2650− Row(
2651− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2652− horizontalArrangement = Arrangement.End,
2653− ) {
2654− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2655− Text(stringResource(if (running) R.string.queue else R.string.send))
2656− }
2657− }
2658− }
2659− },
2660− ) { padding ->
2661− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2662− // Show staged attachments in the full-screen editor too, so a user who staged
2663− // images then expanded for a long prompt can still see and remove them without
2664− // collapsing first (mirrors the inline composer's AttachmentStrip).
2665− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2666− OutlinedTextField(
2667− value = value,
2668− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2669− modifier = Modifier
2670− .fillMaxSize()
2671− .weight(1f)
2672− // Honor the "Send on Enter" setting here too, so the full-screen
2673− // editor matches the inline composer: Enter sends (Shift+Enter
2674− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2675− // when off. Previously this hard-coded ImeAction.Default and had no
2676− // key handler, so a hardware-keyboard user got a different behaviour
2677− // from the inline composer depending on which they happened to open.
2678− .onPreviewKeyEvent { event ->
2679− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2680− val send = enterShouldSend(
2681− enabled = canSend,
2682− hasContent = canSend,
2683− sendOnEnter = sendOnEnter,
2684− shift = event.isShiftPressed,
2685− ctrl = event.isCtrlPressed,
2686− )
2687− if (send) { onSend(); true } else false
2688− },
2689− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2690− maxLines = Int.MAX_VALUE,
2691− keyboardOptions = KeyboardOptions(
2692− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2693− capitalization = KeyboardCapitalization.Sentences,
2694− ),
2695− keyboardActions = KeyboardActions(
2696− onSend = { if (canSend) onSend() },
2697− ),
2698− )
2699− }
2700− }
2701− }
2702− }
2703−}
2704−
2705−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2706− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2707−private fun enterShouldSend(
2708− enabled: Boolean,
2709− hasContent: Boolean,
2710− sendOnEnter: Boolean,
2711− shift: Boolean,
2712− ctrl: Boolean,
2713−): Boolean = when {
2714− !enabled || !hasContent -> false
2715− sendOnEnter -> !shift
2716− else -> ctrl
2717−}
2718−
2719−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2720− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2721− * [ChatInputBar] stays under the complexity threshold. */
2722−@Composable
2723−private fun ComposerTrailingButton(
2724− running: Boolean,
2725− aborting: Boolean,
2726− canSend: Boolean,
2727− canQueue: Boolean,
2728− onSend: () -> Unit,
2729− onAbort: () -> Unit,
2730− onQueue: () -> Unit,
2731−) {
2732− if (running) {
2733− Row(verticalAlignment = Alignment.CenterVertically) {
2734− // While a run is active the trailing action is Stop, so the only send affordance is
2735− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2736− // That leaves a touch-only user with the setting off no way to queue a follow-up
2737− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2738− // there's typed TEXT so queuing is always reachable, without changing the user's
2739− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2740− // canSend, which is also true for an attachment-only composer — because queuing "" just
2741− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2742− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2743− if (canQueue) {
2744− IconButton(
2745− onClick = onQueue,
2746− modifier = Modifier.testTag("queue_button"),
2747− ) {
2748− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2749− // icon (which can be read as "snooze" or "later"), and isn't confused with
2750− // the Send action sitting right beside the Stop button.
2751− Icon(
2752− Icons.AutoMirrored.Filled.PlaylistAdd,
2753− contentDescription = stringResource(R.string.queue_followup),
2754− )
2755− }
2756− }
2757− // Show a spinner while the abort REST call is in flight so the user sees the stop
2758− // was sent, and disable to prevent a double-tap.
2759− IconButton(
2760− onClick = onAbort,
2761− enabled = !aborting,
2762− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2763− ) {
2764− if (aborting) {
2765− val stopLabel = stringResource(R.string.stop)
2766− CircularProgressIndicator(
2767− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2768− strokeWidth = 2.dp,
2769− )
2770− } else {
2771− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2772− }
2773− }
2774− }
2775− } else {
2776− IconButton(
2777− onClick = onSend,
2778− enabled = canSend,
2779− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2780− ) {
2781− // Tint the send icon with primary when there's content to send so the commit action
2782− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2783− Icon(
2784− Icons.AutoMirrored.Filled.Send,
2785− contentDescription = stringResource(R.string.send),
2786− tint = if (canSend) MaterialTheme.colorScheme.primary
2787− else MaterialTheme.colorScheme.onSurfaceVariant,
2788− )
2789− }
2790− }
2791−}
2792−
2793−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2794−@Composable
2795−private fun EmptyConversation(
2796− onSuggestion: (String) -> Unit,
2797− modifier: Modifier = Modifier,
2798−) {
2799− // A few example prompts so a first-time user has a one-tap path to their first
2800− // message instead of staring at a blank input. Tapping a chip fills the draft
2801− // (without sending) so the user can edit it before sending.
2802− val suggestions = remember {
2803− listOf(
2804− R.string.empty_chat_suggest_1,
2805− R.string.empty_chat_suggest_2,
2806− R.string.empty_chat_suggest_3,
2807− )
2808− }
2809− Column(
2810− modifier = modifier.padding(32.dp),
2811− horizontalAlignment = Alignment.CenterHorizontally,
2812− ) {
2813− Icon(
2814− Icons.Filled.AutoAwesome,
2815− contentDescription = null,
2816− modifier = Modifier.size(48.dp),
2817− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2818− )
2819− Spacer(Modifier.size(16.dp))
2820− Text(
2821− stringResource(R.string.empty_chat_title),
2822− style = MaterialTheme.typography.titleMedium,
2823− )
2824− Spacer(Modifier.size(8.dp))
2825− Text(
2826− stringResource(R.string.empty_chat_hint),
2827− style = MaterialTheme.typography.bodyMedium,
2828− color = MaterialTheme.colorScheme.onSurfaceVariant,
2829− )
2830− Spacer(Modifier.size(20.dp))
2831− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2832− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2833− FlowRow(
2834− modifier = Modifier.fillMaxWidth(),
2835− horizontalArrangement = Arrangement.spacedBy(8.dp),
2836− verticalArrangement = Arrangement.spacedBy(8.dp),
2837− ) {
2838− suggestions.forEach { resId ->
2839− val text = stringResource(resId)
2840− androidx.compose.material3.AssistChip(
2841− onClick = { onSuggestion(text) },
2842− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2843− )
2844− }
2845− }
2846− }
2847−}
2848−
2849−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2850− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2851− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2852−@Composable
2853−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2854− val haptics = LocalHapticFeedback.current
2855− var showDiff by rememberSaveable { mutableStateOf(false) }
2856− val expandMotion = rememberVisibilityTransitions()
2857− Surface(
2858− color = MaterialTheme.colorScheme.tertiaryContainer,
2859− tonalElevation = 2.dp,
2860− modifier = Modifier.fillMaxWidth(),
2861− ) {
2862− Column {
2863− Row(
2864− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2865− verticalAlignment = Alignment.CenterVertically,
2866− horizontalArrangement = Arrangement.SpaceBetween,
2867− ) {
2868− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2869− Icon(
2870− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2871− contentDescription = null,
2872− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2873− modifier = Modifier.size(18.dp),
2874− )
2875− Text(
2876− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2877− style = MaterialTheme.typography.bodySmall,
2878− color = MaterialTheme.colorScheme.onTertiaryContainer,
2879− modifier = Modifier.padding(start = 8.dp),
2880− )
2881− // "Show what changed" toggle, shown only when the server provided a diff.
2882− // Collapsible so the banner stays compact by default; a user curious about
2883− // what the revert rolled back can expand it inline without leaving the chat.
2884− if (!diff.isNullOrBlank()) {
2885− TextButton(
2886− onClick = {
2887− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2888− showDiff = !showDiff
2889− },
2890− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2891− ) {
2892− Icon(
2893− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2894− contentDescription = null,
2895− modifier = Modifier.size(16.dp),
2896− )
2897− Text(
2898− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2899− style = MaterialTheme.typography.labelSmall,
2900− modifier = Modifier.padding(start = 4.dp),
2901− )
2902− }
2903− }
2904− }
2905− TextButton(onClick = {
2906− // Haptic on undo to match the other destructive/important confirmations: a
2907− // revert restores potentially hundreds of hidden messages.
2908− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2909− onUndo()
2910− }) { Text(stringResource(R.string.undo)) }
2911− }
2912− // The diff render lives inside the banner's Surface so it inherits the tertiary
2913− // tonal container and reads as part of the banner, not a floating panel.
2914− if (!diff.isNullOrBlank()) {
2915− AnimatedVisibility(
2916− visible = showDiff,
2917− enter = expandMotion.enter,
2918− exit = expandMotion.exit,
2919− ) {
2920− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2921− Text(
2922− stringResource(R.string.revert_diff_header),
2923− style = MaterialTheme.typography.labelSmall,
2924− color = MaterialTheme.colorScheme.onTertiaryContainer,
2925− modifier = Modifier.padding(bottom = 4.dp),
2926− )
2927− DiffView(diff, saveKey = "revertDiff")
2928− }
2929− }
2930− }
2931− }
2932− }
2933−}
2934−
2935−/** A dismissible preview card shown above the composer when the user quote-replied to a
2936− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2937− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2938− * the Discord/Slack quote-preview pattern. */
2939−@Composable
2940−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2941− val haptics = LocalHapticFeedback.current
2942− Surface(
2943− color = MaterialTheme.colorScheme.secondaryContainer,
2944− tonalElevation = 2.dp,
2945− modifier = Modifier.fillMaxWidth(),
2946− ) {
2947− Row(
2948− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2949− verticalAlignment = Alignment.Top,
2950− ) {
2951− Icon(
2952− Icons.Filled.FormatQuote,
2953− contentDescription = null,
2954− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2955− modifier = Modifier.size(18.dp).padding(top = 2.dp),
2956− )
2957− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2958− Text(
2959− stringResource(R.string.quote_reply_banner),
2960− style = MaterialTheme.typography.labelSmall,
2961− color = MaterialTheme.colorScheme.onSecondaryContainer,
2962− )
2963− Text(
2964− quotedText,
2965− style = MaterialTheme.typography.bodySmall,
2966− color = MaterialTheme.colorScheme.onSecondaryContainer,
2967− maxLines = 2,
2968− overflow = TextOverflow.Ellipsis,
2969− )
2970− }
2971− IconButton(onClick = {
2972− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2973− onCancel()
2974− }) {
2975− Icon(
2976− Icons.Filled.Close,
2977− contentDescription = stringResource(R.string.cancel_quote_reply),
2978− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2979− modifier = Modifier.size(18.dp),
2980− )
2981− }
2982− }
2983− }
2984−}
2985−
2986−/** A banner shown while messages composed offline are queued in the outbox, with a
2987− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2988−@Composable
2989−private fun OutboxBanner(
2990− count: Int,
2991− sending: Boolean,
2992− onFlush: () -> Unit,
2993− onDiscard: () -> Unit,
2994−) {
2995− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
2996− Surface(
2997− color = MaterialTheme.colorScheme.secondaryContainer,
2998− tonalElevation = 2.dp,
2999− modifier = Modifier.fillMaxWidth(),
3000− ) {
3001− Row(
3002− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
3003− verticalAlignment = Alignment.CenterVertically,
3004− horizontalArrangement = Arrangement.SpaceBetween,
3005− ) {
3006− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
3007− if (sending) {
3008− CircularProgressIndicator(
3009− Modifier.size(16.dp),
3010− strokeWidth = 2.dp,
3011− color = MaterialTheme.colorScheme.onSecondaryContainer,
3012− )
3013− Spacer(Modifier.size(8.dp))
3014− }
3015− Text(
3016− if (sending) {
3017− stringResource(R.string.outbox_sending)
3018− } else {
3019− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
3020− stringResource(res, count)
3021− },
3022− style = MaterialTheme.typography.bodySmall,
3023− color = MaterialTheme.colorScheme.onSecondaryContainer,
3024− )
3025− }
3026− if (!sending) {
3027− val haptics = LocalHapticFeedback.current
3028− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
3029− TextButton(onClick = {
3030− // Confirm before discarding all queued messages (irreversible), matching
3031− // the confirmation pattern used by deleteSession and other destructive
3032− // actions. Previously a single tap dropped every queued message.
3033− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
3034− showDiscardConfirm = true
3035− }) {
3036− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
3037− }
3038− }
3039− }
3040− }
3041− if (showDiscardConfirm) {
3042− androidx.compose.material3.AlertDialog(
3043− onDismissRequest = { showDiscardConfirm = false },
3044− title = { Text(stringResource(R.string.discard_queued_title)) },
3045− text = { Text(stringResource(R.string.discard_queued_text, count)) },
3046− confirmButton = {
3047− androidx.compose.material3.TextButton(onClick = {
3048− showDiscardConfirm = false
3049− onDiscard()
3050− }) { Text(stringResource(R.string.discard)) }
3051− },
3052− dismissButton = {
3053− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3054− Text(stringResource(R.string.cancel))
3055− }
3056− },
3057− )
3058− }
3059−}
3060−
3061−/** Prompt for a one-off shell command to run in the session's worktree. */
3062−@Composable
3063−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3064− var command by rememberSaveable { mutableStateOf("") }
3065− AlertDialog(
3066− onDismissRequest = onDismiss,
3067− title = { Text(stringResource(R.string.run_shell_command)) },
3068− text = {
3069− OutlinedTextField(
3070− value = command,
3071− onValueChange = { command = it },
3072− modifier = Modifier.fillMaxWidth(),
3073− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3074− label = { Text(stringResource(R.string.shell_command_label)) },
3075− singleLine = true,
3076− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3077− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3078− )
3079− },
3080− confirmButton = {
3081− TextButton(
3082− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3083− enabled = command.isNotBlank(),
3084− ) { Text(stringResource(R.string.run)) }
3085− },
3086− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3087− )
3088−}
3089−
3090−/**
3091− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3092− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3093− * equality is structural so `snapshotFlow` emits only when something relevant changes.
3094− */
3095−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3096−
3097−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3098− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3099− * streaming, not just plain assistant text. O(1). */
3100−private fun streamingContentLength(part: Part?): Int = when (part) {
3101− is TextPart -> part.text.length
3102− is ReasoningPart -> part.text.length
3103− is ToolPart -> when (val st = part.state) {
3104− is ToolCompleted -> st.output?.length ?: 0
3105− is ToolError -> st.error?.length ?: 0
3106− is ToolRunning -> st.title?.length ?: 0
3107− else -> 0
3108− }
3109− else -> 0
3110−}
3111−
3112−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3113− * dialog but lives in the chat screen so the user can rename without backing out to
3114− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3115−@Composable
3116−private fun RenameSessionChatDialog(
3117− initialTitle: String,
3118− onDismiss: () -> Unit,
3119− onConfirm: (String) -> Unit,
3120−) {
3121− // Seed the field once (no key input) so a later external title change — e.g. opencode
3122− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3123− // doesn't re-initialize the box and discard the user's in-progress edit.
3124− var title by rememberSaveable { mutableStateOf(initialTitle) }
3125− AlertDialog(
3126− onDismissRequest = onDismiss,
3127− title = { Text(stringResource(R.string.rename_session_chat)) },
3128− text = {
3129− OutlinedTextField(
3130− value = title,
3131− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3132− modifier = Modifier.fillMaxWidth(),
3133− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3134− label = { Text(stringResource(R.string.rename_session_chat)) },
3135− singleLine = true,
3136− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3137− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3138− )
3139− },
3140− confirmButton = {
3141− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3142− Text(stringResource(R.string.save))
3143− }
3144− },
3145− dismissButton = {
3146− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3147− },
3148− )
3149−}
3150−
3151−/**
3152− * A single item in the chat message list — either a [Message] bubble or a day
3153− * [Separator] inserted before the first message of a new day. The separator shifts
3154− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3155− * the [List] of these items (not `messages.size`/`lastIndex`).
3156− */
3157−private sealed interface MessageListItem {
3158− val key: Any
3159− val contentType: Any
3160−
3161− data class Message(
3162− val message: MessageWithParts,
3163− override val key: Any,
3164− // Whether this is the first message in a consecutive run of the same speaker (role).
3165− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3166− // reducing visual noise in tool-heavy conversations where many assistant messages
3167− // appear back-to-back. A separator or a role change resets the flag.
3168− val isFirstOfSpeaker: Boolean,
3169− ) : MessageListItem {
3170− override val contentType: Any get() = message.info::class
3171− }
3172−
3173− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3174− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3175− // can share a label (e.g. an untimestamped message — empty label — between two
3176− // same-day messages, or two untimestamped groups), and a label-only key would
3177− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3178− // stable for a given message ordering so slots aren't needlessly recreated.
3179− override val key: Any get() = "sep_${ordinal}_$label"
3180− // Separators share a contentType so the LazyColumn can recycle their slots.
3181− override val contentType: Any get() = "separator"
3182− }
3183−}
3184−
3185−/**
3186− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3187− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3188− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3189− * Messages with no timestamp are grouped under an empty-label separator only if they
3190− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3191− *
3192− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3193− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3194− * labels; older days fall back to a locale-stable medium-date format.
3195− */
3196−private fun buildMessageListItems(
3197− messages: List<MessageWithParts>,
3198− todayLabel: String,
3199− yesterdayLabel: String,
3200−): List<MessageListItem> {
3201− if (messages.isEmpty()) return emptyList()
3202− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3203− val dateFmt = mediumDateFormat()
3204− val result = ArrayList<MessageListItem>(messages.size + 4)
3205− val seenKeys = HashSet<String>(messages.size * 2)
3206− var lastDayKey: String? = null
3207− var sepOrdinal = 0
3208− var emptyIdOrdinal = 0
3209− var first = true
3210− // Track the previous message's role to detect consecutive same-speaker runs, so the
3211− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3212− // "no previous message or a separator just interrupted the run", both of which make the
3213− // next message the first of its group.
3214− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3215− for (message in messages) {
3216− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3217− val dayKey = ts?.let { dayKey(it) } ?: ""
3218− // Emit a separator before the very first message (so a leading un-timestamped message
3219− // still gets the first divider, empty label and all), and thereafter only when crossing
3220− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3221− // neither emits its own separator nor resets the day — otherwise a following same-day
3222− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3223− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3224− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3225− // A date separator visually breaks a speaker run, so the next message is treated
3226− // as the first of its group (even if the same role continues across the day break).
3227− prevRoleClass = null
3228− }
3229− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3230− first = false
3231− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3232− // empty id — and the reducer intentionally keeps several such messages as distinct
3233− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3234− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3235− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3236− if (!seenKeys.add(key)) {
3237− var suffix = 1
3238− while (!seenKeys.add("$key#$suffix")) suffix++
3239− key = "$key#$suffix"
3240− }
3241− val roleClass = message.info::class
3242− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3243− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3244− prevRoleClass = roleClass
3245− }
3246− return result
3247−}
3248−
3249−/**
3250− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3251− *
3252− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3253− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3254− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3255− * every message on every token. Message timestamps are immutable once assigned, so we
3256− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3257− * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3258− *
3259− * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3260− * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3261− * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3262− * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3263− * reads, so the common case (a hit) is a single volatile read + hash probe. The bound
3264− * is enforced via [removeEldestEntry] is not available on ConcurrentHashMap, so we cap
3265− * via `compute`-guarded size checks; in practice the cache size is bounded by the number
3266− * of distinct message timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]).
3267− */
3268−private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3269−
3270−private fun dayKey(epochMillis: Long): String = dayKeyCache.getOrPut(epochMillis) {
3271− java.time.Instant.ofEpochMilli(epochMillis)
3272− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3273−}
3274−
3275−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3276−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3277−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3278−private var cachedDateFmt: java.text.DateFormat? = null
3279−private var cachedDateFmtLocale: java.util.Locale? = null
3280−
3281−private fun mediumDateFormat(): java.text.DateFormat {
3282− val locale = java.util.Locale.getDefault()
3283− val existing = cachedDateFmt
3284− if (existing != null && cachedDateFmtLocale == locale) return existing
3285− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3286− cachedDateFmt = it
3287− cachedDateFmtLocale = locale
3288− }
3289−}
3290−
3291−/**
3292− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3293− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3294− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3295− * messages.
3296− */
3297−private fun dayLabel(
3298− dayKey: String,
3299− ts: Long,
3300− today: java.time.LocalDate,
3301− todayLabel: String,
3302− yesterdayLabel: String,
3303− dateFmt: java.text.DateFormat,
3304−): String {
3305− if (dayKey.isEmpty()) return ""
3306− val epochDay = dayKey.toLongOrNull() ?: return ""
3307− val date = java.time.LocalDate.ofEpochDay(epochDay)
3308− return when {
3309− date == today -> todayLabel
3310− date == today.minusDays(1) -> yesterdayLabel
3311− else -> dateFmt.format(java.util.Date(ts))
3312− }
3313−}
3314−
3315−/**
3316− * A centered day divider in the message list. Renders nothing for an empty label
3317− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3318− */
3319−@Composable
3320−private fun DateSeparator(label: String) {
3321− if (label.isBlank()) return
3322− Row(
3323− modifier = Modifier.fillMaxWidth(),
3324− horizontalArrangement = Arrangement.Center,
3325− ) {
3326− Surface(
3327− color = MaterialTheme.colorScheme.surfaceVariant,
3328− shape = MaterialTheme.shapes.small,
3329− // Marked as a heading so TalkBack users can navigate day-by-day with the
3330− // heading-skip gesture — the canonical affordance for date dividers in a list.
3331− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3332− ) {
3333− Text(
3334− label,
3335− style = MaterialTheme.typography.labelSmall,
3336− color = MaterialTheme.colorScheme.onSurfaceVariant,
3337− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3338− )
3339− }
3340− }
3341−}
3342−
3343−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3344− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3345− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3346− * [BoxScope] extension so it can align itself to the top center of its host box. */
3347−@Composable
3348−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3349− val loadingLabel = stringResource(R.string.loading)
3350− val reducedMotion = LocalReducedMotion.current
3351− val transition = rememberInfiniteTransition(label = "skeleton")
3352− val pulse by transition.animateFloat(
3353− initialValue = 0.35f,
3354− targetValue = 0.7f,
3355− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3356− label = "skeletonAlpha",
3357− )
3358− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3359− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3360− @Composable
3361− fun bar(widthFraction: Float) {
3362− Box(
3363− Modifier
3364− .fillMaxWidth(widthFraction)
3365− .height(14.dp)
3366− .clip(RoundedCornerShape(4.dp))
3367− .background(skeletonColor)
3368− .alpha(skeletonAlpha),
3369− )
3370− }
3371− Column(
3372− modifier = Modifier
3373− .align(Alignment.TopCenter)
3374− .padding(top = topPad)
3375− .padding(16.dp)
3376− .fillMaxWidth()
3377− .semantics { contentDescription = loadingLabel },
3378− verticalArrangement = Arrangement.spacedBy(14.dp),
3379− ) {
3380− repeat(4) { i ->
3381− val left = i % 2 == 0
3382− Row(
3383− modifier = Modifier.fillMaxWidth(),
3384− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3385− ) {
3386− Column(
3387− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3388− verticalArrangement = Arrangement.spacedBy(6.dp),
3389− ) {
3390− bar(1f)
3391− bar(0.8f)
3392− }
3393− }
3394− }
3395− }
3396−}