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