@@ -1,3432 +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− // rememberSaveable (not plain remember) so the badge count survives rotation: plain
1070− // remember resets to 0 on recreation, hiding the "new content" signal even though new
1071− // messages are still arriving. Int is Bundle-savable.
1072− var newContentCount by rememberSaveable { mutableIntStateOf(0) }
1073−
1074− val isPinnedToBottom by remember {
1075− derivedStateOf {
1076− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1077− // When a run is active, the LazyColumn has one trailing "__typing"
1078− // item after the last list item. Account for it so "pinned to bottom"
1079− // includes the working indicator — otherwise the pin check targets
1080− // listItems.lastIndex, the typing row sits just below the viewport,
1081− // and the user never sees the progress indicator even when pinned.
1082− val items = currentListItems
1083− val effectiveLast = if (running) items.size else items.lastIndex
1084− lastVisible >= effectiveLast || items.isEmpty()
1085− }
1086− }
1087−
1088− // Jump to the newest message once, when the conversation first loads. Guarded by a
1089− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1090− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1091− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1092− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1093− LaunchedEffect(listItems.isNotEmpty()) {
1094− if (listItems.isNotEmpty() && !didInitialScroll) {
1095− // When a run is active the LazyColumn has a trailing "__typing" row at
1096− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1097− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1098− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1099− didInitialScroll = true
1100− }
1101− }
1102−
1103− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1104− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1105− // isPinnedToBottom check flips to false the instant you send — freezing
1106− // auto-scroll. If the user was pinned to the last item just before the run
1107− // began, bring the typing row into view so the pin (and streaming follow) is
1108− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1109− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1110− LaunchedEffect(running) {
1111− if (running && listItems.isNotEmpty()) {
1112− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1113− if (lastVisible >= listItems.lastIndex) {
1114− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1115− }
1116− }
1117− }
1118−
1119− // Scroll the focused search match into view whenever the user steps through results with
1120− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1121− // includes date separators) and animates there.
1122− //
1123− // Keyed ONLY on searchPos and searchQuery (not listItems): a bare listItems key re-keys
1124− // on every streamed token (the list is rebuilt per snapshot), which re-fires this effect
1125− // ~20×/sec during an active stream — re-scrolling to the focused match on every token
1126− // and making it impossible to browse other matches with the up/down arrows while content
1127− // is streaming. snapshotFlow (reading currentListItems, a rememberUpdatedState) waits for
1128− // the target to appear without re-keying the effect on every list change, mirroring the
1129− // focusedMessageId pattern below.
1130− LaunchedEffect(searchPos, searchQuery) {
1131− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1132− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1133− val targetId = target.info.id
1134− val index = snapshotFlow {
1135− currentListItems.indexOfFirst {
1136− it is MessageListItem.Message && it.message.info.id == targetId
1137− }
1138− }.first { it >= 0 }
1139− runCatchingCancellable { listState.animateScrollToItem(index) }
1140− }
1141−
1142− // Global-search deep link: scroll to and briefly highlight the matched message. The
1143− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1144− // clears itself after a short delay so the user can re-read the surrounding context
1145− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1146− //
1147− // Keyed ONLY on focusedMessageId (not listItems): a bare listItems key re-keys on every
1148− // streamed token (the list is rebuilt per snapshot), which cancels the 2.5s delay before
1149− // it can clear the highlight — re-scrolling to the focus on every token and making an
1150− // actively-streaming chat unreadable. snapshotFlow waits for the message to appear in the
1151− // list (it may not be present on the first composition while messages load) without
1152− // re-keying the effect on every list change.
1153− // rememberSaveable (not plain remember) so the cleared null survives rotation:
1154− // plain remember keyed on focusMessageId re-seeds the non-null nav arg on every
1155− // recreation, re-firing this effect and yanking scroll back to the focus after the
1156− // user already dismissed the highlight. String? is Bundle-savable.
1157− var focusedMessageId by rememberSaveable(focusMessageId) { mutableStateOf(focusMessageId) }
1158− val currentListItemsForFocus by rememberUpdatedState(listItems)
1159− LaunchedEffect(focusedMessageId) {
1160− val focus = focusedMessageId ?: return@LaunchedEffect
1161− // Wait for the focused message to appear in the list, then resolve its index. A
1162− // first-composition empty list (messages still loading) will populate as the seed
1163− // arrives; snapshotFlow re-evaluates on each list change until the match is found.
1164− val index = snapshotFlow {
1165− currentListItemsForFocus.indexOfFirst {
1166− it is MessageListItem.Message && it.message.info.id == focus
1167− }
1168− }.first { it >= 0 }
1169− runCatchingCancellable { listState.animateScrollToItem(index) }
1170− kotlinx.coroutines.delay(2500)
1171− focusedMessageId = null
1172− }
1173−
1174− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1175− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1176− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1177− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1178− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1179− val density = androidx.compose.ui.platform.LocalDensity.current
1180− var wasImeOpen by remember { mutableStateOf(false) }
1181− val imeBottomPx = WindowInsets.ime.getBottom(density)
1182− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1183− if (listItems.isEmpty()) return@LaunchedEffect
1184− val imeOpen = imeBottomPx > 0
1185− // Scroll to bottom only on the open transition (not close) and only when the user
1186− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1187− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1188− if (shouldScroll) {
1189− runCatchingCancellable {
1190− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1191− }
1192− }
1193− wasImeOpen = imeOpen
1194− }
1195−
1196− LaunchedEffect(Unit) {
1197− var prevSize = 0
1198− var prevLen = 0
1199− snapshotFlow {
1200− // Track list size + the streaming length of the last part so we auto-scroll
1201− // as content arrives, plus the pinned flag. A small data class with primitive
1202− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1203− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1204− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1205− // and tool output — not just TextPart — keeps a pinned view following a long
1206− // reasoning/tool block while it streams (previously it stalled at 0).
1207− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1208− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1209− }.collect { signal ->
1210− if (signal.pinned) {
1211− // Back at the bottom: clear the new-content badge.
1212− newContentCount = 0
1213− if (signal.size > 0) {
1214− // Scroll to the effective last index, including the trailing
1215− // "__typing" row when a run is active so the working indicator
1216− // is brought into view (not just the last message).
1217− val items = currentListItems
1218− val target = if (running) items.size else items.lastIndex
1219− listState.scrollToItem(target)
1220− }
1221− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1222− // Content arrived while scrolled up — increment the jump-to-latest badge.
1223− // Only count whole new items (not per-token growth) so the number reflects
1224− // new messages, not a token count.
1225− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1226− else if (newContentCount == 0) newContentCount = 1
1227− }
1228− prevSize = signal.size
1229− prevLen = signal.lastTextLength
1230− }
1231− }
1232−
1233− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1234− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1235− // content padding accounts for the bottomBar's raised height, so the message
1236− // list is already above the keyboard. Adding imePadding here would double-apply
1237− // the IME inset and push messages too far up.
1238− //
1239− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1240− // message list on wide screens instead of floating at the screen edges — on a
1241− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1242− // The horizontal margin below is applied to the FAB/search containers so they
1243− // track the list's left/right edges.
1244− androidx.compose.foundation.layout.BoxWithConstraints(
1245− modifier = Modifier.fillMaxSize().padding(padding),
1246− ) {
1247− val screenMaxWidth = maxWidth
1248− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1249− // Horizontal margin between the capped list's edge and the screen edge (0 on
1250− // screens narrower than the cap). Applied as start/end padding so the FABs and
1251− // search bar sit at the list's edges, not the screen's.
1252− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1253− if (activeConnection == null) {
1254− Column(
1255− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1256− horizontalAlignment = Alignment.CenterHorizontally,
1257− ) {
1258− Text(
1259− stringResource(R.string.not_connected),
1260− color = MaterialTheme.colorScheme.error,
1261− )
1262− Spacer(Modifier.size(12.dp))
1263− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1264− if (reconnecting) {
1265− CircularProgressIndicator(
1266− Modifier.size(20.dp),
1267− color = MaterialTheme.colorScheme.onPrimary,
1268− strokeWidth = 2.dp,
1269− )
1270− } else {
1271− Text(stringResource(R.string.reconnect))
1272− }
1273− }
1274− }
1275− } else {
1276− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1277− // Measure the banner's actual height instead of hardcoding 44dp. At large
1278− // accessibility font scales the banner's labelMedium text + spinner + Retry
1279− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1280− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1281− // fires while the banner is composed (visible), so gate the inset on
1282− // bannerVisible and fall back to 44dp until the first measurement arrives.
1283− var bannerHeightPx by remember { mutableIntStateOf(0) }
1284− // Track the search bar height so the list's top padding can grow when search
1285− // is active — otherwise a scrolled-to match lands at index 0, hidden behind
1286− // the floating search bar (the "scroll-under-the-search-bar" bug).
1287− var searchbarHeightPx by remember { mutableIntStateOf(0) }
1288− val density = LocalDensity.current
1289− val topPad = if (bannerVisible) {
1290− if (bannerHeightPx > 0) {
1291− with(density) { bannerHeightPx.toDp() } + 4.dp
1292− } else {
1293− 44.dp
1294− }
1295− } else {
1296− 16.dp
1297− } + if (searchActive && searchbarHeightPx > 0) {
1298− with(density) { searchbarHeightPx.toDp() } + 4.dp
1299− } else {
1300− 0.dp
1301− }
1302− ConnectionBanner(
1303− state = connectionState,
1304− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
1305− isOnline = isOnline,
1306− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1307− // re-seeds from REST). refreshMessages is the right recovery path
1308− // when the connection is present but the stream died; reconnect()
1309− // is the path when the whole connection is gone (handled by the
1310− // separate "Not connected" state below).
1311− onRetry = { vm.refreshMessages() },
1312− // On an auth failure (401/403), retrying with the same bad credentials
1313− // is futile — offer a one-tap path to edit the active profile's
1314− // credentials instead of making the user hunt for the server list.
1315− onEditCredentials = {
1316− val profileId = activeConnection?.profile?.id
1317− if (profileId != null) onEditProfile?.invoke(profileId)
1318− },
1319− reconnectAttempts = reconnectAttempts,
1320− )
1321− // Persistent inline error banner for a mid-conversation load failure.
1322− // Unlike the one-shot snackbar (which fires once per streak then goes
1323− // silent), this stays visible until the stream recovers, so a persistent
1324− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1325− // Anchored at the top, below the connection banner, so it doesn't overlap
1326− // the message list.
1327− if (loadErrorInline && hasMessages) {
1328− Surface(
1329− color = MaterialTheme.colorScheme.errorContainer,
1330− shape = MaterialTheme.shapes.small,
1331− modifier = Modifier
1332− .align(Alignment.TopCenter)
1333− .padding(top = if (bannerVisible) topPad else 8.dp)
1334− .padding(horizontal = 16.dp)
1335− .semantics { liveRegion = LiveRegionMode.Polite },
1336− ) {
1337− Row(
1338− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1339− verticalAlignment = Alignment.CenterVertically,
1340− horizontalArrangement = Arrangement.spacedBy(8.dp),
1341− ) {
1342− Icon(
1343− Icons.Filled.ErrorOutline,
1344− contentDescription = null,
1345− modifier = Modifier.size(16.dp),
1346− tint = MaterialTheme.colorScheme.onErrorContainer,
1347− )
1348− Text(
1349− stringResource(R.string.load_error_persistent),
1350− style = MaterialTheme.typography.labelMedium,
1351− color = MaterialTheme.colorScheme.onErrorContainer,
1352− modifier = Modifier.weight(1f),
1353− )
1354− TextButton(
1355− onClick = { vm.refreshMessages() },
1356− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1357− ) {
1358− Text(stringResource(R.string.retry))
1359− }
1360− }
1361− }
1362− }
1363− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1364− // recovery is a swipe away everywhere — not just when the message list is
1365− // populated. Previously PTR was only around the populated list, leaving the
1366− // error/loading states reachable only via a button tap.
1367− PullToRefreshBox(
1368− isRefreshing = refreshing,
1369− // Suppress the refresh action while a run is active: a mid-stream
1370− // refresh forces an SSE reconnect that can interrupt the actively
1371− // streaming reply (matching the top-bar refresh button, which is
1372− // also disabled while running). The pull gesture still responds, but
1373− // the release no-ops instead of triggering a disruptive re-seed.
1374− onRefresh = { if (!running) vm.refreshMessages() },
1375− // Cap width and center on large screens for readability — full-width
1376− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1377− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1378− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1379− ) {
1380− // Reserve top space when the banner is visible so it doesn't overlap the
1381− // first message / state content. (topPad computed above.)
1382− if (loading && messages.isEmpty()) {
1383− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1384− // than a bare centered spinner and the first real messages pop into an
1385− // already-shaped list instead of a blank-then-pop.
1386− ChatSkeleton(topPad = topPad)
1387− } else if (loadError && messages.isEmpty()) {
1388− // A failed load with nothing to show. Distinct from the empty
1389− // conversation state below — the conversation isn't empty, it
1390− // failed to load, and offering "Start a conversation" here is
1391− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1392− Column(
1393− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1394− horizontalAlignment = Alignment.CenterHorizontally,
1395− ) {
1396− Text(
1397− stringResource(R.string.load_messages_failed),
1398− color = MaterialTheme.colorScheme.error,
1399− )
1400− Spacer(Modifier.size(12.dp))
1401− Button(onClick = { vm.refreshMessages() }) {
1402− Text(stringResource(R.string.retry))
1403− }
1404− // When the VM's retryWhen loop is actively retrying (loading is true
1405− // on top of the error state), surface a small "retrying…" indicator so
1406− // the user knows the system is working — without it, the static error
1407− // + Retry button reads as "broken, tap to fix", and the user may not
1408− // realize an automatic retry is already in progress.
1409− if (loading) {
1410− Spacer(Modifier.size(12.dp))
1411− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1412− Row(verticalAlignment = Alignment.CenterVertically) {
1413− CircularProgressIndicator(
1414− Modifier.size(14.dp),
1415− strokeWidth = 2.dp,
1416− )
1417− Text(
1418− retryingLabel,
1419− style = MaterialTheme.typography.labelSmall,
1420− color = MaterialTheme.colorScheme.onSurfaceVariant,
1421− modifier = Modifier.padding(start = 6.dp),
1422− )
1423− }
1424− }
1425− }
1426− } else if (messages.isEmpty() && running) {
1427− // A run just started but no parts have arrived yet — the empty list with
1428− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1429− // from the initial-load branch so the perceived start latency is lower and
1430− // the first real assistant part pops into an already-shaped list.
1431− ChatSkeleton(topPad = topPad)
1432− } else if (messages.isEmpty()) {
1433− EmptyConversation(
1434− onSuggestion = {
1435− vm.updateDraft(it)
1436− // Focus the input so the user can edit the suggestion before
1437− // sending, instead of having to manually tap the field.
1438− runCatching { inputFocusRequester.requestFocus() }
1439− },
1440− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1441− )
1442− } else {
1443− val lastMessageId = messages.lastOrNull()?.info?.id
1444− // Text-to-speech for reading assistant replies aloud; shuts down when the
1445− // message list leaves composition.
1446− val tts = rememberTtsController()
1447− val speakingMessageId by tts.speakingId
1448− val ttsState by tts.state
1449− // Provide the in-conversation search query to the markdown renderer so matching
1450− // text spans are highlighted in-place (in addition to the focused-row highlight
1451− // above). Scoped to the list so cleared search stops highlighting immediately.
1452− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1453− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1454− LazyColumn(
1455− state = listState,
1456− modifier = Modifier.fillMaxSize(),
1457− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1458− // never floats over the last message. Top padding grows when the
1459− // connection banner is visible so it doesn't overlap the first message.
1460− contentPadding = PaddingValues(
1461− start = 16.dp,
1462− top = topPad,
1463− end = 16.dp,
1464− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1465− ),
1466− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1467− // more conversation on screen without scrolling as much.
1468− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1469− ) {
1470− items(
1471− items = listItems,
1472− key = { it.key },
1473− contentType = { it.contentType },
1474− ) { item ->
1475− // When in-conversation search is stepping through matches, highlight the
1476− // focused one's row so the user can spot it at a glance among the filtered
1477− // results (full in-text term highlighting would require threading the query
1478− // through the markdown renderer; the row highlight + scroll-to-match covers
1479− // the navigation use case desktop chat apps solve with next/prev).
1480− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1481− searchMessages.getOrNull(searchPos)?.info?.id
1482− } else null
1483− val isFocusedMatch = focusedMatchId != null &&
1484− item is MessageListItem.Message &&
1485− item.message.info.id == focusedMatchId
1486− // Default placement animation so inserted/moved rows glide in. Skipped
1487− // entirely under reduced motion so a streaming message growing in place
1488− // doesn't animate on every token (and respects the a11y preference).
1489− Box(
1490− Modifier
1491− .then(reducedMotionAnimateItem())
1492− .then(
1493− if (isFocusedMatch) {
1494− Modifier.background(
1495− MaterialTheme.colorScheme.secondaryContainer,
1496− MaterialTheme.shapes.medium,
1497− )
1498− } else {
1499− Modifier
1500− },
1501− ),
1502− ) {
1503− when (item) {
1504− is MessageListItem.Separator -> DateSeparator(item.label)
1505− is MessageListItem.Message -> {
1506− val message = item.message
1507− val messageId = message.info.id
1508− // Only the last (streaming) message needs isRunning — it drives the
1509− // reasoning-block spinner. Passing the live flag to every bubble
1510− // makes all visible messages recompose whenever a run starts or stops.
1511− val modelLabel = remember(message.info, models) {
1512− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1513− ?.let { resolveModelLabel(it, models) }
1514− }
1515− // Key agentLabel/quoteText on the message id (not message.parts) so
1516− // the streaming message — whose `parts` list is replaced on every
1517− // token — doesn't re-run filterIsInstance per token for these two
1518− // derived labels. For a non-streaming message, `message.parts` is
1519− // reference-stable anyway, so this is equivalent. For the streaming
1520− // message the label updates as parts change via the message.info/
1521− // parts reference change below — keyed on messageId + a parts-hash
1522− // is overkill; agentLabel/quoteText only need to reflect the latest
1523− // parts, and `remember(messageId, message.parts)` would re-key per
1524− // token. Instead key on `messageId` alone and accept that the label
1525− // lags by one recomposition for the streaming bubble (it stabilizes
1526− // once the stream finishes). This is invisible in practice: agent
1527− // label is set on the first part, quote text grows with text parts
1528− // but is only consumed on a swipe (user-initiated, post-stream).
1529− val agentLabel = remember(messageId) {
1530− message.parts
1531− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1532− .firstOrNull { it.name.isNotBlank() }?.name
1533− }
1534− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1535− // image/code-only messages, which then opt out of the swipe gesture.
1536− val quoteText = remember(messageId) {
1537− message.parts
1538− .filterIsInstance<TextPart>()
1539− .joinToString("\n\n") { it.text }
1540− .trim()
1541− .takeIf { it.isNotEmpty() }
1542− }
1543− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1544− // snapping back (the message isn't dismissed — the quote fills the composer).
1545− // Enabled for non-text messages too (image/tool-only), but the confirm
1546− // callback gives a haptic without triggering reply — so the user gets a
1547− // perceptible "can't quote this" signal instead of a silently dead gesture.
1548− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1549− val undoLabel = stringResource(R.string.undo)
1550− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1551− // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1552− // so it's stable across recompositions (a fresh lambda would force the
1553− // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1554− // derived value that's stable for non-streaming messages.
1555− val swipeState = rememberSwipeToDismissBoxState(
1556− confirmValueChange = remember(messageId, quoteText) {
1557− { value ->
1558− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1559− SwipeToDismissBoxValue.EndToStart
1560− } else {
1561− SwipeToDismissBoxValue.StartToEnd
1562− }
1563− if (value == replyValue) {
1564− if (quoteText != null) {
1565− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1566− vm.quoteReply(quoteText)
1567− runCatching { inputFocusRequester.requestFocus() }
1568− scope.launch {
1569− val res = snackbar.showSnackbar(
1570− message = quoteReplyLabel,
1571− actionLabel = undoLabel,
1572− )
1573− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1574− vm.cancelQuoteReply()
1575− }
1576− }
1577− } else {
1578− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1579− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1580− }
1581− }
1582− false
1583− }
1584− },
1585− )
1586− // In RTL locales, mirror the swipe direction so the reply
1587− // gesture reads naturally (swipe from the trailing edge
1588− // toward the leading edge), matching how LTR users swipe
1589− // left-to-right. Without this, RTL users had no reply swipe.
1590− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1591− // Memoize every MessageBubble lambda on the message id so a recomposition
1592− // triggered by a sibling (e.g. the streaming message's parts changing,
1593− // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1594− // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1595− // many `(() -> Unit)?` params, which Compose treats as unstable), so
1596− // without memoization every visible bubble recomposes on every token,
1597− // defeating the @Immutable MessageWithParts reference-stability the
1598− // reducer's Holder cache provides. This mirrors the SessionListScreen
1599− // per-card lambda memoization pattern.
1600− val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1601− val onEdit = remember(messageId) {
1602− { text: String ->
1603− // editMessage reverts to before this message (hiding it and
1604− // everything after); the revert banner surfaces the rewind
1605− // with an Undo. Focus + scroll the composer into view like the
1606− // Quote action so the prefilled draft isn't off-screen.
1607− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1608− vm.editMessage(messageId, text)
1609− runCatching { inputFocusRequester.requestFocus() }
1610− contentScope.launch {
1611− runCatchingCancellable {
1612− listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1613− }
1614− }
1615− Unit
1616− }
1617− }
1618− val onSpeak = remember(messageId) {
1619− { text: String ->
1620− if (!tts.toggle(messageId, text)) {
1621− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1622− }
1623− Unit
1624− }
1625− }
1626− val onPause = remember { { tts.pause() } }
1627− val onResume = remember { { tts.resume() } }
1628− val onStop = remember { { tts.stop() } }
1629− val onQuote = remember(messageId) {
1630− { text: String ->
1631− vm.quoteReply(text)
1632− runCatching { inputFocusRequester.requestFocus() }
1633− Unit
1634− }
1635− }
1636− val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1637− // Regenerate is only meaningful for a finished assistant reply
1638− // (not the actively-streaming one), so gate it on !running.
1639− val onRegenerate = if (!running) {
1640− remember(messageId) { { vm.regenerate(messageId) } }
1641− } else {
1642− null
1643− }
1644− // Continue: resume a partial reply. Shown only for
1645− // incomplete assistant messages (a partial reply that
1646− // was aborted) and not while a run is active.
1647− val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1648− val onContinue = if (canContinue) {
1649− remember(messageId) { { vm.continueRun(messageId) } }
1650− } else {
1651− null
1652− }
1653− val messageFailed = optimisticStatuses[messageId] == true
1654− val onRetry = if (messageFailed) {
1655− remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1656− } else {
1657− null
1658− }
1659− val onDismiss = if (messageFailed) {
1660− remember(messageId) { { vm.dismissOptimistic(messageId) } }
1661− } else {
1662− null
1663− }
1664− val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1665− {
1666− // Per-message share: build a single-message Markdown
1667− // transcript off-thread and fire ACTION_SEND, mirroring the
1668− // whole-conversation share but scoped to just this message.
1669− scope.launch {
1670− val md = withContext(Dispatchers.Default) {
1671− buildMessageMarkdown(message)
1672− } ?: return@launch
1673− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1674− type = "text/markdown"
1675− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1676− putExtra(android.content.Intent.EXTRA_TEXT, md)
1677− }
1678− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1679− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1680− }
1681− Unit
1682− }
1683− }
1684− SwipeToDismissBox(
1685− state = swipeState,
1686− enableDismissFromEndToStart = !replyFromStartToEnd,
1687− enableDismissFromStartToEnd = replyFromStartToEnd,
1688− backgroundContent = {
1689− Box(
1690− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1691− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1692− ) {
1693− Icon(
1694− Icons.AutoMirrored.Filled.Reply,
1695− contentDescription = null,
1696− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1697− )
1698− }
1699− },
1700− ) {
1701− MessageBubble(
1702− message,
1703− isRunning = running && messageId == lastMessageId,
1704− imageContext = imageContext,
1705− modelLabel = modelLabel,
1706− agentLabel = agentLabel,
1707− onOpenFile = onOpenFile,
1708− onRevert = onRevert,
1709− onEdit = onEdit,
1710− onSpeak = onSpeak,
1711− isSpeaking = messageId == speakingMessageId,
1712− ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1713− onPause = onPause,
1714− onResume = onResume,
1715− onStop = onStop,
1716− onQuote = onQuote,
1717− onBranch = onBranch,
1718− onRegenerate = onRegenerate,
1719− onContinue = onContinue,
1720− sendStatus = optimisticStatuses[messageId]?.let { failed ->
1721− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1722− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1723− },
1724− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1725− onRetry = onRetry,
1726− onDismiss = onDismiss,
1727− onShare = onShare,
1728− isFirstOfSpeaker = item.isFirstOfSpeaker,
1729− highlighted = focusedMessageId != null && messageId == focusedMessageId,
1730− )
1731− }
1732− }
1733− }
1734− }
1735− }
1736− if (running) {
1737− item(key = "__typing") {
1738− val workingText = stringResource(R.string.working)
1739− // When the SSE stream dropped mid-run, show a "reconnecting" label
1740− // instead of the plain "working" text so the user understands the
1741− // run is still active but the stream is reconnecting (not finished).
1742− val reconnectingText = stringResource(R.string.reconnecting)
1743− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1744− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1745− // survives LazyColumn recycling — a local remember reset to 0:00 when
1746− // the row was disposed and scrolled back into view. The VM stamps the
1747− // start on the real false→true transition (send/run/init), not on
1748− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1749− // once per second; the value is decorative (the a11y label is the row's).
1750− // The clock freezes when an abort is confirmed (aborting = true) so the
1751− // user can see how long the run lasted before they stopped it, rather
1752− // than the clock continuing to tick until SessionIdle clears _running.
1753− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1754− // Seed the initial value synchronously from startMs so the timer
1755− // doesn't flash 0:00 when the __typing row is recycled by LazyColumn
1756− // (scrolled out then back in): produceState's coroutine is cancelled on
1757− // disposal and re-launched on re-entry, and a 0L initialValue would
1758− // briefly show "0:00" before the producer's first iteration runs.
1759− val elapsedMs by produceState(
1760− initialValue = if (startMs > 0L) (System.currentTimeMillis() - startMs).coerceAtLeast(0L) else 0L,
1761− startMs, aborting,
1762− ) {
1763− if (startMs == 0L) return@produceState
1764− if (aborting) {
1765− // Freeze at the last-computed value: one final snapshot then stop.
1766− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1767− return@produceState
1768− }
1769− while (true) {
1770− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1771− delay(1000)
1772− }
1773− }
1774− val elapsedText = remember(elapsedMs) {
1775− val total = elapsedMs / 1000
1776− // Locale.US for stable digit formatting: on locales with
1777− // non-ASCII digits (ar-/fa-) the default locale would render
1778− // localized digits inside the Monospace block, breaking the
1779− // fixed-width alignment the monospace family was chosen for.
1780− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1781− }
1782− Row(
1783− verticalAlignment = Alignment.CenterVertically,
1784− // Animate this slot in/out so the working row doesn't pop in and
1785− // jolt the message list when a run starts/stops — matching the
1786− // AnimatedVisibility used by every other transient banner/FAB here.
1787− modifier = Modifier
1788− .then(reducedMotionAnimateItem())
1789− .padding(vertical = 4.dp),
1790− ) {
1791− // Merge the indicator + label + clock into one TalkBack node so
1792− // it's announced once (the working label, then the elapsed time)
1793− // instead of "working… / working… / 0:14" with the label read
1794− // twice. The Stop IconButton below stays separately focusable.
1795− Row(
1796− verticalAlignment = Alignment.CenterVertically,
1797− modifier = Modifier.semantics(mergeDescendants = true) {
1798− contentDescription = "$interruptedLabel $elapsedText"
1799− },
1800− ) {
1801− // Dim the spinner when interrupted so the row reads as
1802− // "paused/reconnecting" rather than actively progressing.
1803− CircularProgressIndicator(
1804− Modifier.size(16.dp),
1805− strokeWidth = 2.dp,
1806− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1807− else MaterialTheme.colorScheme.primary,
1808− )
1809− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1810− Spacer(Modifier.size(8.dp))
1811− Icon(
1812− Icons.Filled.Schedule,
1813− contentDescription = null,
1814− modifier = Modifier.size(14.dp),
1815− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1816− )
1817− Text(
1818− elapsedText,
1819− style = MaterialTheme.typography.labelMedium,
1820− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1821− color = MaterialTheme.colorScheme.onSurfaceVariant,
1822− modifier = Modifier.padding(start = 4.dp),
1823− )
1824− }
1825− // A trailing Stop on the working row so the run can be aborted
1826− // without scrolling back to the composer (which may be off-screen
1827− // while the user reads the streaming output up-thread).
1828− Spacer(Modifier.weight(1f))
1829− val stopLabel = stringResource(R.string.stop)
1830− IconButton(
1831− onClick = { vm.abort() },
1832− modifier = Modifier.semantics { contentDescription = stopLabel },
1833− ) {
1834− Icon(Icons.Filled.Stop, contentDescription = null)
1835− }
1836− }
1837− }
1838− }
1839− }
1840− }
1841− }
1842− }
1843− // Jump-to-latest affordance when the user has scrolled away during a stream.
1844− val fabMotion = rememberVisibilityTransitions()
1845− AnimatedVisibility(
1846− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1847− enter = fabMotion.enter,
1848− exit = fabMotion.exit,
1849− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1850− // edge instead of floating at the screen edge (visually detached on tablets).
1851− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1852− ) {
1853− // Badge the FAB when new content arrived while the user was scrolled up, so
1854− // they know there's something new to jump to (cleared once back at bottom).
1855− BadgedBox(
1856− badge = {
1857− if (newContentCount > 0) {
1858− // Merge the count into the badge announcement so TalkBack reads
1859− // "5 new messages" instead of the bare label and a separate number.
1860− val newContentLabel = pluralStringResource(
1861− R.plurals.plurals_new_messages,
1862− newContentCount,
1863− newContentCount,
1864− )
1865− Badge(
1866− modifier = Modifier.semantics {
1867− contentDescription = newContentLabel
1868− // Announce new-content counts as they change so a
1869− // TalkBack user hears "5 new messages" without having
1870− // to focus the FAB. Polite so it doesn't interrupt an
1871− // in-progress utterance (e.g. streaming token reads).
1872− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1873− },
1874− ) {
1875− Text(
1876− if (newContentCount > 99) "99+" else newContentCount.toString(),
1877− modifier = Modifier.semantics { invisibleToUser() },
1878− )
1879− }
1880− }
1881− },
1882− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1883− ) {
1884− ExtendedFloatingActionButton(
1885− onClick = {
1886− newContentCount = 0
1887− if (listItems.isNotEmpty()) {
1888− // Scroll to the effective last index, including the
1889− // trailing "__typing" row when a run is active.
1890− val target = if (running) listItems.size else listItems.lastIndex
1891− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1892− }
1893− },
1894− // contentDescription null: the visible "Latest" text already labels
1895− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1896− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1897− text = { Text(stringResource(R.string.latest)) },
1898− )
1899− }
1900− }
1901− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1902− // user has scrolled down past the first few messages. Symmetric to the
1903− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1904− val scrolledDown by remember {
1905− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1906− }
1907− AnimatedVisibility(
1908− visible = scrolledDown && listItems.size > 4,
1909− enter = fabMotion.enter,
1910− exit = fabMotion.exit,
1911− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1912− ) {
1913− SmallFloatingActionButton(
1914− onClick = {
1915− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1916− },
1917− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1918− ) {
1919− Icon(
1920− Icons.Filled.KeyboardArrowUp,
1921− contentDescription = stringResource(R.string.scroll_to_top),
1922− )
1923− }
1924− }
1925− // In-conversation search bar. Overlays the list so typing filters messages in
1926− // place; the match count + a no-matches note give immediate feedback.
1927− val searchMotion = rememberVisibilityTransitions()
1928− AnimatedVisibility(
1929− visible = searchActive,
1930− enter = searchMotion.enter,
1931− exit = searchMotion.exit,
1932− // Inset by sideMargin on wide screens so the search bar spans the capped
1933− // list's width, not the full screen width.
1934− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1935− ) {
1936− Surface(
1937− tonalElevation = 3.dp,
1938− modifier = Modifier
1939− .padding(horizontal = 12.dp, vertical = 4.dp)
1940− .fillMaxWidth()
1941− .onSizeChanged { searchbarHeightPx = it.height },
1942− ) {
1943− // Focus the search field when the bar appears (from the overflow menu's
1944− // "Find in conversation" or Ctrl+F), so the user can start typing
1945− // immediately. Runs after the search field enters the composition.
1946− LaunchedEffect(searchActive) {
1947− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1948− }
1949− Row(
1950− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1951− verticalAlignment = Alignment.CenterVertically,
1952− ) {
1953− OutlinedTextField(
1954− value = chatSearch,
1955− onValueChange = { chatSearch = it },
1956− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1957− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1958− singleLine = true,
1959− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1960− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1961− )
1962− // Match counter: "N of M" where N is the focused match (1-based) and
1963− // M is the total matching messages. Only shown when there's a query.
1964− val matchCount = searchMessages.size
1965− Text(
1966− if (searchQuery.isNotEmpty() && matchCount > 0) {
1967− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1968− } else if (searchQuery.isNotEmpty()) {
1969− stringResource(R.string.search_no_matches)
1970− } else "",
1971− style = MaterialTheme.typography.labelSmall,
1972− color = MaterialTheme.colorScheme.onSurfaceVariant,
1973− modifier = Modifier
1974− .padding(horizontal = 4.dp)
1975− // Live region so a TalkBack user hears "3 of 12" / "No
1976− // matches" announce as they step through results, not just
1977− // the sighted user seeing the counter update.
1978− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
1979− )
1980− // Step through matches (Previous / Next), disabled when there are
1981− // fewer than two to navigate. Wrap around at the ends so repeated
1982− // taps cycle through every hit.
1983− val prevLabel = stringResource(R.string.find_previous)
1984− val nextLabel = stringResource(R.string.find_next)
1985− IconButton(
1986− onClick = {
1987− if (matchCount > 0) {
1988− searchPos = (searchPos - 1 + matchCount) % matchCount
1989− }
1990− },
1991− enabled = matchCount > 1,
1992− ) {
1993− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
1994− }
1995− IconButton(
1996− onClick = {
1997− if (matchCount > 0) {
1998− searchPos = (searchPos + 1) % matchCount
1999− }
2000− },
2001− enabled = matchCount > 1,
2002− ) {
2003− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
2004− }
2005− IconButton(onClick = {
2006− searchActive = false
2007− chatSearch = ""
2008− }) {
2009− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
2010− }
2011− }
2012− }
2013− }
2014− // When a search yields no matches (but the conversation isn't empty), say so
2015− // instead of showing a blank list.
2016− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
2017− Text(
2018− stringResource(R.string.search_no_matches),
2019− style = MaterialTheme.typography.bodyMedium,
2020− color = MaterialTheme.colorScheme.onSurfaceVariant,
2021− modifier = Modifier.align(Alignment.Center),
2022− )
2023− }
2024− }
2025− }
2026− }
2027− }
2028−
2029− if (showExitConfirm) {
2030− AlertDialog(
2031− onDismissRequest = { showExitConfirm = false },
2032− title = { Text(stringResource(R.string.stop_and_exit_title)) },
2033− text = { Text(stringResource(R.string.stop_and_exit_text)) },
2034− confirmButton = {
2035− TextButton(onClick = {
2036− showExitConfirm = false
2037− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2038− vm.abort()
2039− onBack()
2040− }) { Text(stringResource(R.string.stop_and_exit)) }
2041− },
2042− dismissButton = {
2043− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
2044− },
2045− )
2046− }
2047−
2048− if (showSummarizeConfirm) {
2049− AlertDialog(
2050− onDismissRequest = { showSummarizeConfirm = false },
2051− title = { Text(stringResource(R.string.summarize_confirm_title)) },
2052− text = { Text(stringResource(R.string.summarize_confirm_text)) },
2053− confirmButton = {
2054− TextButton(onClick = {
2055− showSummarizeConfirm = false
2056− vm.summarize()
2057− }) { Text(stringResource(R.string.action_continue)) }
2058− },
2059− dismissButton = {
2060− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
2061− },
2062− )
2063− }
2064−
2065− if (showInitConfirm) {
2066− AlertDialog(
2067− onDismissRequest = { showInitConfirm = false },
2068− title = { Text(stringResource(R.string.init_confirm_title)) },
2069− text = { Text(stringResource(R.string.init_confirm_text)) },
2070− confirmButton = {
2071− TextButton(onClick = {
2072− showInitConfirm = false
2073− vm.initProject()
2074− }) { Text(stringResource(R.string.action_continue)) }
2075− },
2076− dismissButton = {
2077− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2078− },
2079− )
2080− }
2081−
2082− if (showRenameDialog) {
2083− RenameSessionChatDialog(
2084− initialTitle = sessionTitle ?: "",
2085− onDismiss = { showRenameDialog = false },
2086− onConfirm = { newName ->
2087− showRenameDialog = false
2088− vm.renameSession(newName)
2089− },
2090− )
2091− }
2092−
2093− if (showDeleteDialog) {
2094− AlertDialog(
2095− onDismissRequest = { showDeleteDialog = false },
2096− title = { Text(stringResource(R.string.delete_session_chat_title)) },
2097− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2098− confirmButton = {
2099− TextButton(onClick = {
2100− showDeleteDialog = false
2101− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2102− vm.deleteSession()
2103− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2104− },
2105− dismissButton = {
2106− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2107− },
2108− )
2109− }
2110−
2111− if (showShellDialog) {
2112− ShellCommandDialog(
2113− onDismiss = { showShellDialog = false },
2114− onRun = { cmd ->
2115− showShellDialog = false
2116− vm.runShell(cmd)
2117− },
2118− )
2119− }
2120−
2121− if (showModelPicker) {
2122− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2123− // to, dropping any whose model is no longer offered by the server. Ordered by
2124− // recency (head of the store first).
2125− val recentOptions = remember(models, recentModelEntries) {
2126− val byKey = models.associateBy { it.providerID to it.modelID }
2127− recentModelEntries.mapNotNull { entry ->
2128− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2129− }
2130− }
2131− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2132− // below isn't @Composable, so stringResource can't be called inside it.
2133− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2134− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2135− ModelPickerSheet(
2136− options = models,
2137− selected = selectedModel,
2138− loading = modelsLoading,
2139− error = modelsError,
2140− onSelect = {
2141− vm.selectModel(it)
2142− container.recentModelsStore.add(it.providerID, it.modelID)
2143− },
2144− onRetry = { vm.reloadModels() },
2145− onDismiss = { showModelPicker = false },
2146− preferredModelId = preferredModelId,
2147− onSetPreferredModel = { id ->
2148− scope.launch {
2149− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2150− // Confirm the change with a snackbar so the user sees it took effect —
2151− // the toggle's label flip can be missed, especially when clearing.
2152− val msg = if (id.isEmpty()) {
2153− defaultModelClearedMsg
2154− } else {
2155− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2156− defaultModelSetFmt.format(label)
2157− }
2158− snackbar.showSnackbar(msg)
2159− }
2160− },
2161− recent = recentOptions,
2162− )
2163− }
2164−
2165− if (showAgentPicker) {
2166− AgentPickerSheet(
2167− agents = agents,
2168− selected = selectedAgent,
2169− loading = agentsLoading,
2170− error = agentsError,
2171− onSelect = { vm.selectAgent(it?.name) },
2172− onRetry = { vm.reloadAgents() },
2173− onDismiss = { showAgentPicker = false },
2174− )
2175− }
2176−
2177− if (showCommandPicker) {
2178− CommandPickerSheet(
2179− commands = commands,
2180− loading = commandsLoading,
2181− error = commandsError,
2182− onSelect = { vm.runCommand(it) },
2183− onRetry = { vm.reloadCommands() },
2184− onDismiss = { showCommandPicker = false },
2185− )
2186− }
2187−
2188− pendingPermission?.let { permission ->
2189− PermissionDialog(
2190− permission = permission,
2191− position = permissionProgress.position,
2192− total = permissionProgress.total,
2193− onRespond = { response -> vm.respondPermission(permission, response) },
2194− // On auto-reject timeout, post a notification so a returning user finds a
2195− // persistent record of why the run stopped (the dialog itself is gone).
2196− // Gated by the user's notification setting (notifPermission).
2197− onAutoReject = {
2198− val conn = activeConnection
2199− val ctx = appContext
2200− val title = sessionTitle ?: sessionId
2201− if (notifPermission) {
2202− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2203− ctx, sessionId, title, conn?.profile?.id,
2204− )
2205− }
2206− },
2207− )
2208− }
2209−
2210− if (showPalette) {
2211− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2212− }
2213−
2214− if (showShortcutsDialog) {
2215− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2216− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2217− // depends on the "Send on Enter" setting, noted inline.
2218− AlertDialog(
2219− onDismissRequest = { showShortcutsDialog = false },
2220− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2221− text = {
2222− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2223− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2224− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2225− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2226− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2227− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2228− }
2229− },
2230− confirmButton = {
2231− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2232− },
2233− )
2234− }
2235−}
2236−
2237−@Composable
2238−private fun ShortcutRow(keys: String, desc: String) {
2239− Row(verticalAlignment = Alignment.CenterVertically) {
2240− Text(
2241− keys,
2242− style = MaterialTheme.typography.labelLarge,
2243− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2244− modifier = Modifier.widthIn(min = 160.dp),
2245− )
2246− Text(
2247− desc,
2248− style = MaterialTheme.typography.bodyMedium,
2249− color = MaterialTheme.colorScheme.onSurfaceVariant,
2250− )
2251− }
2252−}
2253−
2254−/**
2255− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2256− * of matching commands above the composer. Tapping a command fires it immediately.
2257− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2258− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2259− */
2260−@Composable
2261−private fun SlashCommandAutocomplete(
2262− value: String,
2263− commands: List<Command>,
2264− running: Boolean,
2265− onRunCommand: (Command) -> Unit,
2266−) {
2267− if (running || commands.isEmpty()) return
2268− val slashQuery = remember(value) {
2269− if (value.startsWith("/")) value.removePrefix("/") else null
2270− } ?: return
2271− val matchingCommands = remember(slashQuery, commands) {
2272− commands.filter { cmd ->
2273− slashQuery.isEmpty() ||
2274− cmd.name.contains(slashQuery, ignoreCase = true) ||
2275− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2276− }.take(8)
2277− }
2278− if (matchingCommands.isNotEmpty()) {
2279− CommandAutocompleteDropdown(
2280− commands = matchingCommands,
2281− onPick = onRunCommand,
2282− )
2283− }
2284−}
2285−
2286−/**
2287− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2288− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2289− * user can discover and invoke commands by typing the conventional "/" prefix instead
2290− * of opening the overflow menu / command palette. Tapping a row fires the command.
2291− */
2292−@Composable
2293−private fun CommandAutocompleteDropdown(
2294− commands: List<Command>,
2295− onPick: (Command) -> Unit,
2296−) {
2297− val haptics = LocalHapticFeedback.current
2298− Surface(
2299− color = MaterialTheme.colorScheme.surface,
2300− tonalElevation = 3.dp,
2301− shape = MaterialTheme.shapes.medium,
2302− modifier = Modifier
2303− .fillMaxWidth()
2304− .padding(horizontal = 8.dp, vertical = 4.dp)
2305− .heightIn(max = 240.dp),
2306− ) {
2307− LazyColumn {
2308− items(
2309− count = commands.size,
2310− key = { commands[it].name },
2311− ) { i ->
2312− val cmd = commands[i]
2313− Row(
2314− modifier = Modifier
2315− .fillMaxWidth()
2316− .clickable(role = Role.Button) {
2317− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2318− onPick(cmd)
2319− }
2320− .padding(horizontal = 16.dp, vertical = 10.dp),
2321− verticalAlignment = Alignment.CenterVertically,
2322− horizontalArrangement = Arrangement.spacedBy(12.dp),
2323− ) {
2324− Text(
2325− "/${cmd.name}",
2326− style = MaterialTheme.typography.labelLarge,
2327− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2328− color = MaterialTheme.colorScheme.primary,
2329− )
2330− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2331− Text(
2332− desc,
2333− style = MaterialTheme.typography.bodySmall,
2334− color = MaterialTheme.colorScheme.onSurfaceVariant,
2335− maxLines = 1,
2336− overflow = TextOverflow.Ellipsis,
2337− )
2338− }
2339− }
2340− }
2341− }
2342− }
2343−}
2344−
2345−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2346−@Suppress("CyclomaticComplexMethod")
2347−@Composable
2348−private fun ChatInputBar(
2349− value: String,
2350− onValueChange: (String) -> Unit,
2351− running: Boolean,
2352− aborting: Boolean,
2353− enabled: Boolean,
2354− sendOnEnter: Boolean,
2355− onSend: () -> Unit,
2356− onAbort: () -> Unit,
2357− queuedFollowUp: String?,
2358− onQueueFollowUp: (String) -> Unit,
2359− onCancelQueue: () -> Unit,
2360− focusRequester: androidx.compose.ui.focus.FocusRequester,
2361− attachments: List<PendingAttachment>,
2362− staging: Boolean,
2363− stagingFileCount: Int,
2364− onRemoveAttachment: (String) -> Unit,
2365− onPickPhoto: () -> Unit,
2366− onPickFile: () -> Unit,
2367− onCamera: () -> Unit,
2368− onVoice: () -> Unit,
2369− onPasteImage: (List<Uri>) -> Unit,
2370− commands: List<Command> = emptyList(),
2371− onRunCommand: (Command) -> Unit = {},
2372−) {
2373− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2374− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2375− val context = LocalContext.current
2376− // Full-screen editor state: opened when the user wants more space for a long prompt.
2377− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2378− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2379− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2380− // A queued follow-up replaces the Stop button with a "queued" chip so the
2381− // user sees their message will be sent when the run finishes, and can cancel.
2382− if (queuedFollowUp != null) {
2383− val editLabel = stringResource(R.string.edit)
2384− Row(
2385− modifier = Modifier
2386− .fillMaxWidth()
2387− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2388− verticalAlignment = Alignment.CenterVertically,
2389− ) {
2390− // Tapping the chip reloads the queued text into the draft (and clears the
2391− // queue) so a typo spotted while queuing can be fixed without retyping.
2392− Column(
2393− modifier = Modifier
2394− .weight(1f)
2395− .clip(MaterialTheme.shapes.small)
2396− .clickable(role = Role.Button, onClickLabel = editLabel) {
2397− onValueChange(queuedFollowUp)
2398− onCancelQueue()
2399− }
2400− .padding(vertical = 4.dp),
2401− ) {
2402− Text(
2403− stringResource(R.string.queued),
2404− style = MaterialTheme.typography.labelSmall,
2405− color = MaterialTheme.colorScheme.onSurfaceVariant,
2406− )
2407− Text(
2408− queuedFollowUp,
2409− style = MaterialTheme.typography.bodySmall,
2410− color = MaterialTheme.colorScheme.onSurfaceVariant,
2411− maxLines = 1,
2412− overflow = TextOverflow.Ellipsis,
2413− )
2414− }
2415− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2416− Text(stringResource(R.string.cancel))
2417− }
2418− }
2419− }
2420− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2421− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2422− // Slash-command autocomplete: extracted to a helper to keep this function's
2423− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2424− // start with "/" or the command catalog is empty.
2425− SlashCommandAutocomplete(
2426− value = value,
2427− commands = commands,
2428− running = running,
2429− onRunCommand = onRunCommand,
2430− )
2431− Row(
2432− modifier = Modifier.fillMaxWidth().padding(8.dp),
2433− verticalAlignment = Alignment.Bottom,
2434− ) {
2435− // Attach menu: photo picker, camera, or any file.
2436− var showAttachMenu by remember { mutableStateOf(false) }
2437− Box {
2438− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2439− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2440− }
2441− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2442− DropdownMenuItem(
2443− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2444− text = { Text(stringResource(R.string.attach_photo)) },
2445− onClick = { showAttachMenu = false; onPickPhoto() },
2446− )
2447− DropdownMenuItem(
2448− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2449− text = { Text(stringResource(R.string.attach_camera)) },
2450− onClick = { showAttachMenu = false; onCamera() },
2451− )
2452− DropdownMenuItem(
2453− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2454− text = { Text(stringResource(R.string.attach_file)) },
2455− onClick = { showAttachMenu = false; onPickFile() },
2456− )
2457− }
2458− }
2459− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2460− // disabled) when the device has no speech-recognition activity, so a user
2461− // without a voice app doesn't get a button that only fails noisily on tap.
2462− val voiceAvailable = remember {
2463− val pm = context.packageManager
2464− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2465− pm.queryIntentActivities(intent, 0).isNotEmpty()
2466− }
2467− if (voiceAvailable) {
2468− IconButton(onClick = onVoice, enabled = enabled) {
2469− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2470− }
2471− }
2472− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2473− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2474− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2475− }
2476− OutlinedTextField(
2477− value = value,
2478− onValueChange = { v ->
2479− // Cap input length so a huge paste can't stall the UI. Shares are
2480− // capped separately in MainActivity; this guards typed/pasted drafts.
2481− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2482− },
2483− modifier = Modifier
2484− .weight(1f)
2485− .focusRequester(focusRequester)
2486− .testTag("chat_input")
2487− // Intercept image content pasted/dropped into the field (keyboard paste
2488− // of a copied screenshot, drag from Files, etc.) and route it through the
2489− // same staging path as the attach menu. Non-image content (text) falls
2490− // through unchanged so normal typing/paste works.
2491− .contentReceiver(
2492− remember {
2493− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2494− val clipData = transferable.clipEntry?.clipData
2495− if (clipData != null) {
2496− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2497− val item = clipData.getItemAt(i)
2498− item.uri?.takeIf { uri ->
2499− item.text == null && uri.toString().let { s ->
2500− s.startsWith("content:") || s.startsWith("file:")
2501− }
2502− }
2503− }
2504− if (imageUris.isNotEmpty()) {
2505− onPasteImage(imageUris)
2506− }
2507− }
2508− transferable
2509− }
2510− },
2511− )
2512− .onPreviewKeyEvent { event ->
2513− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2514− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2515− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2516− val send = enterShouldSend(
2517− enabled = enabled,
2518− hasContent = hasContent,
2519− sendOnEnter = sendOnEnter,
2520− shift = event.isShiftPressed,
2521− ctrl = event.isCtrlPressed,
2522− )
2523− if (send) {
2524− if (running) onQueueFollowUp(value) else onSend()
2525− true
2526− } else {
2527− false
2528− }
2529− },
2530− // While a run is active a typed message only queues (sends after the run), so
2531− // the placeholder says so instead of the plain "Message…".
2532− placeholder = {
2533− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2534− },
2535− enabled = enabled,
2536− maxLines = 6,
2537− // Show a "N / max" countdown once the draft crosses a high fraction of
2538− // the cap, so the user knows a paste is about to be truncated instead
2539− // of being silently cut off. Hidden for normal short prompts to avoid
2540− // clutter under a typical one-line message.
2541− supportingText = {
2542− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2543− if (value.length >= threshold) {
2544− Text(
2545− stringResource(
2546− R.string.draft_chars_remaining,
2547− NetworkConfig.maxDraftLengthChars - value.length,
2548− NetworkConfig.maxDraftLengthChars,
2549− ),
2550− style = MaterialTheme.typography.labelSmall,
2551− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2552− else MaterialTheme.colorScheme.onSurfaceVariant,
2553− )
2554− } else if (value.lines().size > 6) {
2555− // The inline field caps at 6 lines; once the draft crosses that,
2556− // hint that a bigger full-screen editor exists (the Expand icon
2557− // above is easy to miss among the icon row). A tappable label
2558− // would be ideal, but a plain hint is enough to draw attention.
2559− Text(
2560− stringResource(R.string.open_full_editor_hint),
2561− style = MaterialTheme.typography.labelSmall,
2562− color = MaterialTheme.colorScheme.onSurfaceVariant,
2563− )
2564− }
2565− },
2566− keyboardOptions = KeyboardOptions(
2567− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2568− // keyboard shows a send key — matching the setting's intent and
2569− // giving touch-only users a keyboard send affordance. When off,
2570− // ImeAction.Default keeps the enter/newline key for multi-line input.
2571− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2572− capitalization = KeyboardCapitalization.Sentences,
2573− ),
2574− keyboardActions = KeyboardActions(
2575− onSend = {
2576− // Mirror the hardware-Enter handler: during a run the soft-keyboard
2577− // send key must queue the follow-up, not silently drop it. vm.send()
2578− // returns false while a run is active (beginRun() rejects), so calling
2579− // onSend() directly here would lose the typed message with no feedback
2580− // for touch-only users (no hardware Enter path available).
2581− if (enabled && hasContent) {
2582− if (running) onQueueFollowUp(value) else onSend()
2583− }
2584− },
2585− ),
2586− )
2587− ComposerTrailingButton(
2588− running = running,
2589− aborting = aborting,
2590− canSend = enabled && hasContent,
2591− canQueue = enabled && value.isNotBlank(),
2592− onSend = onSend,
2593− onAbort = onAbort,
2594− onQueue = { onQueueFollowUp(value) },
2595− )
2596− }
2597− }
2598− if (showFullScreenEditor) {
2599− FullScreenEditor(
2600− value = value,
2601− onValueChange = onValueChange,
2602− onDismiss = { showFullScreenEditor = false },
2603− onSend = {
2604− showFullScreenEditor = false
2605− // Mirror the inline composer's behavior: while a run is active a send
2606− // can't go immediately, so queue the follow-up instead of silently
2607− // dropping it (vm.send() returns false during a run, which previously
2608− // lost the typed message with no feedback).
2609− if (running) onQueueFollowUp(value) else onSend()
2610− },
2611− canSend = enabled && hasContent,
2612− running = running,
2613− sendOnEnter = sendOnEnter,
2614− attachments = attachments,
2615− onRemoveAttachment = onRemoveAttachment,
2616− staging = staging,
2617− stagingFileCount = stagingFileCount,
2618− )
2619− }
2620− }
2621−}
2622−
2623−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2624− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2625−@OptIn(ExperimentalMaterial3Api::class)
2626−@Composable
2627−private fun FullScreenEditor(
2628− value: String,
2629− onValueChange: (String) -> Unit,
2630− onDismiss: () -> Unit,
2631− onSend: () -> Unit,
2632− canSend: Boolean,
2633− running: Boolean = false,
2634− sendOnEnter: Boolean = false,
2635− attachments: List<PendingAttachment> = emptyList(),
2636− onRemoveAttachment: (String) -> Unit = {},
2637− staging: Boolean = false,
2638− stagingFileCount: Int = 0,
2639−) {
2640− androidx.compose.ui.window.Dialog(
2641− onDismissRequest = onDismiss,
2642− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2643− ) {
2644− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2645− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2646− // gives the available width so we can center a capped-width column.
2647− androidx.compose.foundation.layout.BoxWithConstraints(
2648− modifier = Modifier.fillMaxSize(),
2649− contentAlignment = Alignment.Center,
2650− ) {
2651− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2652− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2653− else 0.dp
2654− Scaffold(
2655− modifier = Modifier.padding(horizontal = hPad),
2656− topBar = {
2657− androidx.compose.material3.TopAppBar(
2658− title = { Text(stringResource(R.string.compose_editor_title)) },
2659− navigationIcon = {
2660− androidx.compose.material3.TextButton(onClick = onDismiss) {
2661− Text(stringResource(R.string.collapse_editor))
2662− }
2663− },
2664− )
2665− },
2666− bottomBar = {
2667− Surface(tonalElevation = 3.dp) {
2668− Row(
2669− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2670− horizontalArrangement = Arrangement.End,
2671− ) {
2672− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2673− Text(stringResource(if (running) R.string.queue else R.string.send))
2674− }
2675− }
2676− }
2677− },
2678− ) { padding ->
2679− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2680− // Show staged attachments in the full-screen editor too, so a user who staged
2681− // images then expanded for a long prompt can still see and remove them without
2682− // collapsing first (mirrors the inline composer's AttachmentStrip).
2683− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2684− OutlinedTextField(
2685− value = value,
2686− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2687− modifier = Modifier
2688− .fillMaxSize()
2689− .weight(1f)
2690− // Honor the "Send on Enter" setting here too, so the full-screen
2691− // editor matches the inline composer: Enter sends (Shift+Enter
2692− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2693− // when off. Previously this hard-coded ImeAction.Default and had no
2694− // key handler, so a hardware-keyboard user got a different behaviour
2695− // from the inline composer depending on which they happened to open.
2696− .onPreviewKeyEvent { event ->
2697− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2698− val send = enterShouldSend(
2699− enabled = canSend,
2700− hasContent = canSend,
2701− sendOnEnter = sendOnEnter,
2702− shift = event.isShiftPressed,
2703− ctrl = event.isCtrlPressed,
2704− )
2705− if (send) { onSend(); true } else false
2706− },
2707− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2708− maxLines = Int.MAX_VALUE,
2709− keyboardOptions = KeyboardOptions(
2710− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2711− capitalization = KeyboardCapitalization.Sentences,
2712− ),
2713− keyboardActions = KeyboardActions(
2714− onSend = { if (canSend) onSend() },
2715− ),
2716− )
2717− }
2718− }
2719− }
2720− }
2721−}
2722−
2723−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2724− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2725−private fun enterShouldSend(
2726− enabled: Boolean,
2727− hasContent: Boolean,
2728− sendOnEnter: Boolean,
2729− shift: Boolean,
2730− ctrl: Boolean,
2731−): Boolean = when {
2732− !enabled || !hasContent -> false
2733− sendOnEnter -> !shift
2734− else -> ctrl
2735−}
2736−
2737−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2738− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2739− * [ChatInputBar] stays under the complexity threshold. */
2740−@Composable
2741−private fun ComposerTrailingButton(
2742− running: Boolean,
2743− aborting: Boolean,
2744− canSend: Boolean,
2745− canQueue: Boolean,
2746− onSend: () -> Unit,
2747− onAbort: () -> Unit,
2748− onQueue: () -> Unit,
2749−) {
2750− if (running) {
2751− Row(verticalAlignment = Alignment.CenterVertically) {
2752− // While a run is active the trailing action is Stop, so the only send affordance is
2753− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2754− // That leaves a touch-only user with the setting off no way to queue a follow-up
2755− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2756− // there's typed TEXT so queuing is always reachable, without changing the user's
2757− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2758− // canSend, which is also true for an attachment-only composer — because queuing "" just
2759− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2760− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2761− if (canQueue) {
2762− IconButton(
2763− onClick = onQueue,
2764− modifier = Modifier.testTag("queue_button"),
2765− ) {
2766− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2767− // icon (which can be read as "snooze" or "later"), and isn't confused with
2768− // the Send action sitting right beside the Stop button.
2769− Icon(
2770− Icons.AutoMirrored.Filled.PlaylistAdd,
2771− contentDescription = stringResource(R.string.queue_followup),
2772− )
2773− }
2774− }
2775− // Show a spinner while the abort REST call is in flight so the user sees the stop
2776− // was sent, and disable to prevent a double-tap.
2777− IconButton(
2778− onClick = onAbort,
2779− enabled = !aborting,
2780− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2781− ) {
2782− if (aborting) {
2783− val stopLabel = stringResource(R.string.stop)
2784− CircularProgressIndicator(
2785− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2786− strokeWidth = 2.dp,
2787− )
2788− } else {
2789− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2790− }
2791− }
2792− }
2793− } else {
2794− IconButton(
2795− onClick = onSend,
2796− enabled = canSend,
2797− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2798− ) {
2799− // Tint the send icon with primary when there's content to send so the commit action
2800− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2801− Icon(
2802− Icons.AutoMirrored.Filled.Send,
2803− contentDescription = stringResource(R.string.send),
2804− tint = if (canSend) MaterialTheme.colorScheme.primary
2805− else MaterialTheme.colorScheme.onSurfaceVariant,
2806− )
2807− }
2808− }
2809−}
2810−
2811−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2812−@Composable
2813−private fun EmptyConversation(
2814− onSuggestion: (String) -> Unit,
2815− modifier: Modifier = Modifier,
2816−) {
2817− // A few example prompts so a first-time user has a one-tap path to their first
2818− // message instead of staring at a blank input. Tapping a chip fills the draft
2819− // (without sending) so the user can edit it before sending.
2820− val suggestions = remember {
2821− listOf(
2822− R.string.empty_chat_suggest_1,
2823− R.string.empty_chat_suggest_2,
2824− R.string.empty_chat_suggest_3,
2825− )
2826− }
2827− Column(
2828− modifier = modifier.padding(32.dp),
2829− horizontalAlignment = Alignment.CenterHorizontally,
2830− ) {
2831− Icon(
2832− Icons.Filled.AutoAwesome,
2833− contentDescription = null,
2834− modifier = Modifier.size(48.dp),
2835− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2836− )
2837− Spacer(Modifier.size(16.dp))
2838− Text(
2839− stringResource(R.string.empty_chat_title),
2840− style = MaterialTheme.typography.titleMedium,
2841− )
2842− Spacer(Modifier.size(8.dp))
2843− Text(
2844− stringResource(R.string.empty_chat_hint),
2845− style = MaterialTheme.typography.bodyMedium,
2846− color = MaterialTheme.colorScheme.onSurfaceVariant,
2847− )
2848− Spacer(Modifier.size(20.dp))
2849− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2850− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2851− FlowRow(
2852− modifier = Modifier.fillMaxWidth(),
2853− horizontalArrangement = Arrangement.spacedBy(8.dp),
2854− verticalArrangement = Arrangement.spacedBy(8.dp),
2855− ) {
2856− suggestions.forEach { resId ->
2857− val text = stringResource(resId)
2858− androidx.compose.material3.AssistChip(
2859− onClick = { onSuggestion(text) },
2860− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2861− )
2862− }
2863− }
2864− }
2865−}
2866−
2867−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2868− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2869− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2870−@Composable
2871−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2872− val haptics = LocalHapticFeedback.current
2873− var showDiff by rememberSaveable { mutableStateOf(false) }
2874− val expandMotion = rememberVisibilityTransitions()
2875− Surface(
2876− color = MaterialTheme.colorScheme.tertiaryContainer,
2877− tonalElevation = 2.dp,
2878− modifier = Modifier.fillMaxWidth(),
2879− ) {
2880− Column {
2881− Row(
2882− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2883− verticalAlignment = Alignment.CenterVertically,
2884− horizontalArrangement = Arrangement.SpaceBetween,
2885− ) {
2886− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2887− Icon(
2888− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2889− contentDescription = null,
2890− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2891− modifier = Modifier.size(18.dp),
2892− )
2893− Text(
2894− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2895− style = MaterialTheme.typography.bodySmall,
2896− color = MaterialTheme.colorScheme.onTertiaryContainer,
2897− modifier = Modifier.padding(start = 8.dp),
2898− )
2899− // "Show what changed" toggle, shown only when the server provided a diff.
2900− // Collapsible so the banner stays compact by default; a user curious about
2901− // what the revert rolled back can expand it inline without leaving the chat.
2902− if (!diff.isNullOrBlank()) {
2903− TextButton(
2904− onClick = {
2905− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2906− showDiff = !showDiff
2907− },
2908− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2909− ) {
2910− Icon(
2911− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2912− contentDescription = null,
2913− modifier = Modifier.size(16.dp),
2914− )
2915− Text(
2916− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2917− style = MaterialTheme.typography.labelSmall,
2918− modifier = Modifier.padding(start = 4.dp),
2919− )
2920− }
2921− }
2922− }
2923− TextButton(onClick = {
2924− // Haptic on undo to match the other destructive/important confirmations: a
2925− // revert restores potentially hundreds of hidden messages.
2926− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2927− onUndo()
2928− }) { Text(stringResource(R.string.undo)) }
2929− }
2930− // The diff render lives inside the banner's Surface so it inherits the tertiary
2931− // tonal container and reads as part of the banner, not a floating panel.
2932− if (!diff.isNullOrBlank()) {
2933− AnimatedVisibility(
2934− visible = showDiff,
2935− enter = expandMotion.enter,
2936− exit = expandMotion.exit,
2937− ) {
2938− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2939− Text(
2940− stringResource(R.string.revert_diff_header),
2941− style = MaterialTheme.typography.labelSmall,
2942− color = MaterialTheme.colorScheme.onTertiaryContainer,
2943− modifier = Modifier.padding(bottom = 4.dp),
2944− )
2945− DiffView(diff, saveKey = "revertDiff")
2946− }
2947− }
2948− }
2949− }
2950− }
2951−}
2952−
2953−/** A dismissible preview card shown above the composer when the user quote-replied to a
2954− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2955− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2956− * the Discord/Slack quote-preview pattern. */
2957−@Composable
2958−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2959− val haptics = LocalHapticFeedback.current
2960− Surface(
2961− color = MaterialTheme.colorScheme.secondaryContainer,
2962− tonalElevation = 2.dp,
2963− modifier = Modifier.fillMaxWidth(),
2964− ) {
2965− Row(
2966− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2967− verticalAlignment = Alignment.Top,
2968− ) {
2969− Icon(
2970− Icons.Filled.FormatQuote,
2971− contentDescription = null,
2972− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2973− modifier = Modifier.size(18.dp).padding(top = 2.dp),
2974− )
2975− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
2976− Text(
2977− stringResource(R.string.quote_reply_banner),
2978− style = MaterialTheme.typography.labelSmall,
2979− color = MaterialTheme.colorScheme.onSecondaryContainer,
2980− )
2981− Text(
2982− quotedText,
2983− style = MaterialTheme.typography.bodySmall,
2984− color = MaterialTheme.colorScheme.onSecondaryContainer,
2985− maxLines = 2,
2986− overflow = TextOverflow.Ellipsis,
2987− )
2988− }
2989− IconButton(onClick = {
2990− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2991− onCancel()
2992− }) {
2993− Icon(
2994− Icons.Filled.Close,
2995− contentDescription = stringResource(R.string.cancel_quote_reply),
2996− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2997− modifier = Modifier.size(18.dp),
2998− )
2999− }
3000− }
3001− }
3002−}
3003−
3004−/** A banner shown while messages composed offline are queued in the outbox, with a
3005− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
3006−@Composable
3007−private fun OutboxBanner(
3008− count: Int,
3009− sending: Boolean,
3010− onFlush: () -> Unit,
3011− onDiscard: () -> Unit,
3012−) {
3013− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
3014− Surface(
3015− color = MaterialTheme.colorScheme.secondaryContainer,
3016− tonalElevation = 2.dp,
3017− modifier = Modifier.fillMaxWidth(),
3018− ) {
3019− Row(
3020− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
3021− verticalAlignment = Alignment.CenterVertically,
3022− horizontalArrangement = Arrangement.SpaceBetween,
3023− ) {
3024− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
3025− if (sending) {
3026− CircularProgressIndicator(
3027− Modifier.size(16.dp),
3028− strokeWidth = 2.dp,
3029− color = MaterialTheme.colorScheme.onSecondaryContainer,
3030− )
3031− Spacer(Modifier.size(8.dp))
3032− }
3033− Text(
3034− if (sending) {
3035− stringResource(R.string.outbox_sending)
3036− } else {
3037− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
3038− stringResource(res, count)
3039− },
3040− style = MaterialTheme.typography.bodySmall,
3041− color = MaterialTheme.colorScheme.onSecondaryContainer,
3042− )
3043− }
3044− if (!sending) {
3045− val haptics = LocalHapticFeedback.current
3046− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
3047− TextButton(onClick = {
3048− // Confirm before discarding all queued messages (irreversible), matching
3049− // the confirmation pattern used by deleteSession and other destructive
3050− // actions. Previously a single tap dropped every queued message.
3051− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
3052− showDiscardConfirm = true
3053− }) {
3054− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
3055− }
3056− }
3057− }
3058− }
3059− if (showDiscardConfirm) {
3060− androidx.compose.material3.AlertDialog(
3061− onDismissRequest = { showDiscardConfirm = false },
3062− title = { Text(stringResource(R.string.discard_queued_title)) },
3063− text = { Text(stringResource(R.string.discard_queued_text, count)) },
3064− confirmButton = {
3065− androidx.compose.material3.TextButton(onClick = {
3066− showDiscardConfirm = false
3067− onDiscard()
3068− }) { Text(stringResource(R.string.discard)) }
3069− },
3070− dismissButton = {
3071− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3072− Text(stringResource(R.string.cancel))
3073− }
3074− },
3075− )
3076− }
3077−}
3078−
3079−/** Prompt for a one-off shell command to run in the session's worktree. */
3080−@Composable
3081−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3082− var command by rememberSaveable { mutableStateOf("") }
3083− AlertDialog(
3084− onDismissRequest = onDismiss,
3085− title = { Text(stringResource(R.string.run_shell_command)) },
3086− text = {
3087− OutlinedTextField(
3088− value = command,
3089− onValueChange = { command = it },
3090− modifier = Modifier.fillMaxWidth(),
3091− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3092− label = { Text(stringResource(R.string.shell_command_label)) },
3093− singleLine = true,
3094− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3095− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3096− )
3097− },
3098− confirmButton = {
3099− TextButton(
3100− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3101− enabled = command.isNotBlank(),
3102− ) { Text(stringResource(R.string.run)) }
3103− },
3104− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3105− )
3106−}
3107−
3108−/**
3109− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3110− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3111− * equality is structural so `snapshotFlow` emits only when something relevant changes.
3112− */
3113−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3114−
3115−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3116− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3117− * streaming, not just plain assistant text. O(1). */
3118−private fun streamingContentLength(part: Part?): Int = when (part) {
3119− is TextPart -> part.text.length
3120− is ReasoningPart -> part.text.length
3121− is ToolPart -> when (val st = part.state) {
3122− is ToolCompleted -> st.output?.length ?: 0
3123− is ToolError -> st.error?.length ?: 0
3124− is ToolRunning -> st.title?.length ?: 0
3125− else -> 0
3126− }
3127− else -> 0
3128−}
3129−
3130−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3131− * dialog but lives in the chat screen so the user can rename without backing out to
3132− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3133−@Composable
3134−private fun RenameSessionChatDialog(
3135− initialTitle: String,
3136− onDismiss: () -> Unit,
3137− onConfirm: (String) -> Unit,
3138−) {
3139− // Seed the field once (no key input) so a later external title change — e.g. opencode
3140− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3141− // doesn't re-initialize the box and discard the user's in-progress edit.
3142− var title by rememberSaveable { mutableStateOf(initialTitle) }
3143− AlertDialog(
3144− onDismissRequest = onDismiss,
3145− title = { Text(stringResource(R.string.rename_session_chat)) },
3146− text = {
3147− OutlinedTextField(
3148− value = title,
3149− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3150− modifier = Modifier.fillMaxWidth(),
3151− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3152− label = { Text(stringResource(R.string.rename_session_chat)) },
3153− singleLine = true,
3154− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3155− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3156− )
3157− },
3158− confirmButton = {
3159− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3160− Text(stringResource(R.string.save))
3161− }
3162− },
3163− dismissButton = {
3164− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3165− },
3166− )
3167−}
3168−
3169−/**
3170− * A single item in the chat message list — either a [Message] bubble or a day
3171− * [Separator] inserted before the first message of a new day. The separator shifts
3172− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3173− * the [List] of these items (not `messages.size`/`lastIndex`).
3174− */
3175−private sealed interface MessageListItem {
3176− val key: Any
3177− val contentType: Any
3178−
3179− data class Message(
3180− val message: MessageWithParts,
3181− override val key: Any,
3182− // Whether this is the first message in a consecutive run of the same speaker (role).
3183− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3184− // reducing visual noise in tool-heavy conversations where many assistant messages
3185− // appear back-to-back. A separator or a role change resets the flag.
3186− val isFirstOfSpeaker: Boolean,
3187− ) : MessageListItem {
3188− override val contentType: Any get() = message.info::class
3189− }
3190−
3191− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3192− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3193− // can share a label (e.g. an untimestamped message — empty label — between two
3194− // same-day messages, or two untimestamped groups), and a label-only key would
3195− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3196− // stable for a given message ordering so slots aren't needlessly recreated.
3197− override val key: Any get() = "sep_${ordinal}_$label"
3198− // Separators share a contentType so the LazyColumn can recycle their slots.
3199− override val contentType: Any get() = "separator"
3200− }
3201−}
3202−
3203−/**
3204− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3205− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3206− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3207− * Messages with no timestamp are grouped under an empty-label separator only if they
3208− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3209− *
3210− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3211− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3212− * labels; older days fall back to a locale-stable medium-date format.
3213− */
3214−private fun buildMessageListItems(
3215− messages: List<MessageWithParts>,
3216− todayLabel: String,
3217− yesterdayLabel: String,
3218−): List<MessageListItem> {
3219− if (messages.isEmpty()) return emptyList()
3220− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3221− val dateFmt = mediumDateFormat()
3222− val result = ArrayList<MessageListItem>(messages.size + 4)
3223− val seenKeys = HashSet<String>(messages.size * 2)
3224− var lastDayKey: String? = null
3225− var sepOrdinal = 0
3226− var emptyIdOrdinal = 0
3227− var first = true
3228− // Track the previous message's role to detect consecutive same-speaker runs, so the
3229− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3230− // "no previous message or a separator just interrupted the run", both of which make the
3231− // next message the first of its group.
3232− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3233− for (message in messages) {
3234− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3235− val dayKey = ts?.let { dayKey(it) } ?: ""
3236− // Emit a separator before the very first message (so a leading un-timestamped message
3237− // still gets the first divider, empty label and all), and thereafter only when crossing
3238− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3239− // neither emits its own separator nor resets the day — otherwise a following same-day
3240− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3241− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3242− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3243− // A date separator visually breaks a speaker run, so the next message is treated
3244− // as the first of its group (even if the same role continues across the day break).
3245− prevRoleClass = null
3246− }
3247− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3248− first = false
3249− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3250− // empty id — and the reducer intentionally keeps several such messages as distinct
3251− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3252− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3253− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3254− if (!seenKeys.add(key)) {
3255− var suffix = 1
3256− while (!seenKeys.add("$key#$suffix")) suffix++
3257− key = "$key#$suffix"
3258− }
3259− val roleClass = message.info::class
3260− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3261− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3262− prevRoleClass = roleClass
3263− }
3264− return result
3265−}
3266−
3267−/**
3268− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3269− *
3270− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3271− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3272− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3273− * every message on every token. Message timestamps are immutable once assigned, so we
3274− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3275− * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3276− *
3277− * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3278− * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3279− * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3280− * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3281− * reads, so the common case (a hit) is a single volatile read + hash probe.
3282− * [removeEldestEntry] is not available on ConcurrentHashMap, so the bound is enforced via
3283− * a size check in [dayKey]: once the cap ([DAY_KEY_CACHE_MAX]) is reached the cache is
3284− * cleared; in practice the cache size is bounded by the number of distinct message
3285− * timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]) and the cap is a
3286− * safety valve for the process-lifetime cache across many sessions.
3287− */
3288−private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3289−
3290−/** Upper bound on [dayKeyCache] entries. Message timestamps are immutable once assigned, so
3291− * the natural bound is the number of distinct timestamps in a session (≤
3292− * [NetworkConfig.maxInMemoryMessages]); this cap is a safety valve for the process-lifetime
3293− * cache across many sessions, keeping a runaway leak from accumulating unbounded memory. */
3294−private const val DAY_KEY_CACHE_MAX = 1024
3295−
3296−private fun dayKey(epochMillis: Long): String {
3297− val cached = dayKeyCache[epochMillis]
3298− if (cached != null) return cached
3299− val value = java.time.Instant.ofEpochMilli(epochMillis)
3300− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3301− // Guard the size under the cache's concurrency: only the first thread to see the cap
3302− // exceeded evicts (draining is O(N) but rare and idempotent), so concurrent inserts
3303− // past the cap don't each pay the scan. computeIfAbsent would hold the segment lock
3304− // during the (cheap) date computation but can't express the size guard, so use put
3305− // after the fact; a duplicate put of the same key/value is harmless.
3306− if (dayKeyCache.size >= DAY_KEY_CACHE_MAX) dayKeyCache.clear()
3307− dayKeyCache[epochMillis] = value
3308− return value
3309−}
3310−
3311−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3312−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3313−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3314−private var cachedDateFmt: java.text.DateFormat? = null
3315−private var cachedDateFmtLocale: java.util.Locale? = null
3316−
3317−private fun mediumDateFormat(): java.text.DateFormat {
3318− val locale = java.util.Locale.getDefault()
3319− val existing = cachedDateFmt
3320− if (existing != null && cachedDateFmtLocale == locale) return existing
3321− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3322− cachedDateFmt = it
3323− cachedDateFmtLocale = locale
3324− }
3325−}
3326−
3327−/**
3328− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3329− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3330− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3331− * messages.
3332− */
3333−private fun dayLabel(
3334− dayKey: String,
3335− ts: Long,
3336− today: java.time.LocalDate,
3337− todayLabel: String,
3338− yesterdayLabel: String,
3339− dateFmt: java.text.DateFormat,
3340−): String {
3341− if (dayKey.isEmpty()) return ""
3342− val epochDay = dayKey.toLongOrNull() ?: return ""
3343− val date = java.time.LocalDate.ofEpochDay(epochDay)
3344− return when {
3345− date == today -> todayLabel
3346− date == today.minusDays(1) -> yesterdayLabel
3347− else -> dateFmt.format(java.util.Date(ts))
3348− }
3349−}
3350−
3351−/**
3352− * A centered day divider in the message list. Renders nothing for an empty label
3353− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3354− */
3355−@Composable
3356−private fun DateSeparator(label: String) {
3357− if (label.isBlank()) return
3358− Row(
3359− modifier = Modifier.fillMaxWidth(),
3360− horizontalArrangement = Arrangement.Center,
3361− ) {
3362− Surface(
3363− color = MaterialTheme.colorScheme.surfaceVariant,
3364− shape = MaterialTheme.shapes.small,
3365− // Marked as a heading so TalkBack users can navigate day-by-day with the
3366− // heading-skip gesture — the canonical affordance for date dividers in a list.
3367− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3368− ) {
3369− Text(
3370− label,
3371− style = MaterialTheme.typography.labelSmall,
3372− color = MaterialTheme.colorScheme.onSurfaceVariant,
3373− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3374− )
3375− }
3376− }
3377−}
3378−
3379−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3380− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3381− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3382− * [BoxScope] extension so it can align itself to the top center of its host box. */
3383−@Composable
3384−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3385− val loadingLabel = stringResource(R.string.loading)
3386− val reducedMotion = LocalReducedMotion.current
3387− val transition = rememberInfiniteTransition(label = "skeleton")
3388− val pulse by transition.animateFloat(
3389− initialValue = 0.35f,
3390− targetValue = 0.7f,
3391− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3392− label = "skeletonAlpha",
3393− )
3394− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3395− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3396− @Composable
3397− fun bar(widthFraction: Float) {
3398− Box(
3399− Modifier
3400− .fillMaxWidth(widthFraction)
3401− .height(14.dp)
3402− .clip(RoundedCornerShape(4.dp))
3403− .background(skeletonColor)
3404− .alpha(skeletonAlpha),
3405− )
3406− }
3407− Column(
3408− modifier = Modifier
3409− .align(Alignment.TopCenter)
3410− .padding(top = topPad)
3411− .padding(16.dp)
3412− .fillMaxWidth()
3413− .semantics { contentDescription = loadingLabel },
3414− verticalArrangement = Arrangement.spacedBy(14.dp),
3415− ) {
3416− repeat(4) { i ->
3417− val left = i % 2 == 0
3418− Row(
3419− modifier = Modifier.fillMaxWidth(),
3420− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3421− ) {
3422− Column(
3423− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3424− verticalArrangement = Arrangement.spacedBy(6.dp),
3425− ) {
3426− bar(1f)
3427− bar(0.8f)
3428− }
3429− }
3430− }
3431− }
3432−}