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