@@ -1,3456 +0,0 @@
1−@file:Suppress("TooManyFunctions")
3−package soy.iko.opencode.ui.chat
5−import android.app.Activity
6−import android.content.Intent
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.platform.LocalContext
134−import androidx.compose.ui.platform.LocalDensity
135−import androidx.compose.ui.platform.LocalHapticFeedback
136−import androidx.compose.ui.platform.LocalLayoutDirection
137−import androidx.compose.ui.platform.LocalView
138−import androidx.compose.ui.platform.testTag
139−import androidx.compose.ui.unit.LayoutDirection
140−import androidx.compose.ui.res.pluralStringResource
141−import androidx.compose.ui.res.stringResource
142−import androidx.compose.ui.semantics.Role
143−import androidx.compose.ui.semantics.contentDescription
144−import androidx.compose.ui.semantics.heading
145−import androidx.compose.ui.semantics.liveRegion
146−import androidx.compose.ui.semantics.LiveRegionMode
147−import androidx.compose.ui.semantics.invisibleToUser
148−import androidx.compose.ui.semantics.semantics
149−import androidx.compose.ui.text.input.ImeAction
150−import androidx.compose.ui.text.style.TextOverflow
151−import androidx.compose.ui.unit.dp
152−import androidx.lifecycle.compose.collectAsStateWithLifecycle
153−import androidx.lifecycle.viewmodel.compose.viewModel
154−import kotlinx.coroutines.Dispatchers
155−import kotlinx.coroutines.coroutineScope
156−import kotlinx.coroutines.delay
157−import kotlinx.coroutines.flow.collectLatest
158−import kotlinx.coroutines.flow.distinctUntilChanged
159−import kotlinx.coroutines.flow.first
160−import kotlinx.coroutines.launch
161−import kotlinx.coroutines.withContext
162−import soy.iko.opencode.data.model.Part
163−import soy.iko.opencode.data.model.MessageWithParts
164−import soy.iko.opencode.data.model.AssistantMessage
165−import soy.iko.opencode.data.model.Command
166−import soy.iko.opencode.data.model.ReasoningPart
167−import soy.iko.opencode.data.model.TextPart
168−import soy.iko.opencode.data.model.ToolCompleted
169−import soy.iko.opencode.data.model.ToolError
170−import soy.iko.opencode.data.model.ToolPart
171−import soy.iko.opencode.data.model.ToolRunning
172−import soy.iko.opencode.data.model.FilePart
173−import soy.iko.opencode.data.model.sourcePath
174−import soy.iko.opencode.data.model.inputElement
175−import soy.iko.opencode.data.network.EventStreamClient
176−import soy.iko.opencode.data.network.NetworkConfig
177−import soy.iko.opencode.di.AppContainer
178−import soy.iko.opencode.R
179−import soy.iko.opencode.ui.components.CommandPalette
180−import soy.iko.opencode.ui.components.ConnectionBanner
181−import soy.iko.opencode.ui.components.DiffView
182−import soy.iko.opencode.ui.components.PaletteAction
183−import soy.iko.opencode.ui.components.LocalReducedMotion
184−import soy.iko.opencode.ui.components.LocalSearchHighlight
186−import soy.iko.opencode.ui.components.copyToClipboard
187−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
188−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
189−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
190−import soy.iko.opencode.ui.components.showToast
191−import soy.iko.opencode.ui.components.toImageContext
192−import soy.iko.opencode.ui.vmFactory
193−import soy.iko.opencode.util.runCatchingCancellable
195−// Optional message id to scroll to and briefly highlight on first load (from global search).
196−// Consumed once: after the message is scrolled into view and highlighted, the focus is
197−// cleared so subsequent recompositions don't re-trigger the scroll.
198−@OptIn(ExperimentalMaterial3Api::class)
201− container: AppContainer,
204− onOpenFile: ((String) -> Unit)? = null,
205− onOpenSession: ((String) -> Unit)? = null,
206− focusMessageId: String? = null,
207− onEditProfile: ((String) -> Unit)? = null,
209− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
210− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
211− val running by vm.running.collectAsStateWithLifecycle()
212− val streamInterrupted by vm.streamInterrupted.collectAsStateWithLifecycle()
213− val aborting by vm.aborting.collectAsStateWithLifecycle()
214− val loading by vm.loading.collectAsStateWithLifecycle()
215− val loadError by vm.loadError.collectAsStateWithLifecycle()
216− val loadErrorInline by vm.loadErrorInline.collectAsStateWithLifecycle()
217− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
218− val models by vm.models.collectAsStateWithLifecycle()
219− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
220− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
221− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
222− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
223− val reconnectAttempts by vm.reconnectAttempts.collectAsStateWithLifecycle()
224− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
225− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
226− val agents by vm.agents.collectAsStateWithLifecycle()
227− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
228− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
229− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
230− val commands by vm.commands.collectAsStateWithLifecycle()
231− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
232− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
233− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
234− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
235− val draft by vm.draft.collectAsStateWithLifecycle()
236− val pendingQuote by vm.pendingQuote.collectAsStateWithLifecycle()
237− val attachments by vm.attachments.collectAsStateWithLifecycle()
238− val reverted by vm.reverted.collectAsStateWithLifecycle()
239− val editing by vm.editing.collectAsStateWithLifecycle()
240− val revertDiff by vm.revertDiff.collectAsStateWithLifecycle()
241− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
242− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
243− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
244− val preferredModelId by container.settingsStore.preferredModelId.collectAsStateWithLifecycle(initialValue = "")
245− val recentModelEntries by container.recentModelsStore.entries.collectAsStateWithLifecycle()
246− val compactSpacing by container.settingsStore.compactMessageSpacing.collectAsStateWithLifecycle(initialValue = false)
247− val notifPermission by container.settingsStore.notifPermission.collectAsStateWithLifecycle(initialValue = true)
248− val isOnline by container.isOnline.collectAsStateWithLifecycle()
249− val haptics = LocalHapticFeedback.current
250− val layoutDirection = LocalLayoutDirection.current
251− val scope = rememberCoroutineScope()
252− val shareContext = LocalContext.current
253− val defaultShareSubject = stringResource(R.string.share_subject)
254− val sessionLabel = stringResource(R.string.session)
255− val defaultModelLabel = stringResource(R.string.default_model)
256− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
258− append(selectedModel?.modelLabel ?: defaultModelLabel)
259− selectedAgent?.let { append(" · $it") }
263− // Connection profile (with auth) for rendering inline image attachments.
264− // Collect as state so a server switch recomposes the image context.
265− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
266− val imageContext = remember(activeConnection?.profile) {
267− activeConnection?.profile?.toImageContext()
270− // Mark this session as read while the user is viewing it; clear on leave so new
271− // background activity can badge it again.
272− DisposableEffect(sessionId) {
273− container.setCurrentSession(sessionId)
274− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
277− // Navigate away when the session is deleted via SSE so the user isn't left
278− // on a zombie screen showing a conversation that no longer exists. Surface a
279− // toast (not a snackbar) because the screen is about to be popped — a snackbar
280− // would be torn down before the user could read it, while a toast survives.
281− // Covers both SSE-driven deletion (deleted on another device) and a user-
282− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
283− // sets the same flag on success).
284− val deletedContext = LocalContext.current
285− LaunchedEffect(sessionDeleted) {
286− if (sessionDeleted) {
287− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
292− val snackbar = remember { SnackbarHostState() }
293− val retryLabel = stringResource(R.string.retry)
294− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
295− // Dedicated focus requester for the in-conversation search field. The overflow menu's
296− // "Find in conversation" and Ctrl+F previously called inputFocusRequester.requestFocus()
297− // (the composer), so typing went to the composer instead of the search field.
298− val searchFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
299− var showModelPicker by rememberSaveable { mutableStateOf(false) }
300− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
301− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
302− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
303− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
304− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
305− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
306− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
307− var showShellDialog by rememberSaveable { mutableStateOf(false) }
308− var showPalette by rememberSaveable { mutableStateOf(false) }
309− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
310− var searchActive by rememberSaveable { mutableStateOf(false) }
311− var chatSearch by rememberSaveable { mutableStateOf("") }
312− // Index of the currently-focused in-conversation search match (into the filtered list).
313− // Drives the up/down navigation: the search bar's arrows step through matches and scroll
314− // the list to each one, mirroring desktop chat apps (the bare filtered list previously
315− // required reading each message to find the term).
316− var searchPos by rememberSaveable { mutableIntStateOf(0) }
317− var searchFiltering by remember { mutableStateOf(false) }
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) }
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,
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 })
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 }
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)
365− snackbar.showSnackbar(event.message)
367− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
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()
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.
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) }
408− val dismisser = launch {
409− delay(NetworkConfig.undoDeleteDelayMs)
410− snackbar.currentSnackbarData?.dismiss()
412− val result = snackbar.showSnackbar(
413− message = sessionDeletedLabel,
414− actionLabel = undoLabel,
415− duration = SnackbarDuration.Indefinite,
418− if (result == SnackbarResult.ActionPerformed) {
419− vm.cancelSessionDelete(id)
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)
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()
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)
449− val photoPicker = rememberLauncherForActivityResult(
450− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
451− ) { uris -> stageUris(uris) }
453− val filePicker = rememberLauncherForActivityResult(
454− ActivityResultContracts.GetMultipleContents(),
455− ) { uris -> stageUris(uris) }
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(),
462− val uri = pendingCaptureUri
463− pendingCaptureUri = null
464− if (success && uri != null) stageUris(listOf(uri))
467− val voiceLauncher = rememberLauncherForActivityResult(
468− ActivityResultContracts.StartActivityForResult(),
470− if (result.resultCode == Activity.RESULT_OK) {
471− val spoken = result.data
472− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
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))
485− fun launchCamera() {
486− val uri = newCameraCaptureUri(appContext)
488− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
491− pendingCaptureUri = uri
492− runCatching { cameraLauncher.launch(uri) }
493− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
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)
501− runCatching { voiceLauncher.launch(intent) }
502− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
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)
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)
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) })
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)
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
560− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker && !searchActive) { showExitConfirm = true }
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
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 -> {
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.
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".
599− onClickLabel = changeLabel,
600− ) { showTitleMenu = true }
601− .semantics(mergeDescendants = true) {},
602− verticalAlignment = Alignment.CenterVertically,
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.
608− sessionTitle ?: sessionLabel,
610− overflow = TextOverflow.Ellipsis,
614− style = MaterialTheme.typography.labelSmall,
615− color = MaterialTheme.colorScheme.onSurfaceVariant,
617− overflow = TextOverflow.Ellipsis,
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.
626− Icons.Filled.KeyboardArrowDown,
627− contentDescription = null,
628− tint = MaterialTheme.colorScheme.onSurfaceVariant,
629− modifier = Modifier.size(20.dp),
632− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
634− text = { Text(stringResource(R.string.palette_switch_model)) },
635− enabled = !modelsLoading || models.isNotEmpty(),
636− onClick = { showTitleMenu = false; showModelPicker = true },
639− text = { Text(stringResource(R.string.palette_choose_agent)) },
640− enabled = !agentsLoading || agents.isNotEmpty(),
641− onClick = { showTitleMenu = false; showAgentPicker = true },
647− IconButton(onClick = {
648− if (running) showExitConfirm = true else onBack()
650− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
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.
659− val workingLabel = stringResource(R.string.working)
660− CircularProgressIndicator(
661− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
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)
676− onClick = { vm.refreshMessages() },
677− enabled = activeConnection != null && !refreshing && !running,
680− CircularProgressIndicator(
681− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
685− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
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)
710− IconButton(onClick = { showOverflowMenu = true }) {
711− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
714− expanded = showOverflowMenu,
715− onDismissRequest = { showOverflowMenu = false },
718− text = { Text(shareLabel) },
719− enabled = hasMessages,
721− showOverflowMenu = false
723− val md = withContext(Dispatchers.Default) {
724− buildConversationMarkdown(vm.messages.value, sessionTitle)
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)
731− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
732− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
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.
739− text = { Text(copyAsMarkdownLabel) },
740− enabled = hasMessages,
742− showOverflowMenu = false
744− val md = withContext(Dispatchers.Default) {
745− buildConversationMarkdown(vm.messages.value, sessionTitle)
747− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), md)
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).
755− text = { Text(shareAsJsonLabel) },
756− enabled = hasMessages,
758− showOverflowMenu = false
760− val json = withContext(Dispatchers.Default) {
761− buildConversationJson(vm.messages.value)
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)
768− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareAsJsonLabel)) }
769− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
774− text = { Text(copyAsJsonLabel) },
775− enabled = hasMessages,
777− showOverflowMenu = false
779− val json = withContext(Dispatchers.Default) {
780− buildConversationJson(vm.messages.value)
782− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_message), json)
787− text = { Text(commandsLabel) },
788− enabled = !commandsLoading || commands.isNotEmpty(),
789− onClick = { showOverflowMenu = false; showCommandPicker = true },
792− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
793− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
796− text = { Text(stringResource(R.string.find_in_conversation)) },
798− showOverflowMenu = false
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).
806− androidx.compose.material3.HorizontalDivider()
807− // Session sharing: create a public link, copy an existing one, or revoke it.
808− if (shareUrl == null) {
810− text = { Text(createShareLabel) },
811− enabled = hasMessages,
812− onClick = { showOverflowMenu = false; vm.shareSession() },
816− text = { Text(copyShareLabel) },
818− showOverflowMenu = false
820− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
821− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
826− text = { Text(stopShareLabel) },
827− onClick = { showOverflowMenu = false; vm.unshareSession() },
831− text = { Text(summarizeLabel) },
832− enabled = hasMessages && !running,
833− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
836− text = { Text(initLabel) },
838− onClick = { showOverflowMenu = false; showInitConfirm = true },
841− text = { Text(shellLabel) },
843− onClick = { showOverflowMenu = false; showShellDialog = true },
845− androidx.compose.material3.HorizontalDivider()
847− text = { Text(renameLabel) },
848− onClick = { showOverflowMenu = false; showRenameDialog = true },
851− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
852− onClick = { showOverflowMenu = false; showDeleteDialog = true },
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(
866− .align(Alignment.TopEnd)
868− .semantics { contentDescription = loadingLabel },
876− snackbarHost = { SnackbarHost(snackbar) },
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()
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()
889− enter = bannerMotion.enter,
890− exit = bannerMotion.exit,
894− isEditing = editing,
895− onUndo = { vm.unrevert() },
899− visible = queuedOffline.isNotEmpty(),
900− enter = bannerMotion.enter,
901− exit = bannerMotion.exit,
904− count = queuedOffline.size,
905− sending = outboxSending,
906− onFlush = { vm.flushQueued() },
907− onDiscard = { vm.discardAllQueued() },
911− visible = pendingQuote != null,
912− enter = bannerMotion.enter,
913− exit = bannerMotion.exit,
915− pendingQuote?.let { QuoteReplyBanner(it, onCancel = { vm.cancelQuoteReply() }) }
919− onValueChange = vm::updateDraft,
921− aborting = aborting,
922− enabled = activeConnection != null,
923− sendOnEnter = sendOnEnter,
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,
936− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
939− onPickFile = { filePicker.launch("*/*") },
940− onCamera = { launchCamera() },
941− onVoice = { launchVoice() },
942− onPasteImage = { stageUris(it) },
943− commands = commands,
944− onRunCommand = { 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).
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()) {
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(),
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 ->
1018− is TextPart -> p.text.contains(searchQuery, ignoreCase = true)
1019− is ReasoningPart -> p.text.contains(searchQuery, ignoreCase = true)
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
1031− is FilePart -> p.filename?.contains(searchQuery, ignoreCase = true) == true ||
1032− p.sourcePath?.contains(searchQuery, ignoreCase = true) == true
1038− searchFiltering = false
1042− // Keep the focused-match index in range as the query (and thus the match set) changes.
1043− // A new query resets to the first match (keyed on searchQuery alone so any change —
1044− // even one that still yields enough matches — jumps to index 0 rather than carrying
1045− // the old index over to a semantically unrelated message). A shrunk set clamps to
1046− // the last valid index (keyed on size so a content refresh that shrinks the matches
1047− // without a query change doesn't leave searchPos out of range).
1048− LaunchedEffect(searchQuery) {
1049− if (searchQuery.isNotEmpty()) searchFiltering = true
1052− LaunchedEffect(searchMessages.size) {
1053− if (searchPos >= searchMessages.size) searchPos = (searchMessages.size - 1).coerceAtLeast(0)
1055− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
1056− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
1058− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
1059− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
1060− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
1061− // would capture the first composition's list — which is empty, since `messages`
1062− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
1063− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
1064− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
1065− // whose value tracks the latest list.
1066− val currentListItems by rememberUpdatedState(listItems)
1068− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
1069− // while the user was scrolled away from the bottom, cleared once they return. A count
1070− // (vs. a bare dot) tells the user how much they missed at a glance.
1071− // rememberSaveable (not plain remember) so the badge count survives rotation: plain
1072− // remember resets to 0 on recreation, hiding the "new content" signal even though new
1073− // messages are still arriving. Int is Bundle-savable.
1074− var newContentCount by rememberSaveable { mutableIntStateOf(0) }
1076− val isPinnedToBottom by remember {
1078− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1079− // When a run is active, the LazyColumn has one trailing "__typing"
1080− // item after the last list item. Account for it so "pinned to bottom"
1081− // includes the working indicator — otherwise the pin check targets
1082− // listItems.lastIndex, the typing row sits just below the viewport,
1083− // and the user never sees the progress indicator even when pinned.
1084− val items = currentListItems
1085− val effectiveLast = if (running) items.size else items.lastIndex
1086− lastVisible >= effectiveLast || items.isEmpty()
1090− // Jump to the newest message once, when the conversation first loads. Guarded by a
1091− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
1092− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
1093− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
1094− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
1095− LaunchedEffect(listItems.isNotEmpty()) {
1096− if (listItems.isNotEmpty() && !didInitialScroll) {
1097− // When a run is active the LazyColumn has a trailing "__typing" row at
1098− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
1099− // running session lands truly pinned to bottom and streaming auto-scroll engages.
1100− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
1101− didInitialScroll = true
1105− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
1106− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
1107− // isPinnedToBottom check flips to false the instant you send — freezing
1108− // auto-scroll. If the user was pinned to the last item just before the run
1109− // began, bring the typing row into view so the pin (and streaming follow) is
1110− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
1111− // recomputed to false by now) so we don't scroll when the user had scrolled up.
1112− LaunchedEffect(running) {
1113− if (running && listItems.isNotEmpty()) {
1114− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
1115− if (lastVisible >= listItems.lastIndex) {
1116− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
1121− // Scroll the focused search match into view whenever the user steps through results with
1122− // the up/down arrows. Resolves the filtered message to its slot in listItems (which
1123− // includes date separators) and animates there.
1125− // Keyed ONLY on searchPos and searchQuery (not listItems): a bare listItems key re-keys
1126− // on every streamed token (the list is rebuilt per snapshot), which re-fires this effect
1127− // ~20×/sec during an active stream — re-scrolling to the focused match on every token
1128− // and making it impossible to browse other matches with the up/down arrows while content
1129− // is streaming. snapshotFlow (reading currentListItems, a rememberUpdatedState) waits for
1130− // the target to appear without re-keying the effect on every list change, mirroring the
1131− // focusedMessageId pattern below.
1132− LaunchedEffect(searchPos, searchQuery) {
1133− if (!searchActive || searchQuery.isEmpty()) return@LaunchedEffect
1134− val target = searchMessages.getOrNull(searchPos) ?: return@LaunchedEffect
1135− val targetId = target.info.id
1136− val index = snapshotFlow {
1137− currentListItems.indexOfFirst {
1138− it is MessageListItem.Message && it.message.info.id == targetId
1140− }.first { it >= 0 }
1141− runCatchingCancellable { listState.animateScrollToItem(index) }
1144− // Global-search deep link: scroll to and briefly highlight the matched message. The
1145− // focus id is threaded through the chat route from GlobalSearchScreen. The highlight
1146− // clears itself after a short delay so the user can re-read the surrounding context
1147− // without a persistent marker. Runs once per focusMessageId (cleared on consume).
1149− // Keyed ONLY on focusedMessageId (not listItems): a bare listItems key re-keys on every
1150− // streamed token (the list is rebuilt per snapshot), which cancels the 2.5s delay before
1151− // it can clear the highlight — re-scrolling to the focus on every token and making an
1152− // actively-streaming chat unreadable. snapshotFlow waits for the message to appear in the
1153− // list (it may not be present on the first composition while messages load) without
1154− // re-keying the effect on every list change.
1155− // rememberSaveable (not plain remember) so the cleared null survives rotation:
1156− // plain remember keyed on focusMessageId re-seeds the non-null nav arg on every
1157− // recreation, re-firing this effect and yanking scroll back to the focus after the
1158− // user already dismissed the highlight. String? is Bundle-savable.
1159− var focusedMessageId by rememberSaveable(focusMessageId) { mutableStateOf(focusMessageId) }
1160− val currentListItemsForFocus by rememberUpdatedState(listItems)
1161− LaunchedEffect(focusedMessageId) {
1162− val focus = focusedMessageId ?: return@LaunchedEffect
1163− // Wait for the focused message to appear in the list, then resolve its index. A
1164− // first-composition empty list (messages still loading) will populate as the seed
1165− // arrives; snapshotFlow re-evaluates on each list change until the match is found.
1166− val index = snapshotFlow {
1167− currentListItemsForFocus.indexOfFirst {
1168− it is MessageListItem.Message && it.message.info.id == focus
1170− }.first { it >= 0 }
1171− runCatchingCancellable { listState.animateScrollToItem(index) }
1172− kotlinx.coroutines.delay(2500)
1173− focusedMessageId = null
1176− // Scroll to bottom when the IME opens and the user was already pinned to bottom, so the
1177− // latest reply stays visible as the composer rises. Without this the IME can obscure the
1178− // last message even though the user was reading it a moment ago. WindowInsets.ime is a
1179− // @Composable property, so we read it inside a snapshotFlow registered in the composable
1180− // scope; the flow re-emits whenever the IME inset changes (open/close transitions).
1181− val density = androidx.compose.ui.platform.LocalDensity.current
1182− var wasImeOpen by rememberSaveable { mutableStateOf(false) }
1183− val imeBottomPx = WindowInsets.ime.getBottom(density)
1184− androidx.compose.runtime.LaunchedEffect(imeBottomPx, listItems.isNotEmpty(), isPinnedToBottom) {
1185− if (listItems.isEmpty()) return@LaunchedEffect
1186− val imeOpen = imeBottomPx > 0
1187− // Scroll to bottom only on the open transition (not close) and only when the user
1188− // was already pinned to bottom — otherwise we'd yank them out of a mid-history read.
1189− val shouldScroll = imeOpen && !wasImeOpen && isPinnedToBottom
1190− if (shouldScroll) {
1191− runCatchingCancellable {
1192− listState.animateScrollToItem(if (running) listItems.size else listItems.lastIndex)
1195− wasImeOpen = imeOpen
1198− LaunchedEffect(Unit) {
1201− var initialized = false
1203− // Track list size + the streaming length of the last part so we auto-scroll
1204− // as content arrives, plus the pinned flag. A small data class with primitive
1205− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
1206− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
1207− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
1208− // and tool output — not just TextPart — keeps a pinned view following a long
1209− // reasoning/tool block while it streams (previously it stalled at 0).
1210− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
1211− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
1212− }.collect { signal ->
1213− if (!initialized) {
1214− prevSize = signal.size
1215− prevLen = signal.lastTextLength
1219− if (signal.pinned) {
1220− // Back at the bottom: clear the new-content badge.
1221− newContentCount = 0
1222− if (signal.size > 0) {
1223− // Scroll to the effective last index, including the trailing
1224− // "__typing" row when a run is active so the working indicator
1225− // is brought into view (not just the last message).
1226− val items = currentListItems
1227− val target = if (running) items.size else items.lastIndex
1228− listState.scrollToItem(target)
1230− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
1231− // Content arrived while scrolled up — increment the jump-to-latest badge.
1232− // Only count whole new items (not per-token growth) so the number reflects
1233− // new messages, not a token count.
1234− if (signal.size > prevSize) newContentCount += signal.size - prevSize
1235− else if (newContentCount == 0) newContentCount = 1
1237− prevSize = signal.size
1238− prevLen = signal.lastTextLength
1242− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
1243− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
1244− // content padding accounts for the bottomBar's raised height, so the message
1245− // list is already above the keyboard. Adding imePadding here would double-apply
1246− // the IME inset and push messages too far up.
1248− // BoxWithConstraints so the FABs and search bar can align to the capped (800dp)
1249− // message list on wide screens instead of floating at the screen edges — on a
1250− // tablet the list is a centered column, so edge-aligned FABs are visually detached.
1251− // The horizontal margin below is applied to the FAB/search containers so they
1252− // track the list's left/right edges.
1253− androidx.compose.foundation.layout.BoxWithConstraints(
1254− modifier = Modifier.fillMaxSize().padding(padding),
1256− val screenMaxWidth = maxWidth
1257− val listMaxWidth = NetworkConfig.chatContentMaxWidthDp.dp
1258− // Horizontal margin between the capped list's edge and the screen edge (0 on
1259− // screens narrower than the cap). Applied as start/end padding so the FABs and
1260− // search bar sit at the list's edges, not the screen's.
1261− val sideMargin = ((screenMaxWidth - listMaxWidth) / 2).coerceAtLeast(0.dp)
1262− if (activeConnection == null) {
1264− modifier = Modifier.align(Alignment.Center).padding(24.dp),
1265− horizontalAlignment = Alignment.CenterHorizontally,
1268− stringResource(R.string.not_connected),
1269− color = MaterialTheme.colorScheme.error,
1271− Spacer(Modifier.size(12.dp))
1272− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
1273− if (reconnecting) {
1274− CircularProgressIndicator(
1275− Modifier.size(20.dp),
1276− color = MaterialTheme.colorScheme.onPrimary,
1277− strokeWidth = 2.dp,
1280− Text(stringResource(R.string.reconnect))
1285− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
1286− // Measure the banner's actual height instead of hardcoding 44dp. At large
1287− // accessibility font scales the banner's labelMedium text + spinner + Retry
1288− // button exceed 44dp, so a fixed inset lets the first message hide behind it
1289− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
1290− // fires while the banner is composed (visible), so gate the inset on
1291− // bannerVisible and fall back to 44dp until the first measurement arrives.
1292− val topPad = if (bannerVisible) {
1293− NetworkConfig.connectionBannerHeightDp.dp + 4.dp
1296− } + if (searchActive) {
1297− NetworkConfig.chatSearchBarHeightDp.dp + 4.dp
1302− state = connectionState,
1303− modifier = Modifier.align(Alignment.TopCenter),
1304− isOnline = isOnline,
1305− // On a hard endpoint failure, retry by forcing an SSE reconnect (which
1306− // re-seeds from REST). refreshMessages is the right recovery path
1307− // when the connection is present but the stream died; reconnect()
1308− // is the path when the whole connection is gone (handled by the
1309− // separate "Not connected" state below).
1310− onRetry = { vm.refreshMessages() },
1311− // On an auth failure (401/403), retrying with the same bad credentials
1312− // is futile — offer a one-tap path to edit the active profile's
1313− // credentials instead of making the user hunt for the server list.
1314− onEditCredentials = {
1315− val profileId = activeConnection?.profile?.id
1316− if (profileId != null) onEditProfile?.invoke(profileId)
1318− reconnectAttempts = reconnectAttempts,
1320− // Persistent inline error banner for a mid-conversation load failure.
1321− // Unlike the one-shot snackbar (which fires once per streak then goes
1322− // silent), this stays visible until the stream recovers, so a persistent
1323− // outage doesn't read as "everything is fine" after the snackbar dismisses.
1324− // Anchored at the top, below the connection banner, so it doesn't overlap
1325− // the message list.
1326− if (loadErrorInline && hasMessages) {
1328− color = MaterialTheme.colorScheme.errorContainer,
1329− shape = MaterialTheme.shapes.small,
1330− modifier = Modifier
1331− .align(Alignment.TopCenter)
1332− .padding(top = if (bannerVisible) topPad else 8.dp)
1333− .padding(horizontal = 16.dp)
1334− .semantics { liveRegion = LiveRegionMode.Polite },
1337− modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),
1338− verticalAlignment = Alignment.CenterVertically,
1339− horizontalArrangement = Arrangement.spacedBy(8.dp),
1342− Icons.Filled.ErrorOutline,
1343− contentDescription = null,
1344− modifier = Modifier.size(16.dp),
1345− tint = MaterialTheme.colorScheme.onErrorContainer,
1348− stringResource(R.string.load_error_persistent),
1349− style = MaterialTheme.typography.labelMedium,
1350− color = MaterialTheme.colorScheme.onErrorContainer,
1351− modifier = Modifier.weight(1f),
1354− onClick = { vm.refreshMessages() },
1355− contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
1357− Text(stringResource(R.string.retry))
1362− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
1363− // recovery is a swipe away everywhere — not just when the message list is
1364− // populated. Previously PTR was only around the populated list, leaving the
1365− // error/loading states reachable only via a button tap.
1367− isRefreshing = refreshing,
1368− // Suppress the refresh action while a run is active: a mid-stream
1369− // refresh forces an SSE reconnect that can interrupt the actively
1370− // streaming reply (matching the top-bar refresh button, which is
1371− // also disabled while running). The pull gesture still responds, but
1372− // the release no-ops instead of triggering a disruptive re-seed.
1373− onRefresh = { if (!running) vm.refreshMessages() },
1374− // Cap width and center on large screens for readability — full-width
1375− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
1376− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
1377− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
1379− // Reserve top space when the banner is visible so it doesn't overlap the
1380− // first message / state content. (topPad computed above.)
1381− if (loading && messages.isEmpty()) {
1382− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1383− // than a bare centered spinner and the first real messages pop into an
1384− // already-shaped list instead of a blank-then-pop.
1385− ChatSkeleton(topPad = topPad)
1386− } else if (loadError && messages.isEmpty()) {
1387− // A failed load with nothing to show. Distinct from the empty
1388− // conversation state below — the conversation isn't empty, it
1389− // failed to load, and offering "Start a conversation" here is
1390− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1392− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1393− horizontalAlignment = Alignment.CenterHorizontally,
1396− stringResource(R.string.load_messages_failed),
1397− color = MaterialTheme.colorScheme.error,
1399− Spacer(Modifier.size(12.dp))
1400− Button(onClick = { vm.refreshMessages() }) {
1401− Text(stringResource(R.string.retry))
1403− // When the VM's retryWhen loop is actively retrying (loading is true
1404− // on top of the error state), surface a small "retrying…" indicator so
1405− // the user knows the system is working — without it, the static error
1406− // + Retry button reads as "broken, tap to fix", and the user may not
1407− // realize an automatic retry is already in progress.
1409− Spacer(Modifier.size(12.dp))
1410− val retryingLabel = stringResource(R.string.retrying_ellipsis)
1411− Row(verticalAlignment = Alignment.CenterVertically) {
1412− CircularProgressIndicator(
1413− Modifier.size(14.dp),
1414− strokeWidth = 2.dp,
1418− style = MaterialTheme.typography.labelSmall,
1419− color = MaterialTheme.colorScheme.onSurfaceVariant,
1420− modifier = Modifier.padding(start = 6.dp),
1425− } else if (messages.isEmpty() && running) {
1426− // A run just started but no parts have arrived yet — the empty list with
1427− // only the trailing "working…" row looks broken. Reuse the skeleton bubbles
1428− // from the initial-load branch so the perceived start latency is lower and
1429− // the first real assistant part pops into an already-shaped list.
1430− ChatSkeleton(topPad = topPad)
1431− } else if (messages.isEmpty()) {
1435− // Focus the input so the user can edit the suggestion before
1436− // sending, instead of having to manually tap the field.
1437− runCatching { inputFocusRequester.requestFocus() }
1439− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1442− val lastMessageId = messages.lastOrNull()?.info?.id
1443− // Text-to-speech for reading assistant replies aloud; shuts down when the
1444− // message list leaves composition.
1445− val tts = rememberTtsController()
1446− val speakingMessageId by tts.speakingId
1447− val ttsState by tts.state
1448− // Provide the in-conversation search query to the markdown renderer so matching
1449− // text spans are highlighted in-place (in addition to the focused-row highlight
1450− // above). Scoped to the list so cleared search stops highlighting immediately.
1451− val activeSearchQuery = searchQuery.takeIf { searchActive && it.isNotEmpty() }
1452− CompositionLocalProvider(LocalSearchHighlight provides activeSearchQuery) {
1455− modifier = Modifier.fillMaxSize(),
1456− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1457− // never floats over the last message. Top padding grows when the
1458− // connection banner is visible so it doesn't overlap the first message.
1459− contentPadding = PaddingValues(
1463− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1465− // Compact spacing (8dp) vs the default 16dp — a power-user toggle to fit
1466− // more conversation on screen without scrolling as much.
1467− verticalArrangement = Arrangement.spacedBy(if (compactSpacing) 8.dp else 16.dp),
1472− contentType = { it.contentType },
1474− // When in-conversation search is stepping through matches, highlight the
1475− // focused one's row so the user can spot it at a glance among the filtered
1476− // results (full in-text term highlighting would require threading the query
1477− // through the markdown renderer; the row highlight + scroll-to-match covers
1478− // the navigation use case desktop chat apps solve with next/prev).
1479− val focusedMatchId = if (searchActive && searchQuery.isNotEmpty()) {
1480− searchMessages.getOrNull(searchPos)?.info?.id
1482− val isFocusedMatch = focusedMatchId != null &&
1483− item is MessageListItem.Message &&
1484− item.message.info.id == focusedMatchId
1485− // No animateItem() here. It is backed by SizeAnimationModifierNode, which
1486− // forces a draw-phase remeasure (the display-list rebuild triggered by
1487− // AndroidComposeView.dispatchDraw) when its target's size changes. That
1488− // remeasure runs inside the draw pass and reads Placeable.getWidth()/
1489− // getHeight() of a child whose measured size hasn't been committed yet —
1490− // an NPE in PaddingValuesModifier.measure / FillNode.measure (the R8 map
1491− // marks both sites with a throws(NullPointerException) rewriteFrame).
1493− // This is the same crash class previously fixed for the markdown library's
1494− // animateContentSize and MessageBubble's send-status AnimatedContent. An
1495− // earlier fix kept animateItem() but skipped it for the actively-streaming
1496− // row; that was insufficient because the crash also fires when OPENING a
1497− // chat (running = false, so every row kept animateItem()): historical rows
1498− // with async-loading content (DiffView's produceState starts empty and
1499− // fills a frame later; RemoteImage loading; large markdown) change size
1500− // after mount and trigger the same draw-phase remeasure. animateItem() is
1501− // fundamentally unsafe on any chat row whose size can change post-mount,
1502− // so it is removed entirely. The glide-in animation it provided is
1503− // decorative (the list already auto-scrolls to new messages) and is not
1504− // worth a 4th round of this crash.
1508− if (isFocusedMatch) {
1509− Modifier.background(
1510− MaterialTheme.colorScheme.secondaryContainer,
1511− MaterialTheme.shapes.medium,
1519− is MessageListItem.Separator -> DateSeparator(item.label)
1520− is MessageListItem.Message -> {
1521− val message = item.message
1522− val messageId = message.info.id
1523− // Only the last (streaming) message needs isRunning — it drives the
1524− // reasoning-block spinner. Passing the live flag to every bubble
1525− // makes all visible messages recompose whenever a run starts or stops.
1526− val modelLabel = remember(message.info, models) {
1527− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1528− ?.let { resolveModelLabel(it, models) }
1530− // Key agentLabel/quoteText on the message id + the id of the
1531− // last TextPart/AgentPart, so the streaming message's label
1532− // updates when a NEW text/agent part is appended (its id
1533− // changes) without re-running filterIsInstance per token (a
1534− // streaming TextPart's id is stable across token updates, so
1535− // the key only changes on append, not on every token). The
1536− // prior `remember(messageId)` pinned these at first
1537− // composition: for a message that started with reasoning/tool
1538− // parts before any TextPart, quoteText stayed "" for the life
1539− // of the list item, so swipe-to-reply yielded "cannot quote
1540− // this" even after text arrived.
1541− val lastTextPartId = remember(message.parts) {
1542− message.parts.lastOrNull { it is TextPart }?.id
1544− val lastAgentPartId = remember(message.parts) {
1545− message.parts.filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1546− .lastOrNull { it.name.isNotBlank() }?.id
1548− val agentLabel = remember(messageId, lastAgentPartId) {
1550− .filterIsInstance<soy.iko.opencode.data.model.AgentPart>()
1551− .firstOrNull { it.name.isNotBlank() }?.name
1553− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1554− // image/code-only messages, which then opt out of the swipe gesture.
1555− val quoteText = remember(messageId, lastTextPartId) {
1557− .filterIsInstance<TextPart>()
1558− .joinToString("\n\n") { it.text }
1560− .takeIf { it.isNotEmpty() }
1562− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1563− // snapping back (the message isn't dismissed — the quote fills the composer).
1564− // Enabled for non-text messages too (image/tool-only), but the confirm
1565− // callback gives a haptic without triggering reply — so the user gets a
1566− // perceptible "can't quote this" signal instead of a silently dead gesture.
1567− val cantQuoteMsg = stringResource(R.string.cannot_quote_this)
1568− val undoLabel = stringResource(R.string.undo)
1569− val quoteReplyLabel = stringResource(R.string.quote_reply_banner)
1570− // Memoize the swipe confirmValueChange lambda on the message id + quoteText
1571− // so it's stable across recompositions (a fresh lambda would force the
1572− // SwipeToDismissBox to re-instantiate its state capture). quoteText is a
1573− // derived value that's stable for non-streaming messages.
1574− val swipeState = rememberSwipeToDismissBoxState(
1575− confirmValueChange = remember(messageId, quoteText) {
1577− val replyValue = if (layoutDirection == LayoutDirection.Rtl) {
1578− SwipeToDismissBoxValue.EndToStart
1580− SwipeToDismissBoxValue.StartToEnd
1582− if (value == replyValue) {
1583− if (quoteText != null) {
1584− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1585− vm.quoteReply(quoteText)
1586− runCatching { inputFocusRequester.requestFocus() }
1588− val res = snackbar.showSnackbar(
1589− message = quoteReplyLabel,
1590− actionLabel = undoLabel,
1592− if (res == androidx.compose.material3.SnackbarResult.ActionPerformed) {
1593− vm.cancelQuoteReply()
1597− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1598− scope.launch { snackbar.showSnackbar(cantQuoteMsg) }
1605− // In RTL locales, mirror the swipe direction so the reply
1606− // gesture reads naturally (swipe from the trailing edge
1607− // toward the leading edge), matching how LTR users swipe
1608− // left-to-right. Without this, RTL users had no reply swipe.
1609− val replyFromStartToEnd = layoutDirection != LayoutDirection.Rtl
1610− // Memoize every MessageBubble lambda on the message id so a recomposition
1611− // triggered by a sibling (e.g. the streaming message's parts changing,
1612− // which gives `listItems` a new identity) doesn't allocate fresh lambdas
1613− // for the unchanged bubbles. MessageBubble is non-skippable (it takes
1614− // many `(() -> Unit)?` params, which Compose treats as unstable), so
1615− // without memoization every visible bubble recomposes on every token,
1616− // defeating the @Immutable MessageWithParts reference-stability the
1617− // reducer's Holder cache provides. This mirrors the SessionListScreen
1618− // per-card lambda memoization pattern.
1619− val onRevert = remember(messageId) { { vm.revertTo(messageId) } }
1620− val onEdit = remember(messageId) {
1622− // editMessage reverts to before this message (hiding it and
1623− // everything after); the revert banner surfaces the rewind
1624− // with an Undo. Focus + scroll the composer into view like the
1625− // Quote action so the prefilled draft isn't off-screen.
1626− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1627− vm.editMessage(messageId, text)
1628− runCatching { inputFocusRequester.requestFocus() }
1629− contentScope.launch {
1630− runCatchingCancellable {
1631− listState.animateScrollToItem(currentListItems.lastIndex.coerceAtLeast(0))
1637− val onSpeak = remember(messageId) {
1639− if (!tts.toggle(messageId, text)) {
1640− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1645− val onPause = remember { { tts.pause() } }
1646− val onResume = remember { { tts.resume() } }
1647− val onStop = remember { { tts.stop() } }
1648− val onQuote = remember(messageId) {
1650− vm.quoteReply(text)
1651− runCatching { inputFocusRequester.requestFocus() }
1655− val onBranch = remember { { text: String -> vm.branchFrom(text); Unit } }
1656− // Regenerate is only meaningful for a finished assistant reply
1657− // (not the actively-streaming one), so gate it on !running.
1658− val onRegenerate = if (!running) {
1659− remember(messageId) { { vm.regenerate(messageId) } }
1663− // Continue: resume a partial reply. Shown only for
1664− // incomplete assistant messages (a partial reply that
1665− // was aborted) and not while a run is active.
1666− val canContinue = !running && message.info is AssistantMessage && !message.info.isComplete
1667− val onContinue = if (canContinue) {
1668− remember(messageId) { { vm.continueRun(messageId) } }
1672− val messageFailed = optimisticStatuses[messageId] == true
1673− val onRetry = if (messageFailed) {
1674− remember(messageId) { { vm.retryOptimisticMessage(messageId); Unit } }
1678− val onDismiss = if (messageFailed) {
1679− remember(messageId) { { vm.dismissOptimistic(messageId) } }
1683− val onShare = remember(messageId, sessionTitle, defaultShareSubject) {
1685− // Per-message share: build a single-message Markdown
1686− // transcript off-thread and fire ACTION_SEND, mirroring the
1687− // whole-conversation share but scoped to just this message.
1689− val md = withContext(Dispatchers.Default) {
1690− buildMessageMarkdown(message)
1692− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
1693− type = "text/markdown"
1694− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
1695− putExtra(android.content.Intent.EXTRA_TEXT, md)
1697− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareContext.getString(R.string.share_message))) }
1698− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
1704− state = swipeState,
1705− enableDismissFromEndToStart = !replyFromStartToEnd,
1706− enableDismissFromStartToEnd = replyFromStartToEnd,
1707− backgroundContent = {
1709− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1710− contentAlignment = if (replyFromStartToEnd) Alignment.CenterStart else Alignment.CenterEnd,
1713− Icons.AutoMirrored.Filled.Reply,
1714− contentDescription = null,
1715− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1722− isRunning = running && messageId == lastMessageId,
1723− imageContext = imageContext,
1724− modelLabel = modelLabel,
1725− agentLabel = agentLabel,
1726− onOpenFile = onOpenFile,
1727− onRevert = onRevert,
1730− isSpeaking = messageId == speakingMessageId,
1731− ttsState = if (messageId == speakingMessageId) ttsState else TtsState.IDLE,
1733− onResume = onResume,
1736− onBranch = onBranch,
1737− onRegenerate = onRegenerate,
1738− onContinue = onContinue,
1739− sendStatus = optimisticStatuses[messageId]?.let { failed ->
1740− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1741− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1743− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1745− onDismiss = onDismiss,
1747− isFirstOfSpeaker = item.isFirstOfSpeaker,
1748− highlighted = focusedMessageId != null && messageId == focusedMessageId,
1756− item(key = "__typing") {
1757− val workingText = stringResource(R.string.working)
1758− // When the SSE stream dropped mid-run, show a "reconnecting" label
1759− // instead of the plain "working" text so the user understands the
1760− // run is still active but the stream is reconnecting (not finished).
1761− val reconnectingText = stringResource(R.string.reconnecting)
1762− val interruptedLabel = if (streamInterrupted) reconnectingText else workingText
1763− // Elapsed-since-run chip driven by the VM's runStartMs so the timer
1764− // survives LazyColumn recycling — a local remember reset to 0:00 when
1765− // the row was disposed and scrolled back into view. The VM stamps the
1766− // start on the real false→true transition (send/run/init), not on
1767− // SSE-reconnect relight, so reconnects don't restart the clock. Updates
1768− // once per second; the value is decorative (the a11y label is the row's).
1769− // The clock freezes when an abort is confirmed (aborting = true) so the
1770− // user can see how long the run lasted before they stopped it, rather
1771− // than the clock continuing to tick until SessionIdle clears _running.
1772− val startMs by vm.runStartMs.collectAsStateWithLifecycle()
1773− // Seed the initial value synchronously from startMs so the timer
1774− // doesn't flash 0:00 when the __typing row is recycled by LazyColumn
1775− // (scrolled out then back in): produceState's coroutine is cancelled on
1776− // disposal and re-launched on re-entry, and a 0L initialValue would
1777− // briefly show "0:00" before the producer's first iteration runs.
1778− val elapsedMs by produceState(
1779− initialValue = if (startMs > 0L) (System.currentTimeMillis() - startMs).coerceAtLeast(0L) else 0L,
1782− if (startMs == 0L) return@produceState
1784− // Freeze at the last-computed value: one final snapshot then stop.
1785− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1786− return@produceState
1789− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1793− val elapsedText = remember(elapsedMs) {
1794− val total = elapsedMs / 1000
1795− // Locale.US for stable digit formatting: on locales with
1796− // non-ASCII digits (ar-/fa-) the default locale would render
1797− // localized digits inside the Monospace block, breaking the
1798− // fixed-width alignment the monospace family was chosen for.
1799− String.format(java.util.Locale.US, "%d:%02d", total / 60, total % 60)
1802− verticalAlignment = Alignment.CenterVertically,
1803− // No animateItem() here for the same reason as the message rows
1804− // above: the __typing row's size changes (the elapsed-time Text
1805− // grows from "0:00" to "M:SS" and the spinner mounts on first
1806− // frame), and animateItem()'s SizeAnimationModifierNode forces a
1807− // draw-phase remeasure that NPEs on Placeable.getWidth(). The
1808− // working row is mounted/unmounted as a whole item (key="__typing")
1809− // by LazyColumn, which already crossfades the appearance; the
1810− // placement animation is not needed.
1811− modifier = Modifier
1812− .padding(vertical = 4.dp),
1814− // Merge the indicator + label + clock into one TalkBack node so
1815− // it's announced once (the working label, then the elapsed time)
1816− // instead of "working… / working… / 0:14" with the label read
1817− // twice. The Stop IconButton below stays separately focusable.
1819− verticalAlignment = Alignment.CenterVertically,
1820− modifier = Modifier.semantics(mergeDescendants = true) {
1821− contentDescription = "$interruptedLabel $elapsedText"
1824− // Dim the spinner when interrupted so the row reads as
1825− // "paused/reconnecting" rather than actively progressing.
1826− CircularProgressIndicator(
1827− Modifier.size(16.dp),
1828− strokeWidth = 2.dp,
1829− color = if (streamInterrupted) MaterialTheme.colorScheme.onSurfaceVariant
1830− else MaterialTheme.colorScheme.primary,
1832− Text(interruptedLabel, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1833− Spacer(Modifier.size(8.dp))
1835− Icons.Filled.Schedule,
1836− contentDescription = null,
1837− modifier = Modifier.size(14.dp),
1838− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1842− style = MaterialTheme.typography.labelMedium,
1843− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1844− color = MaterialTheme.colorScheme.onSurfaceVariant,
1845− modifier = Modifier.padding(start = 4.dp),
1848− // A trailing Stop on the working row so the run can be aborted
1849− // without scrolling back to the composer (which may be off-screen
1850− // while the user reads the streaming output up-thread).
1851− Spacer(Modifier.weight(1f))
1852− val stopLabel = stringResource(R.string.stop)
1854− onClick = { vm.abort() },
1855− modifier = Modifier.semantics { contentDescription = stopLabel },
1857− Icon(Icons.Filled.Stop, contentDescription = null)
1866− // Jump-to-latest affordance when the user has scrolled away during a stream.
1867− val fabMotion = rememberVisibilityTransitions()
1868− AnimatedVisibility(
1869− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1870− enter = fabMotion.enter,
1871− exit = fabMotion.exit,
1872− // Inset by sideMargin on wide screens so the FAB tracks the capped list's
1873− // edge instead of floating at the screen edge (visually detached on tablets).
1874− modifier = Modifier.align(Alignment.BottomEnd).padding(end = sideMargin),
1876− // Badge the FAB when new content arrived while the user was scrolled up, so
1877− // they know there's something new to jump to (cleared once back at bottom).
1880− if (newContentCount > 0) {
1881− // Merge the count into the badge announcement so TalkBack reads
1882− // "5 new messages" instead of the bare label and a separate number.
1883− val newContentLabel = pluralStringResource(
1884− R.plurals.plurals_new_messages,
1889− modifier = Modifier.semantics {
1890− contentDescription = newContentLabel
1891− // Announce new-content counts as they change so a
1892− // TalkBack user hears "5 new messages" without having
1893− // to focus the FAB. Polite so it doesn't interrupt an
1894− // in-progress utterance (e.g. streaming token reads).
1895− liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite
1899− if (newContentCount > 99) "99+" else newContentCount.toString(),
1900− modifier = Modifier.semantics { invisibleToUser() },
1905− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1907− ExtendedFloatingActionButton(
1909− newContentCount = 0
1910− if (listItems.isNotEmpty()) {
1911− // Scroll to the effective last index, including the
1912− // trailing "__typing" row when a run is active.
1913− val target = if (running) listItems.size else listItems.lastIndex
1914− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1917− // contentDescription null: the visible "Latest" text already labels
1918− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1919− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1920− text = { Text(stringResource(R.string.latest)) },
1924− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1925− // user has scrolled down past the first few messages. Symmetric to the
1926− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1927− val scrolledDown by remember {
1928− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1930− AnimatedVisibility(
1931− visible = scrolledDown && listItems.size > 4,
1932− enter = fabMotion.enter,
1933− exit = fabMotion.exit,
1934− modifier = Modifier.align(Alignment.BottomStart).padding(start = sideMargin),
1936− SmallFloatingActionButton(
1938− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1940− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1943− Icons.Filled.KeyboardArrowUp,
1944− contentDescription = stringResource(R.string.scroll_to_top),
1948− // In-conversation search bar. Overlays the list so typing filters messages in
1949− // place; the match count + a no-matches note give immediate feedback.
1950− val searchMotion = rememberVisibilityTransitions()
1951− AnimatedVisibility(
1952− visible = searchActive,
1953− enter = searchMotion.enter,
1954− exit = searchMotion.exit,
1955− // Inset by sideMargin on wide screens so the search bar spans the capped
1956− // list's width, not the full screen width.
1957− modifier = Modifier.align(Alignment.TopCenter).padding(horizontal = sideMargin),
1960− tonalElevation = 3.dp,
1961− modifier = Modifier
1962− .padding(horizontal = 12.dp, vertical = 4.dp)
1965− // Focus the search field when the bar appears (from the overflow menu's
1966− // "Find in conversation" or Ctrl+F), so the user can start typing
1967− // immediately. Runs after the search field enters the composition.
1968− LaunchedEffect(searchActive) {
1969− if (searchActive) runCatching { searchFocusRequester.requestFocus() }
1972− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1973− verticalAlignment = Alignment.CenterVertically,
1976− value = chatSearch,
1977− onValueChange = { chatSearch = it },
1978− modifier = Modifier.weight(1f).focusRequester(searchFocusRequester),
1979− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1981− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1982− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1984− // Match counter: "N of M" where N is the focused match (1-based) and
1985− // M is the total matching messages. Only shown when there's a query.
1986− val matchCount = searchMessages.size
1988− if (searchQuery.isNotEmpty() && matchCount > 0) {
1989− stringResource(R.string.search_match_count, searchPos + 1, matchCount)
1990− } else if (searchQuery.isNotEmpty()) {
1991− stringResource(R.string.search_no_matches)
1993− style = MaterialTheme.typography.labelSmall,
1994− color = MaterialTheme.colorScheme.onSurfaceVariant,
1995− modifier = Modifier
1996− .padding(horizontal = 4.dp)
1997− // Live region so a TalkBack user hears "3 of 12" / "No
1998− // matches" announce as they step through results, not just
1999− // the sighted user seeing the counter update.
2000− .semantics { liveRegion = androidx.compose.ui.semantics.LiveRegionMode.Polite },
2002− // Step through matches (Previous / Next), disabled when there are
2003− // fewer than two to navigate. Wrap around at the ends so repeated
2004− // taps cycle through every hit.
2005− val prevLabel = stringResource(R.string.find_previous)
2006− val nextLabel = stringResource(R.string.find_next)
2009− if (matchCount > 0) {
2010− searchPos = (searchPos - 1 + matchCount) % matchCount
2013− enabled = matchCount > 1,
2015− Icon(Icons.Filled.KeyboardArrowUp, contentDescription = prevLabel)
2019− if (matchCount > 0) {
2020− searchPos = (searchPos + 1) % matchCount
2023− enabled = matchCount > 1,
2025− Icon(Icons.Filled.KeyboardArrowDown, contentDescription = nextLabel)
2027− IconButton(onClick = {
2028− searchActive = false
2031− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
2036− // When a search yields no matches (but the conversation isn't empty), say so
2037− // instead of showing a blank list.
2038− val noMatches = searchActive && searchQuery.isNotEmpty() &&
2039− !searchFiltering && searchMessages.isEmpty() && messages.isNotEmpty()
2042− stringResource(R.string.search_no_matches),
2043− style = MaterialTheme.typography.bodyMedium,
2044− color = MaterialTheme.colorScheme.onSurfaceVariant,
2045− modifier = Modifier.align(Alignment.Center),
2053− if (showExitConfirm) {
2055− onDismissRequest = { showExitConfirm = false },
2056− title = { Text(stringResource(R.string.stop_and_exit_title)) },
2057− text = { Text(stringResource(R.string.stop_and_exit_text)) },
2059− TextButton(onClick = {
2060− showExitConfirm = false
2061− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2064− }) { Text(stringResource(R.string.stop_and_exit)) }
2067− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
2072− if (showSummarizeConfirm) {
2074− onDismissRequest = { showSummarizeConfirm = false },
2075− title = { Text(stringResource(R.string.summarize_confirm_title)) },
2076− text = { Text(stringResource(R.string.summarize_confirm_text)) },
2078− TextButton(onClick = {
2079− showSummarizeConfirm = false
2081− }) { Text(stringResource(R.string.action_continue)) }
2084− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
2089− if (showInitConfirm) {
2091− onDismissRequest = { showInitConfirm = false },
2092− title = { Text(stringResource(R.string.init_confirm_title)) },
2093− text = { Text(stringResource(R.string.init_confirm_text)) },
2095− TextButton(onClick = {
2096− showInitConfirm = false
2098− }) { Text(stringResource(R.string.action_continue)) }
2101− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
2106− if (showRenameDialog) {
2107− RenameSessionChatDialog(
2108− initialTitle = sessionTitle ?: "",
2109− onDismiss = { showRenameDialog = false },
2110− onConfirm = { newName ->
2111− showRenameDialog = false
2112− vm.renameSession(newName)
2117− if (showDeleteDialog) {
2119− onDismissRequest = { showDeleteDialog = false },
2120− title = { Text(stringResource(R.string.delete_session_chat_title)) },
2121− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
2123− TextButton(onClick = {
2124− showDeleteDialog = false
2125− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
2127− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
2130− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
2135− if (showShellDialog) {
2136− ShellCommandDialog(
2137− onDismiss = { showShellDialog = false },
2139− showShellDialog = false
2145− if (showModelPicker) {
2146− // Resolve persisted recent composite keys to the live ModelOption entries they refer
2147− // to, dropping any whose model is no longer offered by the server. Ordered by
2148− // recency (head of the store first).
2149− val recentOptions = remember(models, recentModelEntries) {
2150− val byKey = models.associateBy { it.providerID to it.modelID }
2151− recentModelEntries.mapNotNull { entry ->
2152− container.recentModelsStore.split(entry)?.let { (p, m) -> byKey[p to m] }
2155− // Resolve snackbar strings in the composable scope; the onSetPreferredModel lambda
2156− // below isn't @Composable, so stringResource can't be called inside it.
2157− val defaultModelClearedMsg = stringResource(R.string.default_model_cleared)
2158− val defaultModelSetFmt = stringResource(R.string.default_model_set, "%s")
2161− selected = selectedModel,
2162− loading = modelsLoading,
2163− error = modelsError,
2166− container.recentModelsStore.add(it.providerID, it.modelID)
2168− onRetry = { vm.reloadModels() },
2169− onDismiss = { showModelPicker = false },
2170− preferredModelId = preferredModelId,
2171− onSetPreferredModel = { id ->
2173− runCatchingCancellable { container.settingsStore.setPreferredModelId(id) }
2174− // Confirm the change with a snackbar so the user sees it took effect —
2175− // the toggle's label flip can be missed, especially when clearing.
2176− val msg = if (id.isEmpty()) {
2177− defaultModelClearedMsg
2179− val label = models.firstOrNull { it.modelID == id }?.modelLabel ?: id
2180− defaultModelSetFmt.format(label)
2182− snackbar.showSnackbar(msg)
2185− recent = recentOptions,
2189− if (showAgentPicker) {
2192− selected = selectedAgent,
2193− loading = agentsLoading,
2194− error = agentsError,
2195− onSelect = { vm.selectAgent(it?.name) },
2196− onRetry = { vm.reloadAgents() },
2197− onDismiss = { showAgentPicker = false },
2201− if (showCommandPicker) {
2202− CommandPickerSheet(
2203− commands = commands,
2204− loading = commandsLoading,
2205− error = commandsError,
2206− onSelect = { vm.runCommand(it) },
2207− onRetry = { vm.reloadCommands() },
2208− onDismiss = { showCommandPicker = false },
2212− pendingPermission?.let { permission ->
2214− permission = permission,
2215− position = permissionProgress.position,
2216− total = permissionProgress.total,
2217− onRespond = { response -> vm.respondPermission(permission, response) },
2218− // On auto-reject timeout, post a notification so a returning user finds a
2219− // persistent record of why the run stopped (the dialog itself is gone).
2220− // Gated by the user's notification setting (notifPermission).
2222− val conn = activeConnection
2223− val ctx = appContext
2224− val title = sessionTitle ?: sessionId
2225− if (notifPermission) {
2226− soy.iko.opencode.notification.SessionNotifications.postPermissionAutoRejected(
2227− ctx, sessionId, title, conn?.profile?.id,
2235− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
2238− if (showShortcutsDialog) {
2239− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
2240− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
2241− // depends on the "Send on Enter" setting, noted inline.
2243− onDismissRequest = { showShortcutsDialog = false },
2244− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
2246− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
2247− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
2248− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
2249− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
2250− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
2251− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
2255− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
2262−private fun ShortcutRow(keys: String, desc: String) {
2263− Row(verticalAlignment = Alignment.CenterVertically) {
2266− style = MaterialTheme.typography.labelLarge,
2267− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2268− modifier = Modifier.widthIn(min = 160.dp),
2272− style = MaterialTheme.typography.bodyMedium,
2273− color = MaterialTheme.colorScheme.onSurfaceVariant,
2279− * Slash-command autocomplete: when the draft starts with "/", show a filtered dropdown
2280− * of matching commands above the composer. Tapping a command fires it immediately.
2281− * Extracted from [ChatInputBar] to keep that function's cyclomatic complexity under
2282− * the detekt threshold. Suppressed while running or when the command catalog is empty.
2285−private fun SlashCommandAutocomplete(
2287− commands: List<Command>,
2289− onRunCommand: (Command) -> Unit,
2291− if (running || commands.isEmpty()) return
2292− val slashQuery = remember(value) {
2293− if (value.startsWith("/")) value.removePrefix("/") else null
2295− val matchingCommands = remember(slashQuery, commands) {
2296− commands.filter { cmd ->
2297− slashQuery.isEmpty() ||
2298− cmd.name.contains(slashQuery, ignoreCase = true) ||
2299− (cmd.description?.contains(slashQuery, ignoreCase = true) == true)
2302− if (matchingCommands.isNotEmpty()) {
2303− CommandAutocompleteDropdown(
2304− commands = matchingCommands,
2305− onPick = onRunCommand,
2311− * Slash-command autocomplete dropdown shown above the composer when the draft starts
2312− * with "/". Renders up to 8 matching commands as a scrollable, elevated surface so the
2313− * user can discover and invoke commands by typing the conventional "/" prefix instead
2314− * of opening the overflow menu / command palette. Tapping a row fires the command.
2317−private fun CommandAutocompleteDropdown(
2318− commands: List<Command>,
2319− onPick: (Command) -> Unit,
2321− val haptics = LocalHapticFeedback.current
2323− color = MaterialTheme.colorScheme.surface,
2324− tonalElevation = 3.dp,
2325− shape = MaterialTheme.shapes.medium,
2326− modifier = Modifier
2328− .padding(horizontal = 8.dp, vertical = 4.dp)
2329− .heightIn(max = 240.dp),
2333− count = commands.size,
2334− key = { commands[it].name },
2336− val cmd = commands[i]
2338− modifier = Modifier
2340− .clickable(role = Role.Button) {
2341− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2344− .padding(horizontal = 16.dp, vertical = 10.dp),
2345− verticalAlignment = Alignment.CenterVertically,
2346− horizontalArrangement = Arrangement.spacedBy(12.dp),
2350− style = MaterialTheme.typography.labelLarge,
2351− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
2352− color = MaterialTheme.colorScheme.primary,
2354− cmd.description?.takeIf { it.isNotBlank() }?.let { desc ->
2357− style = MaterialTheme.typography.bodySmall,
2358− color = MaterialTheme.colorScheme.onSurfaceVariant,
2360− overflow = TextOverflow.Ellipsis,
2369−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
2370−@Suppress("CyclomaticComplexMethod")
2372−private fun ChatInputBar(
2374− onValueChange: (String) -> Unit,
2378− sendOnEnter: Boolean,
2379− onSend: () -> Unit,
2380− onAbort: () -> Unit,
2381− queuedFollowUp: String?,
2382− onQueueFollowUp: (String) -> Unit,
2383− onCancelQueue: () -> Unit,
2384− focusRequester: androidx.compose.ui.focus.FocusRequester,
2385− attachments: List<PendingAttachment>,
2387− stagingFileCount: Int,
2388− onRemoveAttachment: (String) -> Unit,
2389− onPickPhoto: () -> Unit,
2390− onPickFile: () -> Unit,
2391− onCamera: () -> Unit,
2392− onVoice: () -> Unit,
2393− onPasteImage: (List<Uri>) -> Unit,
2394− commands: List<Command> = emptyList(),
2395− onRunCommand: (Command) -> Unit = {},
2397− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
2398− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
2399− val context = LocalContext.current
2400− // Full-screen editor state: opened when the user wants more space for a long prompt.
2401− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
2402− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
2403− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
2404− // A queued follow-up replaces the Stop button with a "queued" chip so the
2405− // user sees their message will be sent when the run finishes, and can cancel.
2406− if (queuedFollowUp != null) {
2407− val editLabel = stringResource(R.string.edit)
2409− modifier = Modifier
2411− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
2412− verticalAlignment = Alignment.CenterVertically,
2414− // Tapping the chip reloads the queued text into the draft (and clears the
2415− // queue) so a typo spotted while queuing can be fixed without retyping.
2417− modifier = Modifier
2419− .clip(MaterialTheme.shapes.small)
2420− .clickable(role = Role.Button, onClickLabel = editLabel) {
2421− onValueChange(queuedFollowUp)
2424− .padding(vertical = 4.dp),
2427− stringResource(R.string.queued),
2428− style = MaterialTheme.typography.labelSmall,
2429− color = MaterialTheme.colorScheme.onSurfaceVariant,
2433− style = MaterialTheme.typography.bodySmall,
2434− color = MaterialTheme.colorScheme.onSurfaceVariant,
2436− overflow = TextOverflow.Ellipsis,
2439− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
2440− Text(stringResource(R.string.cancel))
2444− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
2445− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2446− // Slash-command autocomplete: extracted to a helper to keep this function's
2447− // complexity under the detekt threshold. Returns no-op when the draft doesn't
2448− // start with "/" or the command catalog is empty.
2449− SlashCommandAutocomplete(
2451− commands = commands,
2453− onRunCommand = onRunCommand,
2456− modifier = Modifier.fillMaxWidth().padding(8.dp),
2457− verticalAlignment = Alignment.Bottom,
2459− // Attach menu: photo picker, camera, or any file.
2460− var showAttachMenu by remember { mutableStateOf(false) }
2462− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
2463− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
2465− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
2467− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
2468− text = { Text(stringResource(R.string.attach_photo)) },
2469− onClick = { showAttachMenu = false; onPickPhoto() },
2472− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
2473− text = { Text(stringResource(R.string.attach_camera)) },
2474− onClick = { showAttachMenu = false; onCamera() },
2477− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
2478− text = { Text(stringResource(R.string.attach_file)) },
2479− onClick = { showAttachMenu = false; onPickFile() },
2483− // Voice dictation: appends recognized speech to the draft. Hidden (not just
2484− // disabled) when the device has no speech-recognition activity, so a user
2485− // without a voice app doesn't get a button that only fails noisily on tap.
2486− val voiceAvailable = remember {
2487− val pm = context.packageManager
2488− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
2489− pm.queryIntentActivities(intent, 0).isNotEmpty()
2491− if (voiceAvailable) {
2492− IconButton(onClick = onVoice, enabled = enabled) {
2493− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
2496− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
2497− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
2498− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
2502− onValueChange = { v ->
2503− // Cap input length so a huge paste can't stall the UI. Shares are
2504− // capped separately in MainActivity; this guards typed/pasted drafts.
2505− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
2507− modifier = Modifier
2509− .focusRequester(focusRequester)
2510− .testTag("chat_input")
2511− // Intercept image content pasted/dropped into the field (keyboard paste
2512− // of a copied screenshot, drag from Files, etc.) and route it through the
2513− // same staging path as the attach menu. Non-image content (text) falls
2514− // through unchanged so normal typing/paste works.
2517− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
2518− val clipData = transferable.clipEntry?.clipData
2519− if (clipData != null) {
2520− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
2521− val item = clipData.getItemAt(i)
2522− item.uri?.takeIf { uri ->
2523− item.text == null && uri.toString().let { s ->
2524− s.startsWith("content:") || s.startsWith("file:")
2528− if (imageUris.isNotEmpty()) {
2529− onPasteImage(imageUris)
2536− .onPreviewKeyEvent { event ->
2537− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2538− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
2539− // With it off, Enter inserts a newline and Ctrl+Enter sends.
2540− val send = enterShouldSend(
2542− hasContent = hasContent,
2543− sendOnEnter = sendOnEnter,
2544− shift = event.isShiftPressed,
2545− ctrl = event.isCtrlPressed,
2548− if (running) onQueueFollowUp(value) else onSend()
2554− // While a run is active a typed message only queues (sends after the run), so
2555− // the placeholder says so instead of the plain "Message…".
2557− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
2561− // Show a "N / max" countdown once the draft crosses a high fraction of
2562− // the cap, so the user knows a paste is about to be truncated instead
2563− // of being silently cut off. Hidden for normal short prompts to avoid
2564− // clutter under a typical one-line message.
2566− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
2567− if (value.length >= threshold) {
2570− R.string.draft_chars_remaining,
2571− NetworkConfig.maxDraftLengthChars - value.length,
2572− NetworkConfig.maxDraftLengthChars,
2574− style = MaterialTheme.typography.labelSmall,
2575− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
2576− else MaterialTheme.colorScheme.onSurfaceVariant,
2578− } else if (value.lines().size > 6) {
2579− // The inline field caps at 6 lines; once the draft crosses that,
2580− // hint that a bigger full-screen editor exists (the Expand icon
2581− // above is easy to miss among the icon row). A tappable label
2582− // would be ideal, but a plain hint is enough to draw attention.
2584− stringResource(R.string.open_full_editor_hint),
2585− style = MaterialTheme.typography.labelSmall,
2586− color = MaterialTheme.colorScheme.onSurfaceVariant,
2590− keyboardOptions = KeyboardOptions(
2591− // When "Send on Enter" is on, expose ImeAction.Send so the soft
2592− // keyboard shows a send key — matching the setting's intent and
2593− // giving touch-only users a keyboard send affordance. When off,
2594− // ImeAction.Default keeps the enter/newline key for multi-line input.
2595− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2596− capitalization = KeyboardCapitalization.Sentences,
2598− keyboardActions = KeyboardActions(
2600− // Mirror the hardware-Enter handler: during a run the soft-keyboard
2601− // send key must queue the follow-up, not silently drop it. vm.send()
2602− // returns false while a run is active (beginRun() rejects), so calling
2603− // onSend() directly here would lose the typed message with no feedback
2604− // for touch-only users (no hardware Enter path available).
2605− if (enabled && hasContent) {
2606− if (running) onQueueFollowUp(value) else onSend()
2611− ComposerTrailingButton(
2613− aborting = aborting,
2614− canSend = enabled && hasContent,
2615− canQueue = enabled && value.isNotBlank(),
2618− onQueue = { onQueueFollowUp(value) },
2622− if (showFullScreenEditor) {
2625− onValueChange = onValueChange,
2626− onDismiss = { showFullScreenEditor = false },
2628− showFullScreenEditor = false
2629− // Mirror the inline composer's behavior: while a run is active a send
2630− // can't go immediately, so queue the follow-up instead of silently
2631− // dropping it (vm.send() returns false during a run, which previously
2632− // lost the typed message with no feedback).
2633− if (running) onQueueFollowUp(value) else onSend()
2635− canSend = enabled && hasContent,
2637− sendOnEnter = sendOnEnter,
2638− attachments = attachments,
2639− onRemoveAttachment = onRemoveAttachment,
2641− stagingFileCount = stagingFileCount,
2647−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
2648− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
2649−@OptIn(ExperimentalMaterial3Api::class)
2651−private fun FullScreenEditor(
2653− onValueChange: (String) -> Unit,
2654− onDismiss: () -> Unit,
2655− onSend: () -> Unit,
2657− running: Boolean = false,
2658− sendOnEnter: Boolean = false,
2659− attachments: List<PendingAttachment> = emptyList(),
2660− onRemoveAttachment: (String) -> Unit = {},
2661− staging: Boolean = false,
2662− stagingFileCount: Int = 0,
2664− androidx.compose.ui.window.Dialog(
2665− onDismissRequest = onDismiss,
2666− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
2668− // Cap the editor width on large screens (tablets) so the text field doesn't stretch
2669− // edge-to-edge — matching the chat list's readability rationale. BoxWithConstraints
2670− // gives the available width so we can center a capped-width column.
2671− androidx.compose.foundation.layout.BoxWithConstraints(
2672− modifier = Modifier.fillMaxSize(),
2673− contentAlignment = Alignment.Center,
2675− val hPad = if (maxWidth > NetworkConfig.twoPaneWidthThresholdDp.dp)
2676− ((maxWidth - NetworkConfig.composerDialogMaxWidthDp.dp) / 2).coerceAtLeast(0.dp)
2679− modifier = Modifier.padding(horizontal = hPad),
2681− androidx.compose.material3.TopAppBar(
2682− title = { Text(stringResource(R.string.compose_editor_title)) },
2684− androidx.compose.material3.TextButton(onClick = onDismiss) {
2685− Text(stringResource(R.string.collapse_editor))
2691− Surface(tonalElevation = 3.dp) {
2693− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
2694− horizontalArrangement = Arrangement.End,
2696− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
2697− Text(stringResource(if (running) R.string.queue else R.string.send))
2703− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
2704− // Show staged attachments in the full-screen editor too, so a user who staged
2705− // images then expanded for a long prompt can still see and remove them without
2706− // collapsing first (mirrors the inline composer's AttachmentStrip).
2707− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging, stagingFileCount = stagingFileCount)
2710− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
2711− modifier = Modifier
2714− // Honor the "Send on Enter" setting here too, so the full-screen
2715− // editor matches the inline composer: Enter sends (Shift+Enter
2716− // newlines) when on; Enter inserts a newline and Ctrl+Enter sends
2717− // when off. Previously this hard-coded ImeAction.Default and had no
2718− // key handler, so a hardware-keyboard user got a different behaviour
2719− // from the inline composer depending on which they happened to open.
2720− .onPreviewKeyEvent { event ->
2721− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
2722− val send = enterShouldSend(
2724− hasContent = canSend,
2725− sendOnEnter = sendOnEnter,
2726− shift = event.isShiftPressed,
2727− ctrl = event.isCtrlPressed,
2729− if (send) { onSend(); true } else false
2731− placeholder = { Text(stringResource(R.string.message_placeholder)) },
2732− maxLines = Int.MAX_VALUE,
2733− keyboardOptions = KeyboardOptions(
2734− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
2735− capitalization = KeyboardCapitalization.Sentences,
2737− keyboardActions = KeyboardActions(
2738− onSend = { if (canSend) onSend() },
2747−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
2748− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
2749−private fun enterShouldSend(
2751− hasContent: Boolean,
2752− sendOnEnter: Boolean,
2756− !enabled || !hasContent -> false
2757− sendOnEnter -> !shift
2761−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
2762− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
2763− * [ChatInputBar] stays under the complexity threshold. */
2765−private fun ComposerTrailingButton(
2770− onSend: () -> Unit,
2771− onAbort: () -> Unit,
2772− onQueue: () -> Unit,
2775− Row(verticalAlignment = Alignment.CenterVertically) {
2776− // While a run is active the trailing action is Stop, so the only send affordance is
2777− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
2778− // That leaves a touch-only user with the setting off no way to queue a follow-up
2779− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
2780− // there's typed TEXT so queuing is always reachable, without changing the user's
2781− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
2782− // canSend, which is also true for an attachment-only composer — because queuing "" just
2783− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
2784− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
2788− modifier = Modifier.testTag("queue_button"),
2790− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
2791− // icon (which can be read as "snooze" or "later"), and isn't confused with
2792− // the Send action sitting right beside the Stop button.
2794− Icons.AutoMirrored.Filled.PlaylistAdd,
2795− contentDescription = stringResource(R.string.queue_followup),
2799− // Show a spinner while the abort REST call is in flight so the user sees the stop
2800− // was sent, and disable to prevent a double-tap.
2803− enabled = !aborting,
2804− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
2807− val stopLabel = stringResource(R.string.stop)
2808− CircularProgressIndicator(
2809− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
2810− strokeWidth = 2.dp,
2813− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
2821− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
2823− // Tint the send icon with primary when there's content to send so the commit action
2824− // draws the eye; muted otherwise. A plain enabled/disabled flip is easy to miss.
2826− Icons.AutoMirrored.Filled.Send,
2827− contentDescription = stringResource(R.string.send),
2828− tint = if (canSend) MaterialTheme.colorScheme.primary
2829− else MaterialTheme.colorScheme.onSurfaceVariant,
2835−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
2837−private fun EmptyConversation(
2838− onSuggestion: (String) -> Unit,
2839− modifier: Modifier = Modifier,
2841− // A few example prompts so a first-time user has a one-tap path to their first
2842− // message instead of staring at a blank input. Tapping a chip fills the draft
2843− // (without sending) so the user can edit it before sending.
2844− val suggestions = remember {
2846− R.string.empty_chat_suggest_1,
2847− R.string.empty_chat_suggest_2,
2848− R.string.empty_chat_suggest_3,
2852− modifier = modifier.padding(32.dp),
2853− horizontalAlignment = Alignment.CenterHorizontally,
2856− Icons.Filled.AutoAwesome,
2857− contentDescription = null,
2858− modifier = Modifier.size(48.dp),
2859− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2861− Spacer(Modifier.size(16.dp))
2863− stringResource(R.string.empty_chat_title),
2864− style = MaterialTheme.typography.titleMedium,
2866− Spacer(Modifier.size(8.dp))
2868− stringResource(R.string.empty_chat_hint),
2869− style = MaterialTheme.typography.bodyMedium,
2870− color = MaterialTheme.colorScheme.onSurfaceVariant,
2872− Spacer(Modifier.size(20.dp))
2873− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2874− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2876− modifier = Modifier.fillMaxWidth(),
2877− horizontalArrangement = Arrangement.spacedBy(8.dp),
2878− verticalArrangement = Arrangement.spacedBy(8.dp),
2880− suggestions.forEach { resId ->
2881− val text = stringResource(resId)
2882− androidx.compose.material3.AssistChip(
2883− onClick = { onSuggestion(text) },
2884− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2891−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). When the
2892− * server included a diff of the revert, a collapsible "Show what changed" affordance reveals
2893− * it inline via [DiffView] so the user can see what was rolled back before deciding to undo. */
2895−private fun RevertBanner(diff: String?, isEditing: Boolean, onUndo: () -> Unit) {
2896− val haptics = LocalHapticFeedback.current
2897− var showDiff by rememberSaveable { mutableStateOf(false) }
2898− val expandMotion = rememberVisibilityTransitions()
2900− color = MaterialTheme.colorScheme.tertiaryContainer,
2901− tonalElevation = 2.dp,
2902− modifier = Modifier.fillMaxWidth(),
2906− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2907− verticalAlignment = Alignment.CenterVertically,
2908− horizontalArrangement = Arrangement.SpaceBetween,
2910− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2912− if (isEditing) Icons.Filled.Edit else Icons.Filled.Restore,
2913− contentDescription = null,
2914− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2915− modifier = Modifier.size(18.dp),
2918− stringResource(if (isEditing) R.string.editing_banner else R.string.reverted_banner),
2919− style = MaterialTheme.typography.bodySmall,
2920− color = MaterialTheme.colorScheme.onTertiaryContainer,
2921− modifier = Modifier.padding(start = 8.dp),
2923− // "Show what changed" toggle, shown only when the server provided a diff.
2924− // Collapsible so the banner stays compact by default; a user curious about
2925− // what the revert rolled back can expand it inline without leaving the chat.
2926− if (!diff.isNullOrBlank()) {
2929− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2930− showDiff = !showDiff
2932− contentPadding = androidx.compose.foundation.layout.PaddingValues(start = 8.dp, end = 4.dp),
2935− if (showDiff) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
2936− contentDescription = null,
2937− modifier = Modifier.size(16.dp),
2940− stringResource(if (showDiff) R.string.revert_hide_diff else R.string.revert_show_diff),
2941− style = MaterialTheme.typography.labelSmall,
2942− modifier = Modifier.padding(start = 4.dp),
2947− TextButton(onClick = {
2948− // Haptic on undo to match the other destructive/important confirmations: a
2949− // revert restores potentially hundreds of hidden messages.
2950− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
2952− }) { Text(stringResource(R.string.undo)) }
2954− // The diff render lives inside the banner's Surface so it inherits the tertiary
2955− // tonal container and reads as part of the banner, not a floating panel.
2956− if (!diff.isNullOrBlank()) {
2957− AnimatedVisibility(
2958− visible = showDiff,
2959− enter = expandMotion.enter,
2960− exit = expandMotion.exit,
2962− Column(modifier = Modifier.padding(start = 12.dp, end = 12.dp, bottom = 8.dp)) {
2964− stringResource(R.string.revert_diff_header),
2965− style = MaterialTheme.typography.labelSmall,
2966− color = MaterialTheme.colorScheme.onTertiaryContainer,
2967− modifier = Modifier.padding(bottom = 4.dp),
2969− DiffView(diff, saveKey = "revertDiff")
2977−/** A dismissible preview card shown above the composer when the user quote-replied to a
2978− * message. Displays the quoted text (truncated) with a Cancel affordance so the user can
2979− * abort the quote without digging into the draft to strip the `>`-prefixed lines. Mirrors
2980− * the Discord/Slack quote-preview pattern. */
2982−private fun QuoteReplyBanner(quotedText: String, onCancel: () -> Unit) {
2983− val haptics = LocalHapticFeedback.current
2985− color = MaterialTheme.colorScheme.secondaryContainer,
2986− tonalElevation = 2.dp,
2987− modifier = Modifier.fillMaxWidth(),
2990− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
2991− verticalAlignment = Alignment.Top,
2994− Icons.Filled.FormatQuote,
2995− contentDescription = null,
2996− tint = MaterialTheme.colorScheme.onSecondaryContainer,
2997− modifier = Modifier.size(18.dp).padding(top = 2.dp),
2999− Column(modifier = Modifier.weight(1f).padding(start = 8.dp)) {
3001− stringResource(R.string.quote_reply_banner),
3002− style = MaterialTheme.typography.labelSmall,
3003− color = MaterialTheme.colorScheme.onSecondaryContainer,
3007− style = MaterialTheme.typography.bodySmall,
3008− color = MaterialTheme.colorScheme.onSecondaryContainer,
3010− overflow = TextOverflow.Ellipsis,
3013− IconButton(onClick = {
3014− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
3018− Icons.Filled.Close,
3019− contentDescription = stringResource(R.string.cancel_quote_reply),
3020− tint = MaterialTheme.colorScheme.onSecondaryContainer,
3021− modifier = Modifier.size(18.dp),
3028−/** A banner shown while messages composed offline are queued in the outbox, with a
3029− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
3031−private fun OutboxBanner(
3034− onFlush: () -> Unit,
3035− onDiscard: () -> Unit,
3037− var showDiscardConfirm by rememberSaveable { mutableStateOf(false) }
3039− color = MaterialTheme.colorScheme.secondaryContainer,
3040− tonalElevation = 2.dp,
3041− modifier = Modifier.fillMaxWidth(),
3044− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
3045− verticalAlignment = Alignment.CenterVertically,
3046− horizontalArrangement = Arrangement.SpaceBetween,
3048− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
3050− CircularProgressIndicator(
3051− Modifier.size(16.dp),
3052− strokeWidth = 2.dp,
3053− color = MaterialTheme.colorScheme.onSecondaryContainer,
3055− Spacer(Modifier.size(8.dp))
3059− stringResource(R.string.outbox_sending)
3061− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
3062− stringResource(res, count)
3064− style = MaterialTheme.typography.bodySmall,
3065− color = MaterialTheme.colorScheme.onSecondaryContainer,
3069− val haptics = LocalHapticFeedback.current
3070− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
3071− TextButton(onClick = {
3072− // Confirm before discarding all queued messages (irreversible), matching
3073− // the confirmation pattern used by deleteSession and other destructive
3074− // actions. Previously a single tap dropped every queued message.
3075− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
3076− showDiscardConfirm = true
3078− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
3083− if (showDiscardConfirm) {
3084− androidx.compose.material3.AlertDialog(
3085− onDismissRequest = { showDiscardConfirm = false },
3086− title = { Text(stringResource(R.string.discard_queued_title)) },
3087− text = { Text(stringResource(R.string.discard_queued_text, count)) },
3089− androidx.compose.material3.TextButton(onClick = {
3090− showDiscardConfirm = false
3092− }) { Text(stringResource(R.string.discard)) }
3095− androidx.compose.material3.TextButton(onClick = { showDiscardConfirm = false }) {
3096− Text(stringResource(R.string.cancel))
3103−/** Prompt for a one-off shell command to run in the session's worktree. */
3105−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
3106− var command by rememberSaveable { mutableStateOf("") }
3108− onDismissRequest = onDismiss,
3109− title = { Text(stringResource(R.string.run_shell_command)) },
3113− onValueChange = { command = it },
3114− modifier = Modifier.fillMaxWidth(),
3115− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
3116− label = { Text(stringResource(R.string.shell_command_label)) },
3118− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3119− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
3124− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
3125− enabled = command.isNotBlank(),
3126− ) { Text(stringResource(R.string.run)) }
3128− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
3133− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
3134− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
3135− * equality is structural so `snapshotFlow` emits only when something relevant changes.
3137−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
3139−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
3140− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
3141− * streaming, not just plain assistant text. O(1). */
3142−private fun streamingContentLength(part: Part?): Int = when (part) {
3143− is TextPart -> part.text.length
3144− is ReasoningPart -> part.text.length
3145− is ToolPart -> when (val st = part.state) {
3146− is ToolCompleted -> st.output?.length ?: 0
3147− is ToolError -> st.error?.length ?: 0
3148− is ToolRunning -> st.title?.length ?: 0
3154−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
3155− * dialog but lives in the chat screen so the user can rename without backing out to
3156− * the list. Pre-filled with the current title; the cap matches the list dialog. */
3158−private fun RenameSessionChatDialog(
3159− initialTitle: String,
3160− onDismiss: () -> Unit,
3161− onConfirm: (String) -> Unit,
3163− // Seed the field once (no key input) so a later external title change — e.g. opencode
3164− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
3165− // doesn't re-initialize the box and discard the user's in-progress edit.
3166− var title by rememberSaveable { mutableStateOf(initialTitle) }
3168− onDismissRequest = onDismiss,
3169− title = { Text(stringResource(R.string.rename_session_chat)) },
3173− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
3174− modifier = Modifier.fillMaxWidth(),
3175− placeholder = { Text(stringResource(R.string.session_title_hint)) },
3176− label = { Text(stringResource(R.string.rename_session_chat)) },
3178− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
3179− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
3183− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
3184− Text(stringResource(R.string.save))
3188− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
3194− * A single item in the chat message list — either a [Message] bubble or a day
3195− * [Separator] inserted before the first message of a new day. The separator shifts
3196− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
3197− * the [List] of these items (not `messages.size`/`lastIndex`).
3199−private sealed interface MessageListItem {
3201− val contentType: Any
3203− data class Message(
3204− val message: MessageWithParts,
3205− override val key: Any,
3206− // Whether this is the first message in a consecutive run of the same speaker (role).
3207− // Used to suppress the assistant avatar/header on follow-up messages in the same run,
3208− // reducing visual noise in tool-heavy conversations where many assistant messages
3209− // appear back-to-back. A separator or a role change resets the flag.
3210− val isFirstOfSpeaker: Boolean,
3211− ) : MessageListItem {
3212− override val contentType: Any get() = message.info::class
3215− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
3216− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
3217− // can share a label (e.g. an untimestamped message — empty label — between two
3218− // same-day messages, or two untimestamped groups), and a label-only key would
3219− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
3220− // stable for a given message ordering so slots aren't needlessly recreated.
3221− override val key: Any get() = "sep_${ordinal}_$label"
3222− // Separators share a contentType so the LazyColumn can recycle their slots.
3223− override val contentType: Any get() = "separator"
3228− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
3229− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
3230− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
3231− * Messages with no timestamp are grouped under an empty-label separator only if they
3232− * start the list, so a server that omits timestamps doesn't suppress the first divider.
3234− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
3235− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
3236− * labels; older days fall back to a locale-stable medium-date format.
3238−private fun buildMessageListItems(
3239− messages: List<MessageWithParts>,
3240− todayLabel: String,
3241− yesterdayLabel: String,
3242−): List<MessageListItem> {
3243− if (messages.isEmpty()) return emptyList()
3244− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
3245− val dateFmt = mediumDateFormat()
3246− val result = ArrayList<MessageListItem>(messages.size + 4)
3247− val seenKeys = HashSet<String>(messages.size * 2)
3248− var lastDayKey: String? = null
3250− var emptyIdOrdinal = 0
3252− // Track the previous message's role to detect consecutive same-speaker runs, so the
3253− // avatar/header can be suppressed on follow-up messages in the same run. A null means
3254− // "no previous message or a separator just interrupted the run", both of which make the
3255− // next message the first of its group.
3256− var prevRoleClass: kotlin.reflect.KClass<out soy.iko.opencode.data.model.MessageInfo>? = null
3257− for (message in messages) {
3258− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
3259− val dayKey = ts?.let { dayKey(it) } ?: ""
3260− // Emit a separator before the very first message (so a leading un-timestamped message
3261− // still gets the first divider, empty label and all), and thereafter only when crossing
3262− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
3263− // neither emits its own separator nor resets the day — otherwise a following same-day
3264− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
3265− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
3266− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
3267− // A date separator visually breaks a speaker run, so the next message is treated
3268− // as the first of its group (even if the same role continues across the day break).
3269− prevRoleClass = null
3271− if (dayKey.isNotEmpty()) lastDayKey = dayKey
3273− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
3274− // empty id — and the reducer intentionally keeps several such messages as distinct
3275− // holders — so give each a stable synthetic key and defensively de-collide any remaining
3276− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
3277− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
3278− if (!seenKeys.add(key)) {
3280− while (!seenKeys.add("$key#$suffix")) suffix++
3281− key = "$key#$suffix"
3283− val roleClass = message.info::class
3284− val isFirstOfSpeaker = prevRoleClass == null || roleClass != prevRoleClass
3285− result.add(MessageListItem.Message(message, key, isFirstOfSpeaker))
3286− prevRoleClass = roleClass
3292− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
3294− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
3295− * whole `messages` list, which must stay so the live message's fresh parts render), so a
3296− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
3297− * every message on every token. Message timestamps are immutable once assigned, so we
3298− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
3299− * a cheap hash lookup. Bounded; only touched on the main thread during composition.
3301− * Backed by a [ConcurrentHashMap] (not an access-ordered LinkedHashMap): the previous
3302− * synchronized access-ordered LinkedHashMap reordered its linked list node on every
3303− * `getOrPut` hit, which is real work multiplied by N messages × ~20 snapshots/sec during
3304− * streaming. A ConcurrentHashMap has no access-order bookkeeping and is lock-free for
3305− * reads, so the common case (a hit) is a single volatile read + hash probe.
3306− * [removeEldestEntry] is not available on ConcurrentHashMap, so the bound is enforced via
3307− * a size check in [dayKey]: once the cap ([DAY_KEY_CACHE_MAX]) is reached the cache is
3308− * cleared; in practice the cache size is bounded by the number of distinct message
3309− * timestamps in a session (≤ [NetworkConfig.maxInMemoryMessages]) and the cap is a
3310− * safety valve for the process-lifetime cache across many sessions.
3312−private val dayKeyCache = java.util.concurrent.ConcurrentHashMap<Long, String>(256)
3314−/** Upper bound on [dayKeyCache] entries. Message timestamps are immutable once assigned, so
3315− * the natural bound is the number of distinct timestamps in a session (≤
3316− * [NetworkConfig.maxInMemoryMessages]); this cap is a safety valve for the process-lifetime
3317− * cache across many sessions, keeping a runaway leak from accumulating unbounded memory. */
3318−private const val DAY_KEY_CACHE_MAX = 1024
3320−private fun dayKey(epochMillis: Long): String {
3321− val cached = dayKeyCache[epochMillis]
3322− if (cached != null) return cached
3323− val value = java.time.Instant.ofEpochMilli(epochMillis)
3324− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
3325− // Guard the size under the cache's concurrency: only the first thread to see the cap
3326− // exceeded evicts (draining is O(N) but rare and idempotent), so concurrent inserts
3327− // past the cap don't each pay the scan. computeIfAbsent would hold the segment lock
3328− // during the (cheap) date computation but can't express the size guard, so use put
3329− // after the fact; a duplicate put of the same key/value is harmless.
3330− if (dayKeyCache.size >= DAY_KEY_CACHE_MAX) dayKeyCache.clear()
3331− dayKeyCache[epochMillis] = value
3335−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
3336−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
3337−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
3338−private var cachedDateFmt: java.text.DateFormat? = null
3339−private var cachedDateFmtLocale: java.util.Locale? = null
3341−private fun mediumDateFormat(): java.text.DateFormat {
3342− val locale = java.util.Locale.getDefault()
3343− val existing = cachedDateFmt
3344− if (existing != null && cachedDateFmtLocale == locale) return existing
3345− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
3347− cachedDateFmtLocale = locale
3352− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
3353− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
3354− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
3357−private fun dayLabel(
3360− today: java.time.LocalDate,
3361− todayLabel: String,
3362− yesterdayLabel: String,
3363− dateFmt: java.text.DateFormat,
3365− if (dayKey.isEmpty()) return ""
3366− val epochDay = dayKey.toLongOrNull() ?: return ""
3367− val date = java.time.LocalDate.ofEpochDay(epochDay)
3369− date == today -> todayLabel
3370− date == today.minusDays(1) -> yesterdayLabel
3371− else -> dateFmt.format(java.util.Date(ts))
3376− * A centered day divider in the message list. Renders nothing for an empty label
3377− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
3380−private fun DateSeparator(label: String) {
3381− if (label.isBlank()) return
3383− modifier = Modifier.fillMaxWidth(),
3384− horizontalArrangement = Arrangement.Center,
3387− color = MaterialTheme.colorScheme.surfaceVariant,
3388− shape = MaterialTheme.shapes.small,
3389− // Marked as a heading so TalkBack users can navigate day-by-day with the
3390− // heading-skip gesture — the canonical affordance for date dividers in a list.
3391− modifier = Modifier.semantics(mergeDescendants = true) { heading() },
3395− style = MaterialTheme.typography.labelSmall,
3396− color = MaterialTheme.colorScheme.onSurfaceVariant,
3397− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
3403−/** Skeleton placeholder bubbles for the chat loading and run-started states. Alpha pulses
3404− * (gated by reduced-motion) to convey ongoing work; the column carries the a11y label so
3405− * TalkBack announces "Loading" instead of reading the skeleton bars. Rendered as a
3406− * [BoxScope] extension so it can align itself to the top center of its host box. */
3408−private fun androidx.compose.foundation.layout.BoxScope.ChatSkeleton(topPad: androidx.compose.ui.unit.Dp) {
3409− val loadingLabel = stringResource(R.string.loading)
3410− val reducedMotion = LocalReducedMotion.current
3411− val transition = rememberInfiniteTransition(label = "skeleton")
3412− val pulse by transition.animateFloat(
3413− initialValue = 0.35f,
3414− targetValue = 0.7f,
3415− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
3416− label = "skeletonAlpha",
3418− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
3419− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
3421− fun bar(widthFraction: Float) {
3424− .fillMaxWidth(widthFraction)
3426− .clip(RoundedCornerShape(4.dp))
3427− .background(skeletonColor)
3428− .alpha(skeletonAlpha),
3432− modifier = Modifier
3433− .align(Alignment.TopCenter)
3434− .padding(top = topPad)
3437− .semantics { contentDescription = loadingLabel },
3438− verticalArrangement = Arrangement.spacedBy(14.dp),
3441− val left = i % 2 == 0
3443− modifier = Modifier.fillMaxWidth(),
3444− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
3447− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
3448− verticalArrangement = Arrangement.spacedBy(6.dp),