@@ -1,2389 +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.height
33−import androidx.compose.foundation.layout.imePadding
34−import androidx.compose.foundation.layout.navigationBars
35−import androidx.compose.foundation.layout.padding
36−import androidx.compose.foundation.layout.size
37−import androidx.compose.foundation.layout.union
38−import androidx.compose.foundation.layout.widthIn
39−import androidx.compose.foundation.layout.windowInsetsPadding
40−import androidx.compose.foundation.layout.wrapContentWidth
41−import androidx.compose.foundation.lazy.LazyColumn
42−import androidx.compose.foundation.lazy.items
43−import androidx.compose.foundation.lazy.rememberLazyListState
44−import androidx.compose.foundation.shape.RoundedCornerShape
45−import androidx.compose.material.icons.Icons
46−import androidx.compose.material.icons.automirrored.filled.ArrowBack
47−import androidx.compose.material.icons.automirrored.filled.Send
48−import androidx.compose.material.icons.filled.Add
49−import androidx.compose.material.icons.filled.AutoAwesome
50−import androidx.compose.material.icons.filled.Delete
51−import androidx.compose.material.icons.filled.Description
52−import androidx.compose.material.icons.filled.Close
53−import androidx.compose.material.icons.filled.Edit
54−import androidx.compose.material.icons.filled.Expand
55−import androidx.compose.material.icons.filled.Search
56−import androidx.compose.material.icons.filled.KeyboardArrowDown
57−import androidx.compose.material.icons.filled.KeyboardArrowUp
58−import androidx.compose.material.icons.filled.Mic
59−import androidx.compose.material.icons.filled.MoreVert
60−import androidx.compose.material.icons.filled.PhotoCamera
61−import androidx.compose.material.icons.filled.PhotoLibrary
62−import androidx.compose.material.icons.filled.Refresh
63−import androidx.compose.material.icons.filled.Restore
64−import androidx.compose.material.icons.automirrored.filled.PlaylistAdd
65−import androidx.compose.material.icons.automirrored.filled.Reply
66−import androidx.compose.material.icons.filled.Schedule
67−import androidx.compose.material.icons.filled.Stop
68−import androidx.compose.material3.AlertDialog
69−import androidx.compose.material3.Badge
70−import androidx.compose.material3.BadgedBox
71−import androidx.compose.material3.Button
72−import androidx.compose.material3.CircularProgressIndicator
73−import androidx.compose.material3.SmallFloatingActionButton
74−import androidx.compose.material3.DropdownMenu
75−import androidx.compose.material3.DropdownMenuItem
76−import androidx.compose.material3.ExperimentalMaterial3Api
77−import androidx.compose.material3.ExtendedFloatingActionButton
78−import androidx.compose.material3.FloatingActionButton
79−import androidx.compose.material3.Icon
80−import androidx.compose.material3.IconButton
81−import androidx.compose.material3.MaterialTheme
82−import androidx.compose.material3.OutlinedTextField
83−import androidx.compose.material3.Scaffold
84−import androidx.compose.material3.SnackbarDuration
85−import androidx.compose.material3.SwipeToDismissBox
86−import androidx.compose.material3.SwipeToDismissBoxValue
87−import androidx.compose.material3.rememberSwipeToDismissBoxState
88−import androidx.compose.material3.SnackbarHost
89−import androidx.compose.material3.SnackbarHostState
90−import androidx.compose.material3.SnackbarResult
91−import androidx.compose.material3.Surface
92−import androidx.compose.material3.Text
93−import androidx.compose.material3.TextButton
94−import androidx.compose.material3.TopAppBar
95−import androidx.compose.material3.pulltorefresh.PullToRefreshBox
96−import androidx.compose.runtime.Composable
97−import androidx.compose.runtime.CompositionLocalProvider
98−import androidx.compose.runtime.DisposableEffect
99−import androidx.compose.runtime.LaunchedEffect
100−import androidx.compose.runtime.derivedStateOf
101−import androidx.compose.runtime.getValue
102−import androidx.compose.runtime.mutableIntStateOf
103−import androidx.compose.runtime.mutableLongStateOf
104−import androidx.compose.runtime.mutableStateOf
105−import androidx.compose.runtime.produceState
106−import androidx.compose.runtime.remember
107−import androidx.compose.runtime.rememberCoroutineScope
108−import androidx.compose.runtime.rememberUpdatedState
109−import androidx.compose.runtime.saveable.rememberSaveable
110−import androidx.compose.runtime.setValue
111−import androidx.compose.runtime.snapshotFlow
112−import androidx.compose.foundation.text.KeyboardActions
113−import androidx.compose.foundation.text.KeyboardOptions
114−import androidx.compose.ui.text.input.KeyboardCapitalization
115−import androidx.compose.ui.Alignment
116−import androidx.compose.ui.Modifier
117−import androidx.compose.ui.draw.alpha
118−import androidx.compose.ui.draw.clip
119−import androidx.compose.ui.focus.focusRequester
120−import androidx.compose.ui.input.key.Key
121−import androidx.compose.ui.input.key.KeyEventType
122−import androidx.compose.ui.input.key.isCtrlPressed
123−import androidx.compose.ui.input.key.isShiftPressed
124−import androidx.compose.ui.input.key.key
125−import androidx.compose.ui.input.key.onPreviewKeyEvent
126−import androidx.compose.ui.input.key.type
127−import androidx.compose.ui.layout.onSizeChanged
128−import androidx.compose.ui.platform.LocalContext
129−import androidx.compose.ui.platform.LocalDensity
130−import androidx.compose.ui.platform.LocalHapticFeedback
131−import androidx.compose.ui.platform.LocalView
132−import androidx.compose.ui.platform.testTag
133−import androidx.compose.ui.res.stringResource
134−import androidx.compose.ui.semantics.Role
135−import androidx.compose.ui.semantics.contentDescription
136−import androidx.compose.ui.semantics.semantics
137−import androidx.compose.ui.text.input.ImeAction
138−import androidx.compose.ui.text.style.TextOverflow
139−import androidx.compose.ui.unit.dp
140−import androidx.lifecycle.compose.collectAsStateWithLifecycle
141−import androidx.lifecycle.viewmodel.compose.viewModel
142−import kotlinx.coroutines.Dispatchers
143−import kotlinx.coroutines.coroutineScope
144−import kotlinx.coroutines.delay
145−import kotlinx.coroutines.flow.distinctUntilChanged
146−import kotlinx.coroutines.launch
147−import kotlinx.coroutines.withContext
148−import soy.iko.opencode.data.model.Part
149−import soy.iko.opencode.data.model.MessageWithParts
150−import soy.iko.opencode.data.model.ReasoningPart
151−import soy.iko.opencode.data.model.TextPart
152−import soy.iko.opencode.data.model.ToolCompleted
153−import soy.iko.opencode.data.model.ToolError
154−import soy.iko.opencode.data.model.ToolPart
155−import soy.iko.opencode.data.model.ToolRunning
156−import soy.iko.opencode.data.network.EventStreamClient
157−import soy.iko.opencode.data.network.NetworkConfig
158−import soy.iko.opencode.di.AppContainer
159−import soy.iko.opencode.R
160−import soy.iko.opencode.ui.components.CommandPalette
161−import soy.iko.opencode.ui.components.ConnectionBanner
162−import soy.iko.opencode.ui.components.PaletteAction
163−import soy.iko.opencode.ui.components.LocalReducedMotion
164−import soy.iko.opencode.ui.components.copyToClipboard
165−import soy.iko.opencode.ui.components.LocalRelativeTimeTick
166−import soy.iko.opencode.ui.components.rememberRelativeTimeTick
167−import soy.iko.opencode.ui.components.rememberVisibilityTransitions
168−import soy.iko.opencode.ui.components.showToast
169−import soy.iko.opencode.ui.components.toImageContext
170−import soy.iko.opencode.ui.vmFactory
171−import soy.iko.opencode.util.runCatchingCancellable
172−
173−@OptIn(ExperimentalMaterial3Api::class)
174−@Composable
175−fun ChatScreen(
176− container: AppContainer,
177− sessionId: String,
178− onBack: () -> Unit,
179− onOpenFile: ((String) -> Unit)? = null,
180− onOpenSession: ((String) -> Unit)? = null,
181−) {
182− val vm: ChatViewModel = viewModel(key = sessionId, factory = vmFactory { ChatViewModel(container, sessionId) })
183− val hasMessages by vm.hasMessages.collectAsStateWithLifecycle()
184− val running by vm.running.collectAsStateWithLifecycle()
185− val aborting by vm.aborting.collectAsStateWithLifecycle()
186− val loading by vm.loading.collectAsStateWithLifecycle()
187− val loadError by vm.loadError.collectAsStateWithLifecycle()
188− val refreshing by vm.refreshing.collectAsStateWithLifecycle()
189− val models by vm.models.collectAsStateWithLifecycle()
190− val modelsLoading by vm.modelsLoading.collectAsStateWithLifecycle()
191− val modelsError by vm.modelsError.collectAsStateWithLifecycle()
192− val selectedModel by vm.selectedModel.collectAsStateWithLifecycle()
193− val connectionState by vm.connectionState.collectAsStateWithLifecycle()
194− val pendingPermission by vm.pendingPermission.collectAsStateWithLifecycle()
195− val permissionProgress by vm.permissionProgress.collectAsStateWithLifecycle()
196− val agents by vm.agents.collectAsStateWithLifecycle()
197− val agentsLoading by vm.agentsLoading.collectAsStateWithLifecycle()
198− val agentsError by vm.agentsError.collectAsStateWithLifecycle()
199− val selectedAgent by vm.selectedAgent.collectAsStateWithLifecycle()
200− val commands by vm.commands.collectAsStateWithLifecycle()
201− val commandsLoading by vm.commandsLoading.collectAsStateWithLifecycle()
202− val commandsError by vm.commandsError.collectAsStateWithLifecycle()
203− val sessionTitle by vm.sessionTitle.collectAsStateWithLifecycle()
204− val sessionDeleted by vm.sessionDeleted.collectAsStateWithLifecycle()
205− val draft by vm.draft.collectAsStateWithLifecycle()
206− val attachments by vm.attachments.collectAsStateWithLifecycle()
207− val reverted by vm.reverted.collectAsStateWithLifecycle()
208− val shareUrl by vm.shareUrl.collectAsStateWithLifecycle()
209− val reconnecting by vm.reconnecting.collectAsStateWithLifecycle()
210− val sendOnEnter by container.settingsStore.sendOnEnter.collectAsStateWithLifecycle(initialValue = true)
211− val isOnline by container.isOnline.collectAsStateWithLifecycle()
212− val haptics = LocalHapticFeedback.current
213− val scope = rememberCoroutineScope()
214− val shareContext = LocalContext.current
215− val defaultShareSubject = stringResource(R.string.share_subject)
216− val sessionLabel = stringResource(R.string.session)
217− val defaultModelLabel = stringResource(R.string.default_model)
218− val subtitle = remember(selectedModel?.modelLabel, selectedAgent, defaultModelLabel) {
219− buildString {
220− append(selectedModel?.modelLabel ?: defaultModelLabel)
221− selectedAgent?.let { append(" · $it") }
222− }
223− }
224−
225− // Connection profile (with auth) for rendering inline image attachments.
226− // Collect as state so a server switch recomposes the image context.
227− val activeConnection by container.activeConnection.collectAsStateWithLifecycle()
228− val imageContext = remember(activeConnection?.profile) {
229− activeConnection?.profile?.toImageContext()
230− }
231−
232− // Mark this session as read while the user is viewing it; clear on leave so new
233− // background activity can badge it again.
234− DisposableEffect(sessionId) {
235− container.setCurrentSession(sessionId)
236− onDispose { if (container.currentSession.value == sessionId) container.setCurrentSession(null) }
237− }
238−
239− // Navigate away when the session is deleted via SSE so the user isn't left
240− // on a zombie screen showing a conversation that no longer exists. Surface a
241− // toast (not a snackbar) because the screen is about to be popped — a snackbar
242− // would be torn down before the user could read it, while a toast survives.
243− // Covers both SSE-driven deletion (deleted on another device) and a user-
244− // initiated delete from the chat overflow menu (deleteSession in ChatViewModel
245− // sets the same flag on success).
246− val deletedContext = LocalContext.current
247− LaunchedEffect(sessionDeleted) {
248− if (sessionDeleted) {
249− showToast(deletedContext, deletedContext.getString(R.string.session_deleted_chat))
250− onBack()
251− }
252− }
253−
254− val snackbar = remember { SnackbarHostState() }
255− val retryLabel = stringResource(R.string.retry)
256− val inputFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
257− var showModelPicker by rememberSaveable { mutableStateOf(false) }
258− var showAgentPicker by rememberSaveable { mutableStateOf(false) }
259− var showTitleMenu by rememberSaveable { mutableStateOf(false) }
260− var showCommandPicker by rememberSaveable { mutableStateOf(false) }
261− var showExitConfirm by rememberSaveable { mutableStateOf(false) }
262− var showStopConfirm by rememberSaveable { mutableStateOf(false) }
263− var showOverflowMenu by rememberSaveable { mutableStateOf(false) }
264− var showRenameDialog by rememberSaveable { mutableStateOf(false) }
265− var showDeleteDialog by rememberSaveable { mutableStateOf(false) }
266− var showShellDialog by rememberSaveable { mutableStateOf(false) }
267− var showPalette by rememberSaveable { mutableStateOf(false) }
268− var showShortcutsDialog by rememberSaveable { mutableStateOf(false) }
269− var searchActive by rememberSaveable { mutableStateOf(false) }
270− var chatSearch by rememberSaveable { mutableStateOf("") }
271− // Summarize and init (generate AGENTS.md) are irreversible, so a single tap is gated behind
272− // a confirmation dialog (from both the overflow menu and the command palette).
273− var showSummarizeConfirm by rememberSaveable { mutableStateOf(false) }
274− var showInitConfirm by rememberSaveable { mutableStateOf(false) }
275−
276− // Command-palette entries (keyboard-first: Ctrl+K). Labels resolved here so the remembered
277− // action list doesn't need a Composable context. Actions map to the same handlers the
278− // overflow menu drives, so the palette is a keyboard shortcut to them, not a parallel path.
279− val paletteModelLabel = stringResource(R.string.palette_switch_model)
280− val paletteAgentLabel = stringResource(R.string.palette_choose_agent)
281− val paletteCommandLabel = stringResource(R.string.palette_run_command)
282− val paletteSummarizeLabel = stringResource(R.string.palette_summarize)
283− val paletteRenameLabel = stringResource(R.string.rename_session_chat)
284− val paletteShellLabel = stringResource(R.string.run_shell_command)
285− val paletteActions = remember(
286− paletteModelLabel, paletteAgentLabel, paletteCommandLabel,
287− paletteSummarizeLabel, paletteRenameLabel, paletteShellLabel, hasMessages, running,
288− ) {
289− buildList {
290− add(PaletteAction("model", paletteModelLabel) { showModelPicker = true })
291− add(PaletteAction("agent", paletteAgentLabel) { showAgentPicker = true })
292− add(PaletteAction("command", paletteCommandLabel) { showCommandPicker = true })
293− if (hasMessages && !running) add(PaletteAction("summarize", paletteSummarizeLabel) { showSummarizeConfirm = true })
294− if (!running) add(PaletteAction("shell", paletteShellLabel) { showShellDialog = true })
295− add(PaletteAction("rename", paletteRenameLabel) { showRenameDialog = true })
296− }
297− }
298−
299− // Keep the screen awake while the agent is working in *this* session. The foreground
300− // service that holds process priority during a run is managed app-wide off
301− // container.anyRunActive (see OpencodeApp) so it survives navigating away from the chat
302− // mid-run — otherwise leaving the screen would drop priority and Doze could choke the
303− // SSE stream before the completion notification fires.
304− val currentView = LocalView.current
305− val appContext = LocalContext.current.applicationContext
306− DisposableEffect(running) {
307− currentView.keepScreenOn = running
308− onDispose { currentView.keepScreenOn = false }
309− }
310−
311− LaunchedEffect(Unit) {
312− vm.errorEvents.collect { event ->
313− // Only a failed *send* is retryable; attaching Retry to any other error (e.g. a
314− // message-load failure) would silently re-submit the last prompt on tap.
315− val result = if (event.retryable) {
316− snackbar.showSnackbar(message = event.message, actionLabel = retryLabel)
317− } else {
318− snackbar.showSnackbar(event.message)
319− }
320− if (result == androidx.compose.material3.SnackbarResult.ActionPerformed) vm.retryFailed()
321− }
322− }
323−
324− // In-place Undo for a user-initiated session delete. The delete is deferred for an undo
325− // window on the container; show the snackbar over the conversation the user is viewing so
326− // they can cancel without being navigated to the session list first. If the window expires
327− // the scheduled delete sets `sessionDeleted` and the effect below navigates away.
328− val undoLabel = stringResource(R.string.undo)
329− val sessionDeletedLabel = stringResource(R.string.session_deleted_chat)
330− LaunchedEffect(Unit) {
331− vm.deleteUndoEvents.collect {
332− coroutineScope {
333− val dismisser = launch {
334− delay(NetworkConfig.undoDeleteDelayMs)
335− snackbar.currentSnackbarData?.dismiss()
336− }
337− val result = snackbar.showSnackbar(
338− message = sessionDeletedLabel,
339− actionLabel = undoLabel,
340− duration = SnackbarDuration.Indefinite,
341− )
342− dismisser.cancel()
343− if (result == SnackbarResult.ActionPerformed) vm.cancelSessionDelete()
344− }
345− }
346− }
347−
348− // --- Attachments, voice, and share-link plumbing ---
349− val attachTooLargeMsg = stringResource(R.string.attachment_too_large)
350− val attachFailedMsg = stringResource(R.string.attachment_failed)
351− val attachLimitMsg = stringResource(R.string.attachment_limit)
352− val noCameraMsg = stringResource(R.string.no_camera_app)
353− val noVoiceMsg = stringResource(R.string.no_voice_app)
354− val voicePrompt = stringResource(R.string.voice_prompt)
355− val linkCopiedMsg = stringResource(R.string.link_copied)
356− val ttsUnavailableMsg = stringResource(R.string.tts_unavailable)
357−
358− // Count of picks currently being read + base64-encoded off the main thread, so the
359− // composer can show a staging placeholder immediately (chips only materialize once done).
360− var stagingCount by remember { mutableStateOf(0) }
361−
362− // Convert each picked Uri to a base64 attachment off the main thread, honoring the
363− // per-prompt count cap and surfacing per-file errors without aborting the batch.
364− fun stageUris(uris: List<Uri>) {
365− if (uris.isEmpty()) return
366− scope.launch {
367− stagingCount++
368− try {
369− for (uri in uris) {
370− if (vm.attachments.value.size >= NetworkConfig.maxAttachments) {
371− snackbar.showSnackbar(attachLimitMsg)
372− break
373− }
374− when (val result = uri.toAttachmentResult(appContext)) {
375− is AttachmentResult.Ok -> vm.addAttachment(result.attachment)
376− AttachmentResult.TooLarge -> snackbar.showSnackbar(attachTooLargeMsg)
377− AttachmentResult.Failed -> snackbar.showSnackbar(attachFailedMsg)
378− }
379− }
380− } finally {
381− stagingCount--
382− }
383− }
384− }
385−
386− val photoPicker = rememberLauncherForActivityResult(
387− ActivityResultContracts.PickMultipleVisualMedia(NetworkConfig.maxAttachments),
388− ) { uris -> stageUris(uris) }
389−
390− val filePicker = rememberLauncherForActivityResult(
391− ActivityResultContracts.GetMultipleContents(),
392− ) { uris -> stageUris(uris) }
393−
394− // Uri survives a config change mid-capture so the TakePicture result still resolves.
395− var pendingCaptureUri by rememberSaveable { mutableStateOf<Uri?>(null) }
396− val cameraLauncher = rememberLauncherForActivityResult(
397− ActivityResultContracts.TakePicture(),
398− ) { success ->
399− val uri = pendingCaptureUri
400− pendingCaptureUri = null
401− if (success && uri != null) stageUris(listOf(uri))
402− }
403−
404− val voiceLauncher = rememberLauncherForActivityResult(
405− ActivityResultContracts.StartActivityForResult(),
406− ) { result ->
407− if (result.resultCode == Activity.RESULT_OK) {
408− val spoken = result.data
409− ?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
410− ?.firstOrNull()
411− ?.takeIf { it.isNotBlank() }
412− if (spoken != null) {
413− // Append to the existing draft rather than replacing, so dictation adds to
414− // whatever the user already typed.
415− val current = vm.draft.value
416− val combined = if (current.isBlank()) spoken else "$current $spoken"
417− vm.updateDraft(combined.take(NetworkConfig.maxDraftLengthChars))
418− }
419− }
420− }
421−
422− fun launchCamera() {
423− val uri = newCameraCaptureUri(appContext)
424− if (uri == null) {
425− scope.launch { snackbar.showSnackbar(attachFailedMsg) }
426− return
427− }
428− pendingCaptureUri = uri
429− runCatching { cameraLauncher.launch(uri) }
430− .onFailure { pendingCaptureUri = null; scope.launch { snackbar.showSnackbar(noCameraMsg) } }
431− }
432−
433− fun launchVoice() {
434− val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
435− putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
436− putExtra(RecognizerIntent.EXTRA_PROMPT, voicePrompt)
437− }
438− runCatching { voiceLauncher.launch(intent) }
439− .onFailure { scope.launch { snackbar.showSnackbar(noVoiceMsg) } }
440− }
441−
442− // A freshly-created share link is copied to the clipboard so the user can paste it right away.
443− LaunchedEffect(Unit) {
444− vm.shareLinkEvents.collect { url ->
445− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), url)
446− snackbar.showSnackbar(linkCopiedMsg)
447− }
448− }
449−
450− // Navigate to a session freshly branched from a message (branchFrom), once it's created.
451− // Keyed on Unit (like the sibling one-shot collectors above): keying on the onOpenSession
452− // lambda would cancel/restart this collector whenever the lambda's identity changes, risking
453− // a dropped branch-navigation event in the gap.
454− val branchedMsg = stringResource(R.string.branch_created)
455− LaunchedEffect(Unit) {
456− vm.branchEvents.collect { newId ->
457− showToast(shareContext, branchedMsg)
458− onOpenSession?.invoke(newId)
459− }
460− }
461−
462− // Stage images shared into the app (via the system share sheet) as attachments.
463− // Keyed on pendingSharedMedia (not Unit) so the effect re-fires when new media arrives
464− // while this ChatScreen is already composed — which happens in two-pane mode, where the
465− // detail ChatScreen is persistent (keyed on sessionId) and a LaunchedEffect(Unit) would
466− // only fire on first composition. consumePendingSharedMedia() atomically drains the
467− // pending list (compareAndSet to empty), so re-firing on the now-empty value is a no-op.
468− val pendingSharedMedia by container.pendingSharedMedia.collectAsStateWithLifecycle()
469− LaunchedEffect(pendingSharedMedia) {
470− val shared = container.consumePendingSharedMedia()
471− if (shared.isNotEmpty()) stageUris(shared.map { Uri.parse(it) })
472− }
473−
474− fun doSend() {
475− if (vm.send(draft)) {
476− // TextHandleMove (a light tick) is semantically right for a send commit;
477− // LongPress is reserved for long-press/swipe gestures.
478− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
479− }
480− }
481−
482− BackHandler(enabled = running && !showModelPicker && !showAgentPicker && !showCommandPicker) { showExitConfirm = true }
483−
484− Scaffold(
485− // Hardware-keyboard shortcuts (tablets / DeX / Chromebooks): Ctrl+K opens the command
486− // palette; Escape closes it, or stops a run. onPreviewKeyEvent on the Scaffold root sees
487− // events before the focused text field, but only Ctrl+K / Escape are consumed so normal
488− // typing (and the composer's own Enter-to-send handling) is untouched.
489− modifier = Modifier.onPreviewKeyEvent { ev ->
490− if (ev.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
491− when {
492− ev.isCtrlPressed && ev.key == Key.K -> { showPalette = true; true }
493− ev.key == Key.Escape && showPalette -> { showPalette = false; true }
494− ev.key == Key.Escape && running && !showStopConfirm && !showExitConfirm -> {
495− showStopConfirm = true; true
496− }
497− else -> false
498− }
499− },
500− topBar = {
501− TopAppBar(
502− title = {
503− val changeLabel = stringResource(R.string.change_model_agent)
504− // The subtitle reads "model · agent", so tapping the title offers *both*
505− // — a small menu picks which picker to open. Previously the tap went
506− // straight to the model picker, leaving the agent changeable only via
507− // the overflow menu despite the title implying otherwise.
508− Box {
509− Row(
510− // mergeDescendants so TalkBack reads the title/subtitle Texts as one
511− // node; the click label rides on `clickable` (onClickLabel) instead of
512− // an explicit contentDescription, which would have SUPPRESSED the child
513− // Texts and announced only "Change model and agent".
514− modifier = Modifier
515− .clickable(
516− role = Role.Button,
517− onClickLabel = changeLabel,
518− ) { showTitleMenu = true }
519− .semantics(mergeDescendants = true) {},
520− verticalAlignment = Alignment.CenterVertically,
521− ) {
522− Column(modifier = Modifier.weight(1f, fill = false)) {
523− // maxLines=1 + Ellipsis so a long session title can't wrap and
524− // push the top bar to multiple lines, shifting the whole layout.
525− Text(
526− sessionTitle ?: sessionLabel,
527− maxLines = 1,
528− overflow = TextOverflow.Ellipsis,
529− )
530− Text(
531− subtitle,
532− style = MaterialTheme.typography.labelSmall,
533− color = MaterialTheme.colorScheme.onSurfaceVariant,
534− maxLines = 1,
535− overflow = TextOverflow.Ellipsis,
536− )
537− }
538− // Always show the affordance so the title reads as tappable even when
539− // the model catalog failed to load (models empty). Without it the title
540− // is indistinguishable from plain text and the pickers are effectively
541− // undiscoverable — and the dropdown items already disable themselves
542− // while a catalog is loading or unavailable.
543− Icon(
544− Icons.Filled.KeyboardArrowDown,
545− contentDescription = null,
546− tint = MaterialTheme.colorScheme.onSurfaceVariant,
547− modifier = Modifier.size(20.dp),
548− )
549− }
550− DropdownMenu(expanded = showTitleMenu, onDismissRequest = { showTitleMenu = false }) {
551− DropdownMenuItem(
552− text = { Text(stringResource(R.string.palette_switch_model)) },
553− enabled = !modelsLoading || models.isNotEmpty(),
554− onClick = { showTitleMenu = false; showModelPicker = true },
555− )
556− DropdownMenuItem(
557− text = { Text(stringResource(R.string.palette_choose_agent)) },
558− enabled = !agentsLoading || agents.isNotEmpty(),
559− onClick = { showTitleMenu = false; showAgentPicker = true },
560− )
561− }
562− }
563− },
564− navigationIcon = {
565− IconButton(onClick = {
566− if (running) showExitConfirm = true else onBack()
567− }) {
568− Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(R.string.back))
569− }
570− },
571− actions = {
572− // At-a-glance run status in the top bar. When the user is scrolled
573− // up (jump-to-latest FAB visible), the input-bar Stop button and the
574− // trailing "working…" row are off-screen, so a top-bar spinner is the
575− // only signal the agent is still working.
576− if (running) {
577− val workingLabel = stringResource(R.string.working)
578− CircularProgressIndicator(
579− Modifier.size(18.dp).semantics { contentDescription = workingLabel },
580− strokeWidth = 2.dp,
581− )
582− }
583− // Manual refresh: forces an SSE reconnect, which re-seeds messages
584− // from REST. A recovery path when the stream silently drops and the
585− // auto-reconnect re-seed is slow or fails. Shows a brief spinner as
586− // immediate tap feedback — the SSE reconnect may not visibly change
587− // the connection state when already Connected, so without it the tap
588− // appears to do nothing.
589− val refreshLabel = stringResource(R.string.refresh)
590− IconButton(
591− onClick = { vm.refreshMessages() },
592− enabled = activeConnection != null && !refreshing,
593− ) {
594− if (refreshing) {
595− CircularProgressIndicator(
596− Modifier.size(18.dp).semantics { contentDescription = refreshLabel },
597− strokeWidth = 2.dp,
598− )
599− } else {
600− Icon(Icons.Filled.Refresh, contentDescription = refreshLabel)
601− }
602− }
603− // Overflow menu consolidates the less-frequent actions (share,
604− // commands, agent, model, rename, delete) so the top bar stays
605− // scannable on narrow phones — previously 5 icons crowded the bar
606− // alongside the back button and tappable title. Catalog-loading
607− // spinners stay inline (next to the overflow) so a load state is
608− // visible without opening the menu.
609− val moreLabel = stringResource(R.string.more)
610− val loadingLabel = stringResource(R.string.loading)
611− val shareLabel = stringResource(R.string.share_conversation)
612− val commandsLabel = stringResource(R.string.commands)
613− val renameLabel = stringResource(R.string.rename_session_chat)
614− val deleteLabel = stringResource(R.string.delete_session_chat)
615− val createShareLabel = stringResource(R.string.create_share_link)
616− val copyShareLabel = stringResource(R.string.copy_share_link)
617− val stopShareLabel = stringResource(R.string.stop_sharing)
618− val summarizeLabel = stringResource(R.string.summarize_conversation)
619− val initLabel = stringResource(R.string.generate_agents_md)
620− val shellLabel = stringResource(R.string.run_shell_command)
621− Box {
622− IconButton(onClick = { showOverflowMenu = true }) {
623− Icon(Icons.Filled.MoreVert, contentDescription = moreLabel)
624− }
625− DropdownMenu(
626− expanded = showOverflowMenu,
627− onDismissRequest = { showOverflowMenu = false },
628− ) {
629− DropdownMenuItem(
630− text = { Text(shareLabel) },
631− enabled = hasMessages,
632− onClick = {
633− showOverflowMenu = false
634− scope.launch {
635− val md = withContext(Dispatchers.Default) {
636− buildConversationMarkdown(vm.messages.value, sessionTitle)
637− }
638− val send = android.content.Intent(android.content.Intent.ACTION_SEND).apply {
639− type = "text/markdown"
640− putExtra(android.content.Intent.EXTRA_SUBJECT, sessionTitle ?: defaultShareSubject)
641− putExtra(android.content.Intent.EXTRA_TEXT, md)
642− }
643− runCatchingCancellable { shareContext.startActivity(android.content.Intent.createChooser(send, shareLabel)) }
644− .onFailure { showToast(shareContext, shareContext.getString(R.string.no_share_app)) }
645− }
646− },
647− )
648− DropdownMenuItem(
649− text = { Text(commandsLabel) },
650− enabled = !commandsLoading || commands.isNotEmpty(),
651− onClick = { showOverflowMenu = false; showCommandPicker = true },
652− )
653− DropdownMenuItem(
654− text = { Text(stringResource(R.string.keyboard_shortcuts)) },
655− onClick = { showOverflowMenu = false; showShortcutsDialog = true },
656− )
657− DropdownMenuItem(
658− text = { Text(stringResource(R.string.find_in_conversation)) },
659− onClick = {
660− showOverflowMenu = false
661− searchActive = true
662− runCatching { inputFocusRequester.requestFocus() }
663− },
664− )
665− androidx.compose.material3.HorizontalDivider()
666− // Session sharing: create a public link, copy an existing one, or revoke it.
667− if (shareUrl == null) {
668− DropdownMenuItem(
669− text = { Text(createShareLabel) },
670− enabled = hasMessages,
671− onClick = { showOverflowMenu = false; vm.shareSession() },
672− )
673− } else {
674− DropdownMenuItem(
675− text = { Text(copyShareLabel) },
676− onClick = {
677− showOverflowMenu = false
678− shareUrl?.let {
679− copyToClipboard(shareContext, shareContext.getString(R.string.clip_label_share), it)
680− scope.launch { snackbar.showSnackbar(linkCopiedMsg) }
681− }
682− },
683− )
684− DropdownMenuItem(
685− text = { Text(stopShareLabel) },
686− onClick = { showOverflowMenu = false; vm.unshareSession() },
687− )
688− }
689− DropdownMenuItem(
690− text = { Text(summarizeLabel) },
691− enabled = hasMessages && !running,
692− onClick = { showOverflowMenu = false; showSummarizeConfirm = true },
693− )
694− DropdownMenuItem(
695− text = { Text(initLabel) },
696− enabled = !running,
697− onClick = { showOverflowMenu = false; showInitConfirm = true },
698− )
699− DropdownMenuItem(
700− text = { Text(shellLabel) },
701− enabled = !running,
702− onClick = { showOverflowMenu = false; showShellDialog = true },
703− )
704− androidx.compose.material3.HorizontalDivider()
705− DropdownMenuItem(
706− text = { Text(renameLabel) },
707− onClick = { showOverflowMenu = false; showRenameDialog = true },
708− )
709− DropdownMenuItem(
710− text = { Text(deleteLabel, color = MaterialTheme.colorScheme.error) },
711− onClick = { showOverflowMenu = false; showDeleteDialog = true },
712− )
713− }
714− // While a catalog is initially loading (empty list + loading flag),
715− // show a tiny inline spinner beside the overflow so the user can see
716− // a load is in progress without opening the menu. Once loaded the
717− // spinner disappears; the menu items are always enabled (tapping a
718− // picker with no items shows the "no models/agents/commands" state).
719− val catalogLoading = (commandsLoading && commands.isEmpty()) ||
720− (agentsLoading && agents.isEmpty()) ||
721− (modelsLoading && models.isEmpty())
722− if (catalogLoading) {
723− CircularProgressIndicator(
724− Modifier
725− .align(Alignment.TopEnd)
726− .size(10.dp)
727− .semantics { contentDescription = loadingLabel },
728− strokeWidth = 1.dp,
729− )
730− }
731− }
732− },
733− )
734− },
735− snackbarHost = { SnackbarHost(snackbar) },
736− bottomBar = {
737− val queuedFollowUp by vm.queuedFollowUp.collectAsStateWithLifecycle()
738− val todoPlan by vm.todoPlan.collectAsStateWithLifecycle()
739− val queuedOffline by vm.outbox.collectAsStateWithLifecycle()
740− val outboxSending by container.outboxSending.collectAsStateWithLifecycle()
741− Column {
742− // Pinned above the composer so the agent's plan and progress stay visible
743− // while scrolled up mid-run; renders nothing when there's no plan.
744− TodoPlanBar(todoPlan)
745− val bannerMotion = rememberVisibilityTransitions()
746− AnimatedVisibility(
747− visible = reverted,
748− enter = bannerMotion.enter,
749− exit = bannerMotion.exit,
750− ) {
751− RevertBanner(onUndo = { vm.unrevert() })
752− }
753− AnimatedVisibility(
754− visible = queuedOffline.isNotEmpty(),
755− enter = bannerMotion.enter,
756− exit = bannerMotion.exit,
757− ) {
758− OutboxBanner(
759− count = queuedOffline.size,
760− sending = outboxSending,
761− onFlush = { vm.flushQueued() },
762− onDiscard = { vm.discardAllQueued() },
763− )
764− }
765− ChatInputBar(
766− value = draft,
767− onValueChange = vm::updateDraft,
768− running = running,
769− aborting = aborting,
770− enabled = activeConnection != null,
771− sendOnEnter = sendOnEnter,
772− onSend = ::doSend,
773− onAbort = { showStopConfirm = true },
774− queuedFollowUp = queuedFollowUp,
775− onQueueFollowUp = vm::queueFollowUp,
776− onCancelQueue = { vm.queueFollowUp("") },
777− focusRequester = inputFocusRequester,
778− attachments = attachments,
779− staging = stagingCount > 0,
780− onRemoveAttachment = vm::removeAttachment,
781− onPickPhoto = {
782− photoPicker.launch(
783− PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly),
784− )
785− },
786− onPickFile = { filePicker.launch("*/*") },
787− onCamera = { launchCamera() },
788− onVoice = { launchVoice() },
789− onPasteImage = { stageUris(it) },
790− )
791− }
792− },
793− ) { padding ->
794− // Collect messages inside the content lambda so streaming token updates
795− // recompose only this subtree, not the top bar / input bar / 20+ other
796− // state reads in the ChatScreen body.
797− val messages by vm.messages.collectAsStateWithLifecycle()
798− val optimisticStatuses by vm.optimisticStatuses.collectAsStateWithLifecycle()
799− val listState = rememberLazyListState()
800− val contentScope = rememberCoroutineScope()
801− val timeTick = rememberRelativeTimeTick()
802− // Dismiss the soft keyboard when the user scrolls the message list, a standard Android
803− // chat affordance for reading while the IME is open. Watching isScrollInProgress via
804− // snapshotFlow avoids wiring a nested scroll connection and fires on any scroll gesture.
805− val keyboardController = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
806− androidx.compose.runtime.LaunchedEffect(listState) {
807− androidx.compose.runtime.snapshotFlow { listState.isScrollInProgress }
808− .distinctUntilChanged()
809− .collect { scrolling -> if (scrolling) keyboardController?.hide() }
810− } // Group messages by day and interleave date separators so a long conversation
811− // has visual "Today"/"Yesterday"/date breaks. Computed once per messages
812− // emission (memoized) so a scroll-induced recomposition doesn't re-scan. Lives
813− // outside the PullToRefreshBox so the auto-scroll effects below can reference
814− // the same list the LazyColumn renders (separators shift the indices vs. the
815− // raw messages list, so scroll targets must be in listItems space).
816− val todayLabel = stringResource(R.string.today)
817− val yesterdayLabel = stringResource(R.string.yesterday)
818− // In-conversation search: when active, narrow to messages whose text contains the query.
819− // Computed on the filtered set so day separators still align with the visible messages.
820− val searchQuery = chatSearch.trim()
821− val searchMessages = remember(messages, searchQuery) {
822− if (searchQuery.isEmpty()) messages
823− else messages.filter { m ->
824− m.parts.any { p -> (p as? TextPart)?.text?.contains(searchQuery, ignoreCase = true) == true }
825− }
826− }
827− val listItems = remember(searchMessages, todayLabel, yesterdayLabel) {
828− buildMessageListItems(searchMessages, todayLabel, yesterdayLabel)
829− }
830− // listItems is a plain (non-snapshot) local, rebuilt each recomposition. The
831− // derivedStateOf and snapshotFlow lambdas below are created once (keyless
832− // remember / LaunchedEffect(Unit)); reading `listItems` directly inside them
833− // would capture the first composition's list — which is empty, since `messages`
834− // starts empty — freezing it forever. That pinned isPinnedToBottom at true and
835− // AutoScrollSignal.size at 0, breaking streaming auto-scroll and the
836− // jump-to-latest FAB. rememberUpdatedState hands those lambdas a stable State
837− // whose value tracks the latest list.
838− val currentListItems by rememberUpdatedState(listItems)
839−
840− // New-content signal for the jump-to-latest FAB: counts how many new items arrived
841− // while the user was scrolled away from the bottom, cleared once they return. A count
842− // (vs. a bare dot) tells the user how much they missed at a glance.
843− var newContentCount by remember { mutableIntStateOf(0) }
844−
845− val isPinnedToBottom by remember {
846− derivedStateOf {
847− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
848− // When a run is active, the LazyColumn has one trailing "__typing"
849− // item after the last list item. Account for it so "pinned to bottom"
850− // includes the working indicator — otherwise the pin check targets
851− // listItems.lastIndex, the typing row sits just below the viewport,
852− // and the user never sees the progress indicator even when pinned.
853− val items = currentListItems
854− val effectiveLast = if (running) items.size else items.lastIndex
855− lastVisible >= effectiveLast || items.isEmpty()
856− }
857− }
858−
859− // Jump to the newest message once, when the conversation first loads. Guarded by a
860− // saveable one-shot flag so it doesn't re-fire on recomposition after a config change
861− // (rotation) — rememberLazyListState restores the user's scroll offset, and an
862− // unconditional scrollToItem here would clobber it, snapping them back to the bottom.
863− var didInitialScroll by rememberSaveable { mutableStateOf(false) }
864− LaunchedEffect(listItems.isNotEmpty()) {
865− if (listItems.isNotEmpty() && !didInitialScroll) {
866− // When a run is active the LazyColumn has a trailing "__typing" row at
867− // listItems.size; target it (not listItems.lastIndex) so deep-linking into a
868− // running session lands truly pinned to bottom and streaming auto-scroll engages.
869− listState.scrollToItem(if (running) listItems.size else listItems.lastIndex)
870− didInitialScroll = true
871− }
872− }
873−
874− // When a run starts, the LazyColumn gains a trailing "__typing" row, so
875− // effectiveLast jumps from listItems.lastIndex to listItems.size and the
876− // isPinnedToBottom check flips to false the instant you send — freezing
877− // auto-scroll. If the user was pinned to the last item just before the run
878− // began, bring the typing row into view so the pin (and streaming follow) is
879− // preserved. Guard on the raw last-visible index (isPinnedToBottom has already
880− // recomputed to false by now) so we don't scroll when the user had scrolled up.
881− LaunchedEffect(running) {
882− if (running && listItems.isNotEmpty()) {
883− val lastVisible = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: -1
884− if (lastVisible >= listItems.lastIndex) {
885− runCatchingCancellable { listState.animateScrollToItem(listItems.size) }
886− }
887− }
888− }
889−
890− LaunchedEffect(Unit) {
891− var prevSize = 0
892− var prevLen = 0
893− snapshotFlow {
894− // Track list size + the streaming length of the last part so we auto-scroll
895− // as content arrives, plus the pinned flag. A small data class with primitive
896− // fields avoids the per-frame boxing that Triple<Int,Int,Boolean> pays
897− // (snapshotFlow re-evaluates this lambda every snapshot), and reading only the
898− // last part's length is O(1) vs. a sumOf over every part. Covering reasoning
899− // and tool output — not just TextPart — keeps a pinned view following a long
900− // reasoning/tool block while it streams (previously it stalled at 0).
901− val lastLen = streamingContentLength(messages.lastOrNull()?.parts?.lastOrNull())
902− AutoScrollSignal(currentListItems.size, lastLen, isPinnedToBottom)
903− }.collect { signal ->
904− if (signal.pinned) {
905− // Back at the bottom: clear the new-content badge.
906− newContentCount = 0
907− if (signal.size > 0) {
908− // Scroll to the effective last index, including the trailing
909− // "__typing" row when a run is active so the working indicator
910− // is brought into view (not just the last message).
911− val items = currentListItems
912− val target = if (running) items.size else items.lastIndex
913− listState.scrollToItem(target)
914− }
915− } else if (signal.size > prevSize || signal.lastTextLength > prevLen) {
916− // Content arrived while scrolled up — increment the jump-to-latest badge.
917− // Only count whole new items (not per-token growth) so the number reflects
918− // new messages, not a token count.
919− if (signal.size > prevSize) newContentCount += signal.size - prevSize
920− else if (newContentCount == 0) newContentCount = 1
921− }
922− prevSize = signal.size
923− prevLen = signal.lastTextLength
924− }
925− }
926−
927− CompositionLocalProvider(LocalRelativeTimeTick provides timeTick) {
928− // The bottomBar (ChatInputBar) already has imePadding, and the Scaffold's
929− // content padding accounts for the bottomBar's raised height, so the message
930− // list is already above the keyboard. Adding imePadding here would double-apply
931− // the IME inset and push messages too far up.
932− Box(modifier = Modifier.fillMaxSize().padding(padding)) {
933− if (activeConnection == null) {
934− Column(
935− modifier = Modifier.align(Alignment.Center).padding(24.dp),
936− horizontalAlignment = Alignment.CenterHorizontally,
937− ) {
938− Text(
939− stringResource(R.string.not_connected),
940− color = MaterialTheme.colorScheme.error,
941− )
942− Spacer(Modifier.size(12.dp))
943− Button(onClick = { vm.reconnect() }, enabled = !reconnecting) {
944− if (reconnecting) {
945− CircularProgressIndicator(
946− Modifier.size(20.dp),
947− color = MaterialTheme.colorScheme.onPrimary,
948− strokeWidth = 2.dp,
949− )
950− } else {
951− Text(stringResource(R.string.reconnect))
952− }
953− }
954− }
955− } else {
956− val bannerVisible = !isOnline || connectionState != EventStreamClient.ConnectionState.Connected
957− // Measure the banner's actual height instead of hardcoding 44dp. At large
958− // accessibility font scales the banner's labelMedium text + spinner + Retry
959− // button exceed 44dp, so a fixed inset lets the first message hide behind it
960− // (the same hazard FileViewScreen's overlay calls out). onSizeChanged only
961− // fires while the banner is composed (visible), so gate the inset on
962− // bannerVisible and fall back to 44dp until the first measurement arrives.
963− var bannerHeightPx by remember { mutableIntStateOf(0) }
964− val density = LocalDensity.current
965− val topPad = if (bannerVisible) {
966− if (bannerHeightPx > 0) {
967− with(density) { bannerHeightPx.toDp() } + 4.dp
968− } else {
969− 44.dp
970− }
971− } else {
972− 16.dp
973− }
974− ConnectionBanner(
975− state = connectionState,
976− modifier = Modifier.align(Alignment.TopCenter).onSizeChanged { bannerHeightPx = it.height },
977− isOnline = isOnline,
978− // On a hard failure, retry by forcing an SSE reconnect (which
979− // re-seeds from REST). refreshMessages is the right recovery path
980− // when the connection is present but the stream died; reconnect()
981− // is the path when the whole connection is gone (handled by the
982− // separate "Not connected" state below).
983− onRetry = { vm.refreshMessages() },
984− )
985− // Pull-to-refresh wraps ALL content states (loading, error, empty, list) so
986− // recovery is a swipe away everywhere — not just when the message list is
987− // populated. Previously PTR was only around the populated list, leaving the
988− // error/loading states reachable only via a button tap.
989− PullToRefreshBox(
990− isRefreshing = refreshing,
991− onRefresh = { vm.refreshMessages() },
992− // Cap width and center on large screens for readability — full-width
993− // bubbles stretch edge-to-edge on tablets, hurting line-length comfort.
994− modifier = Modifier.fillMaxSize().wrapContentWidth(Alignment.CenterHorizontally)
995− .widthIn(max = NetworkConfig.chatContentMaxWidthDp.dp),
996− ) {
997− // Reserve top space when the banner is visible so it doesn't overlap the
998− // first message / state content. (topPad computed above.)
999− if (loading && messages.isEmpty()) {
1000− val loadingLabel = stringResource(R.string.loading)
1001− // Skeleton bubbles pre-structure the layout so the perceived load is faster
1002− // than a bare centered spinner and the first real messages pop into an
1003− // already-shaped list instead of a blank-then-pop. Alpha pulses (gated by
1004− // reduced-motion) to convey ongoing work; the column carries the a11y label.
1005− val reducedMotion = LocalReducedMotion.current
1006− val transition = rememberInfiniteTransition(label = "skeleton")
1007− val pulse by transition.animateFloat(
1008− initialValue = 0.35f,
1009− targetValue = 0.7f,
1010− animationSpec = infiniteRepeatable(tween(900), RepeatMode.Reverse),
1011− label = "skeletonAlpha",
1012− )
1013− val skeletonAlpha = if (reducedMotion) 0.5f else pulse
1014− val skeletonColor = MaterialTheme.colorScheme.surfaceVariant
1015− @Composable
1016− fun bar(widthFraction: Float) {
1017− Box(
1018− Modifier
1019− .fillMaxWidth(widthFraction)
1020− .height(14.dp)
1021− .clip(RoundedCornerShape(4.dp))
1022− .background(skeletonColor)
1023− .alpha(skeletonAlpha),
1024− )
1025− }
1026− Column(
1027− modifier = Modifier
1028− .align(Alignment.TopCenter)
1029− .padding(top = topPad)
1030− .padding(16.dp)
1031− .fillMaxWidth()
1032− .semantics { contentDescription = loadingLabel },
1033− verticalArrangement = Arrangement.spacedBy(14.dp),
1034− ) {
1035− repeat(4) { i ->
1036− val left = i % 2 == 0
1037− Row(
1038− modifier = Modifier.fillMaxWidth(),
1039− horizontalArrangement = if (left) Arrangement.Start else Arrangement.End,
1040− ) {
1041− Column(
1042− modifier = Modifier.fillMaxWidth(if (left) 0.7f else 0.55f),
1043− verticalArrangement = Arrangement.spacedBy(6.dp),
1044− ) {
1045− bar(1f)
1046− bar(0.8f)
1047− }
1048− }
1049− }
1050− }
1051− } else if (loadError && messages.isEmpty()) {
1052− // A failed load with nothing to show. Distinct from the empty
1053− // conversation state below — the conversation isn't empty, it
1054− // failed to load, and offering "Start a conversation" here is
1055− // misleading. Offer a Retry instead, mirroring SessionListScreen.
1056− Column(
1057− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1058− horizontalAlignment = Alignment.CenterHorizontally,
1059− ) {
1060− Text(
1061− stringResource(R.string.load_messages_failed),
1062− color = MaterialTheme.colorScheme.error,
1063− )
1064− Spacer(Modifier.size(12.dp))
1065− Button(onClick = { vm.refreshMessages() }) {
1066− Text(stringResource(R.string.retry))
1067− }
1068− }
1069− } else if (messages.isEmpty() && running) {
1070− // A run just started but no parts have arrived yet — the empty
1071− // list with only the trailing "working…" row looks broken, so
1072− // surface a clear starting state until the first part streams in.
1073− val workingText = stringResource(R.string.working)
1074− Column(
1075− modifier = Modifier.align(Alignment.Center).padding(top = topPad).padding(24.dp),
1076− horizontalAlignment = Alignment.CenterHorizontally,
1077− ) {
1078− CircularProgressIndicator(Modifier.size(28.dp), strokeWidth = 3.dp)
1079− Spacer(Modifier.size(12.dp))
1080− Text(workingText, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
1081− }
1082− } else if (messages.isEmpty()) {
1083− EmptyConversation(
1084− onSuggestion = {
1085− vm.updateDraft(it)
1086− // Focus the input so the user can edit the suggestion before
1087− // sending, instead of having to manually tap the field.
1088− runCatching { inputFocusRequester.requestFocus() }
1089− },
1090− modifier = Modifier.align(Alignment.Center).padding(top = topPad),
1091− )
1092− } else {
1093− val lastMessageId = messages.lastOrNull()?.info?.id
1094− // Text-to-speech for reading assistant replies aloud; shuts down when the
1095− // message list leaves composition.
1096− val tts = rememberTtsController()
1097− val speakingMessageId by tts.speakingId
1098− LazyColumn(
1099− state = listState,
1100− modifier = Modifier.fillMaxSize(),
1101− // Extra bottom padding reserves room for the jump-to-latest FAB so it
1102− // never floats over the last message. Top padding grows when the
1103− // connection banner is visible so it doesn't overlap the first message.
1104− contentPadding = PaddingValues(
1105− start = 16.dp,
1106− top = topPad,
1107− end = 16.dp,
1108− bottom = 16.dp + NetworkConfig.chatListFabInsetDp.dp,
1109− ),
1110− verticalArrangement = Arrangement.spacedBy(16.dp),
1111− ) {
1112− items(
1113− items = listItems,
1114− key = { it.key },
1115− contentType = { it.contentType },
1116− ) { item ->
1117− // Default placement animation so inserted/moved rows glide in. Skipped
1118− // entirely under reduced motion so a streaming message growing in place
1119− // doesn't animate on every token (and respects the a11y preference).
1120− Box(
1121− if (LocalReducedMotion.current) Modifier else Modifier.animateItem(),
1122− ) {
1123− when (item) {
1124− is MessageListItem.Separator -> DateSeparator(item.label)
1125− is MessageListItem.Message -> {
1126− val message = item.message
1127− // Only the last (streaming) message needs isRunning — it drives the
1128− // reasoning-block spinner. Passing the live flag to every bubble
1129− // makes all visible messages recompose whenever a run starts or stops.
1130− val modelLabel = remember(message.info, models) {
1131− (message.info as? soy.iko.opencode.data.model.AssistantMessage)
1132− ?.let { resolveModelLabel(it, models) }
1133− }
1134− // Text used to drive swipe-to-reply (and pre-fill the quote). Empty for
1135− // image/code-only messages, which then opt out of the swipe gesture.
1136− val quoteText = remember(message.parts) {
1137− message.parts
1138− .filterIsInstance<TextPart>()
1139− .joinToString("\n\n") { it.text }
1140− .trim()
1141− .takeIf { it.isNotEmpty() }
1142− }
1143− // Swipe-start-to-end reveals a reply affordance and triggers quote-reply,
1144− // snapping back (the message isn't dismissed — the quote fills the composer).
1145− // Only enabled when there's text to quote, so non-text messages don't
1146− // capture horizontal drags (e.g. inside a horizontally-scrollable code block).
1147− val swipeState = rememberSwipeToDismissBoxState(
1148− confirmValueChange = { value ->
1149− if (value == SwipeToDismissBoxValue.StartToEnd && quoteText != null) {
1150− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1151− vm.quoteReply(quoteText)
1152− runCatching { inputFocusRequester.requestFocus() }
1153− }
1154− false
1155− },
1156− )
1157− SwipeToDismissBox(
1158− state = swipeState,
1159− enableDismissFromEndToStart = false,
1160− enableDismissFromStartToEnd = quoteText != null,
1161− backgroundContent = {
1162− Box(
1163− Modifier.fillMaxSize().padding(horizontal = 16.dp),
1164− contentAlignment = Alignment.CenterStart,
1165− ) {
1166− Icon(
1167− Icons.AutoMirrored.Filled.Reply,
1168− contentDescription = null,
1169− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1170− )
1171− }
1172− },
1173− ) {
1174− MessageBubble(
1175− message,
1176− isRunning = running && message.info.id == lastMessageId,
1177− imageContext = imageContext,
1178− modelLabel = modelLabel,
1179− onOpenFile = onOpenFile,
1180− onRevert = { vm.revertTo(message.info.id) },
1181− onEdit = { text ->
1182− // editMessage reverts to before this message (hiding it and
1183− // everything after); the revert banner surfaces the rewind
1184− // with an Undo. Focus + scroll the composer into view like the
1185− // Quote action so the prefilled draft isn't off-screen.
1186− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1187− vm.editMessage(message.info.id, text)
1188− runCatching { inputFocusRequester.requestFocus() }
1189− contentScope.launch {
1190− runCatchingCancellable {
1191− listState.animateScrollToItem(listItems.lastIndex.coerceAtLeast(0))
1192− }
1193− }
1194− },
1195− onSpeak = { text ->
1196− if (!tts.toggle(message.info.id, text)) {
1197− // TTS engine unavailable (init failed / not yet ready
1198− // / blank text): surface feedback so the button doesn't
1199− // appear dead. Throttled so a rapid double-tap (stop
1200− // then immediate re-tap before ready) doesn't spam.
1201− scope.launch { snackbar.showSnackbar(ttsUnavailableMsg) }
1202− }
1203− },
1204− isSpeaking = message.info.id == speakingMessageId,
1205− onQuote = { text ->
1206− vm.quoteReply(text)
1207− runCatching { inputFocusRequester.requestFocus() }
1208− },
1209− onBranch = { text -> vm.branchFrom(text) },
1210− // Regenerate is only meaningful for a finished assistant reply
1211− // (not the actively-streaming one), so gate it on !running.
1212− onRegenerate = if (!running) {
1213− { vm.regenerate(message.info.id) }
1214− } else null,
1215− sendStatus = optimisticStatuses[message.info.id]?.let { failed ->
1216− if (failed) soy.iko.opencode.ui.chat.MessageSendStatus.FAILED
1217− else soy.iko.opencode.ui.chat.MessageSendStatus.SENDING
1218− },
1219− isEdited = message.info.time?.let { it.updated != null && it.updated != it.created } == true,
1220− onRetry = optimisticStatuses[message.info.id]?.let { failed ->
1221− if (failed) {
1222− { vm.retryOptimisticMessage(message.info.id) }
1223− } else {
1224− null
1225− }
1226− },
1227− onDismiss = optimisticStatuses[message.info.id]?.let { failed ->
1228− if (failed) {
1229− { vm.dismissOptimistic(message.info.id) }
1230− } else {
1231− null
1232− }
1233− },
1234− )
1235− }
1236− }
1237− }
1238− }
1239− }
1240− if (running) {
1241− item(key = "__typing") {
1242− val workingText = stringResource(R.string.working)
1243− // Elapsed-since-run chip: the typing row only composes while a run is
1244− // active, so anchoring the timer to first composition approximates the
1245− // run start and gives the user a sense of how long the agent has been
1246− // working — distinguishing a healthy long run from a hung one. Updates
1247− // once per second; the value is decorative (the a11y label is the row's).
1248− var startMs by remember { mutableLongStateOf(0L) }
1249− LaunchedEffect(Unit) { startMs = System.currentTimeMillis() }
1250− val elapsedMs by produceState(0L, startMs) {
1251− if (startMs == 0L) return@produceState
1252− while (true) {
1253− value = (System.currentTimeMillis() - startMs).coerceAtLeast(0L)
1254− delay(1000)
1255− }
1256− }
1257− val elapsedText = remember(elapsedMs) {
1258− val total = elapsedMs / 1000
1259− "%d:%02d".format(total / 60, total % 60)
1260− }
1261− Row(
1262− verticalAlignment = Alignment.CenterVertically,
1263− modifier = Modifier.semantics {
1264− contentDescription = workingText
1265− },
1266− ) {
1267− CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp)
1268− Text(workingText, style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start = 6.dp))
1269− Spacer(Modifier.size(8.dp))
1270− Icon(
1271− Icons.Filled.Schedule,
1272− contentDescription = null,
1273− modifier = Modifier.size(14.dp),
1274− tint = MaterialTheme.colorScheme.onSurfaceVariant,
1275− )
1276− Text(
1277− elapsedText,
1278− style = MaterialTheme.typography.labelMedium,
1279− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1280− color = MaterialTheme.colorScheme.onSurfaceVariant,
1281− modifier = Modifier.padding(start = 4.dp),
1282− )
1283− // A trailing Stop on the working row so the run can be aborted
1284− // without scrolling back to the composer (which may be off-screen
1285− // while the user reads the streaming output up-thread).
1286− Spacer(Modifier.weight(1f))
1287− val stopLabel = stringResource(R.string.stop)
1288− IconButton(
1289− onClick = { showStopConfirm = true },
1290− modifier = Modifier.semantics { contentDescription = stopLabel },
1291− ) {
1292− Icon(Icons.Filled.Stop, contentDescription = null)
1293− }
1294− }
1295− }
1296− }
1297− }
1298− }
1299− }
1300− // Jump-to-latest affordance when the user has scrolled away during a stream.
1301− val fabMotion = rememberVisibilityTransitions()
1302− AnimatedVisibility(
1303− visible = !isPinnedToBottom && listItems.isNotEmpty(),
1304− enter = fabMotion.enter,
1305− exit = fabMotion.exit,
1306− modifier = Modifier.align(Alignment.BottomEnd),
1307− ) {
1308− // Badge the FAB when new content arrived while the user was scrolled up, so
1309− // they know there's something new to jump to (cleared once back at bottom).
1310− BadgedBox(
1311− badge = {
1312− if (newContentCount > 0) {
1313− val newContentLabel = stringResource(R.string.new_messages)
1314− Badge(modifier = Modifier.semantics { contentDescription = newContentLabel }) {
1315− Text(if (newContentCount > 99) "99+" else newContentCount.toString())
1316− }
1317− }
1318− },
1319− modifier = Modifier.padding(end = 16.dp, bottom = 16.dp),
1320− ) {
1321− ExtendedFloatingActionButton(
1322− onClick = {
1323− newContentCount = 0
1324− if (listItems.isNotEmpty()) {
1325− // Scroll to the effective last index, including the
1326− // trailing "__typing" row when a run is active.
1327− val target = if (running) listItems.size else listItems.lastIndex
1328− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(target) } }
1329− }
1330− },
1331− // contentDescription null: the visible "Latest" text already labels
1332− // the FAB, so a description here makes TalkBack announce "Latest" twice.
1333− icon = { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null) },
1334− text = { Text(stringResource(R.string.latest)) },
1335− )
1336− }
1337− }
1338− // Scroll-to-top affordance: a small FAB at the start edge, visible when the
1339− // user has scrolled down past the first few messages. Symmetric to the
1340− // jump-to-latest FAB, for long conversations where manual fling back is tedious.
1341− val scrolledDown by remember {
1342− derivedStateOf { listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 200 }
1343− }
1344− AnimatedVisibility(
1345− visible = scrolledDown && listItems.size > 4,
1346− enter = fabMotion.enter,
1347− exit = fabMotion.exit,
1348− modifier = Modifier.align(Alignment.BottomStart),
1349− ) {
1350− SmallFloatingActionButton(
1351− onClick = {
1352− contentScope.launch { runCatchingCancellable { listState.animateScrollToItem(0) } }
1353− },
1354− modifier = Modifier.padding(start = 16.dp, bottom = 16.dp),
1355− ) {
1356− Icon(
1357− Icons.Filled.KeyboardArrowUp,
1358− contentDescription = stringResource(R.string.scroll_to_top),
1359− )
1360− }
1361− }
1362− // In-conversation search bar. Overlays the list so typing filters messages in
1363− // place; the match count + a no-matches note give immediate feedback.
1364− val searchMotion = rememberVisibilityTransitions()
1365− AnimatedVisibility(
1366− visible = searchActive,
1367− enter = searchMotion.enter,
1368− exit = searchMotion.exit,
1369− modifier = Modifier.align(Alignment.TopCenter),
1370− ) {
1371− Surface(
1372− tonalElevation = 3.dp,
1373− modifier = Modifier
1374− .padding(horizontal = 12.dp, vertical = 4.dp)
1375− .fillMaxWidth(),
1376− ) {
1377− Row(
1378− modifier = Modifier.padding(start = 8.dp, end = 4.dp),
1379− verticalAlignment = Alignment.CenterVertically,
1380− ) {
1381− OutlinedTextField(
1382− value = chatSearch,
1383− onValueChange = { chatSearch = it },
1384− modifier = Modifier.weight(1f),
1385− placeholder = { Text(stringResource(R.string.search_in_conversation)) },
1386− singleLine = true,
1387− leadingIcon = { Icon(Icons.Filled.Search, contentDescription = null) },
1388− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
1389− )
1390− Text(
1391− if (searchQuery.isNotEmpty()) {
1392− stringResource(R.string.search_match_count, searchMessages.size, messages.size)
1393− } else "",
1394− style = MaterialTheme.typography.labelSmall,
1395− color = MaterialTheme.colorScheme.onSurfaceVariant,
1396− modifier = Modifier.padding(horizontal = 4.dp),
1397− )
1398− IconButton(onClick = {
1399− searchActive = false
1400− chatSearch = ""
1401− }) {
1402− Icon(Icons.Filled.Close, contentDescription = stringResource(R.string.clear_search))
1403− }
1404− }
1405− }
1406− }
1407− // When a search yields no matches (but the conversation isn't empty), say so
1408− // instead of showing a blank list.
1409− if (searchActive && searchQuery.isNotEmpty() && searchMessages.isEmpty() && messages.isNotEmpty()) {
1410− Text(
1411− stringResource(R.string.search_no_matches),
1412− style = MaterialTheme.typography.bodyMedium,
1413− color = MaterialTheme.colorScheme.onSurfaceVariant,
1414− modifier = Modifier.align(Alignment.Center),
1415− )
1416− }
1417− }
1418− }
1419− }
1420− }
1421−
1422− if (showExitConfirm) {
1423− AlertDialog(
1424− onDismissRequest = { showExitConfirm = false },
1425− title = { Text(stringResource(R.string.stop_and_exit_title)) },
1426− text = { Text(stringResource(R.string.stop_and_exit_text)) },
1427− confirmButton = {
1428− TextButton(onClick = {
1429− showExitConfirm = false
1430− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1431− vm.abort()
1432− onBack()
1433− }) { Text(stringResource(R.string.stop_and_exit)) }
1434− },
1435− dismissButton = {
1436− TextButton(onClick = { showExitConfirm = false }) { Text(stringResource(R.string.stay)) }
1437− },
1438− )
1439− }
1440−
1441− if (showStopConfirm) {
1442− AlertDialog(
1443− onDismissRequest = { showStopConfirm = false },
1444− title = { Text(stringResource(R.string.stop_run_title)) },
1445− text = { Text(stringResource(R.string.stop_run_text)) },
1446− confirmButton = {
1447− TextButton(onClick = {
1448− showStopConfirm = false
1449− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.TextHandleMove)
1450− vm.abort()
1451− }) { Text(stringResource(R.string.stop), color = MaterialTheme.colorScheme.error) }
1452− },
1453− dismissButton = {
1454− TextButton(onClick = { showStopConfirm = false }) { Text(stringResource(R.string.cancel)) }
1455− },
1456− )
1457− }
1458−
1459− if (showSummarizeConfirm) {
1460− AlertDialog(
1461− onDismissRequest = { showSummarizeConfirm = false },
1462− title = { Text(stringResource(R.string.summarize_confirm_title)) },
1463− text = { Text(stringResource(R.string.summarize_confirm_text)) },
1464− confirmButton = {
1465− TextButton(onClick = {
1466− showSummarizeConfirm = false
1467− vm.summarize()
1468− }) { Text(stringResource(R.string.action_continue)) }
1469− },
1470− dismissButton = {
1471− TextButton(onClick = { showSummarizeConfirm = false }) { Text(stringResource(R.string.cancel)) }
1472− },
1473− )
1474− }
1475−
1476− if (showInitConfirm) {
1477− AlertDialog(
1478− onDismissRequest = { showInitConfirm = false },
1479− title = { Text(stringResource(R.string.init_confirm_title)) },
1480− text = { Text(stringResource(R.string.init_confirm_text)) },
1481− confirmButton = {
1482− TextButton(onClick = {
1483− showInitConfirm = false
1484− vm.initProject()
1485− }) { Text(stringResource(R.string.action_continue)) }
1486− },
1487− dismissButton = {
1488− TextButton(onClick = { showInitConfirm = false }) { Text(stringResource(R.string.cancel)) }
1489− },
1490− )
1491− }
1492−
1493− if (showRenameDialog) {
1494− RenameSessionChatDialog(
1495− initialTitle = sessionTitle ?: "",
1496− onDismiss = { showRenameDialog = false },
1497− onConfirm = { newName ->
1498− showRenameDialog = false
1499− vm.renameSession(newName)
1500− },
1501− )
1502− }
1503−
1504− if (showDeleteDialog) {
1505− AlertDialog(
1506− onDismissRequest = { showDeleteDialog = false },
1507− title = { Text(stringResource(R.string.delete_session_chat_title)) },
1508− text = { Text(stringResource(R.string.delete_session_chat_text, sessionTitle ?: sessionLabel)) },
1509− confirmButton = {
1510− TextButton(onClick = {
1511− showDeleteDialog = false
1512− haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.LongPress)
1513− vm.deleteSession()
1514− }) { Text(stringResource(R.string.delete), color = MaterialTheme.colorScheme.error) }
1515− },
1516− dismissButton = {
1517− TextButton(onClick = { showDeleteDialog = false }) { Text(stringResource(R.string.cancel)) }
1518− },
1519− )
1520− }
1521−
1522− if (showShellDialog) {
1523− ShellCommandDialog(
1524− onDismiss = { showShellDialog = false },
1525− onRun = { cmd ->
1526− showShellDialog = false
1527− vm.runShell(cmd)
1528− },
1529− )
1530− }
1531−
1532− if (showModelPicker) {
1533− ModelPickerSheet(
1534− options = models,
1535− selected = selectedModel,
1536− loading = modelsLoading,
1537− error = modelsError,
1538− onSelect = { vm.selectModel(it) },
1539− onRetry = { vm.reloadModels() },
1540− onDismiss = { showModelPicker = false },
1541− )
1542− }
1543−
1544− if (showAgentPicker) {
1545− AgentPickerSheet(
1546− agents = agents,
1547− selected = selectedAgent,
1548− loading = agentsLoading,
1549− error = agentsError,
1550− onSelect = { vm.selectAgent(it?.name) },
1551− onRetry = { vm.reloadAgents() },
1552− onDismiss = { showAgentPicker = false },
1553− )
1554− }
1555−
1556− if (showCommandPicker) {
1557− CommandPickerSheet(
1558− commands = commands,
1559− loading = commandsLoading,
1560− error = commandsError,
1561− onSelect = { vm.runCommand(it) },
1562− onRetry = { vm.reloadCommands() },
1563− onDismiss = { showCommandPicker = false },
1564− )
1565− }
1566−
1567− pendingPermission?.let { permission ->
1568− PermissionDialog(
1569− permission = permission,
1570− position = permissionProgress.position,
1571− total = permissionProgress.total,
1572− onRespond = { response -> vm.respondPermission(permission, response) },
1573− )
1574− }
1575−
1576− if (showPalette) {
1577− CommandPalette(actions = paletteActions, onDismiss = { showPalette = false })
1578− }
1579−
1580− if (showShortcutsDialog) {
1581− // Surfaces the hardware-keyboard shortcuts (Ctrl+K palette, Escape stop, Enter send)
1582− // that are otherwise wired but undiscoverable. A simple key/value list; Enter behavior
1583− // depends on the "Send on Enter" setting, noted inline.
1584− AlertDialog(
1585− onDismissRequest = { showShortcutsDialog = false },
1586− title = { Text(stringResource(R.string.keyboard_shortcuts_title)) },
1587− text = {
1588− Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
1589− ShortcutRow("Ctrl + K", stringResource(R.string.shortcut_open_palette))
1590− ShortcutRow("Esc", stringResource(R.string.shortcut_stop_run))
1591− ShortcutRow("Esc", stringResource(R.string.shortcut_close))
1592− ShortcutRow("Enter", stringResource(R.string.shortcut_send))
1593− ShortcutRow("Shift + Enter / Ctrl + Enter", stringResource(R.string.shortcut_newline))
1594− }
1595− },
1596− confirmButton = {
1597− TextButton(onClick = { showShortcutsDialog = false }) { Text(stringResource(R.string.action_continue)) }
1598− },
1599− )
1600− }
1601−}
1602−
1603−@Composable
1604−private fun ShortcutRow(keys: String, desc: String) {
1605− Row(verticalAlignment = Alignment.CenterVertically) {
1606− Text(
1607− keys,
1608− style = MaterialTheme.typography.labelLarge,
1609− fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
1610− modifier = Modifier.widthIn(min = 160.dp),
1611− )
1612− Text(
1613− desc,
1614− style = MaterialTheme.typography.bodyMedium,
1615− color = MaterialTheme.colorScheme.onSurfaceVariant,
1616− )
1617− }
1618−}
1619−
1620−@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
1621−@Composable
1622−private fun ChatInputBar(
1623− value: String,
1624− onValueChange: (String) -> Unit,
1625− running: Boolean,
1626− aborting: Boolean,
1627− enabled: Boolean,
1628− sendOnEnter: Boolean,
1629− onSend: () -> Unit,
1630− onAbort: () -> Unit,
1631− queuedFollowUp: String?,
1632− onQueueFollowUp: (String) -> Unit,
1633− onCancelQueue: () -> Unit,
1634− focusRequester: androidx.compose.ui.focus.FocusRequester,
1635− attachments: List<PendingAttachment>,
1636− staging: Boolean,
1637− onRemoveAttachment: (String) -> Unit,
1638− onPickPhoto: () -> Unit,
1639− onPickFile: () -> Unit,
1640− onCamera: () -> Unit,
1641− onVoice: () -> Unit,
1642− onPasteImage: (List<Uri>) -> Unit,
1643−) {
1644− // Sendable when there's text OR at least one attachment (an image-only prompt is valid).
1645− val hasContent = value.isNotBlank() || attachments.isNotEmpty()
1646− // Full-screen editor state: opened when the user wants more space for a long prompt.
1647− var showFullScreenEditor by rememberSaveable { mutableStateOf(false) }
1648− Surface(tonalElevation = 3.dp, modifier = Modifier.imePadding()) {
1649− Column(modifier = Modifier.fillMaxWidth().windowInsetsPadding(WindowInsets.navigationBars)) {
1650− // A queued follow-up replaces the Stop button with a "queued" chip so the
1651− // user sees their message will be sent when the run finishes, and can cancel.
1652− if (queuedFollowUp != null) {
1653− val editLabel = stringResource(R.string.edit)
1654− Row(
1655− modifier = Modifier
1656− .fillMaxWidth()
1657− .padding(start = 12.dp, top = 6.dp, end = 4.dp),
1658− verticalAlignment = Alignment.CenterVertically,
1659− ) {
1660− // Tapping the chip reloads the queued text into the draft (and clears the
1661− // queue) so a typo spotted while queuing can be fixed without retyping.
1662− Column(
1663− modifier = Modifier
1664− .weight(1f)
1665− .clip(MaterialTheme.shapes.small)
1666− .clickable(role = Role.Button, onClickLabel = editLabel) {
1667− onValueChange(queuedFollowUp)
1668− onCancelQueue()
1669− }
1670− .padding(vertical = 4.dp),
1671− ) {
1672− Text(
1673− stringResource(R.string.queued),
1674− style = MaterialTheme.typography.labelSmall,
1675− color = MaterialTheme.colorScheme.onSurfaceVariant,
1676− )
1677− Text(
1678− queuedFollowUp,
1679− style = MaterialTheme.typography.bodySmall,
1680− color = MaterialTheme.colorScheme.onSurfaceVariant,
1681− maxLines = 1,
1682− overflow = TextOverflow.Ellipsis,
1683− )
1684− }
1685− TextButton(onClick = onCancelQueue, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)) {
1686− Text(stringResource(R.string.cancel))
1687− }
1688− }
1689− }
1690− // Staged attachments: horizontally-scrollable thumbnails/chips, each removable.
1691− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1692− Row(
1693− modifier = Modifier.fillMaxWidth().padding(8.dp),
1694− verticalAlignment = Alignment.Bottom,
1695− ) {
1696− // Attach menu: photo picker, camera, or any file.
1697− var showAttachMenu by remember { mutableStateOf(false) }
1698− Box {
1699− IconButton(onClick = { showAttachMenu = true }, enabled = enabled) {
1700− Icon(Icons.Filled.Add, contentDescription = stringResource(R.string.add_attachment))
1701− }
1702− DropdownMenu(expanded = showAttachMenu, onDismissRequest = { showAttachMenu = false }) {
1703− DropdownMenuItem(
1704− leadingIcon = { Icon(Icons.Filled.PhotoLibrary, contentDescription = null) },
1705− text = { Text(stringResource(R.string.attach_photo)) },
1706− onClick = { showAttachMenu = false; onPickPhoto() },
1707− )
1708− DropdownMenuItem(
1709− leadingIcon = { Icon(Icons.Filled.PhotoCamera, contentDescription = null) },
1710− text = { Text(stringResource(R.string.attach_camera)) },
1711− onClick = { showAttachMenu = false; onCamera() },
1712− )
1713− DropdownMenuItem(
1714− leadingIcon = { Icon(Icons.Filled.Description, contentDescription = null) },
1715− text = { Text(stringResource(R.string.attach_file)) },
1716− onClick = { showAttachMenu = false; onPickFile() },
1717− )
1718− }
1719− }
1720− // Voice dictation: appends recognized speech to the draft.
1721− IconButton(onClick = onVoice, enabled = enabled) {
1722− Icon(Icons.Filled.Mic, contentDescription = stringResource(R.string.voice_input))
1723− }
1724− // Expand to a full-screen editor for long prompts (the inline field caps at 6 lines).
1725− IconButton(onClick = { showFullScreenEditor = true }, enabled = enabled) {
1726− Icon(Icons.Filled.Expand, contentDescription = stringResource(R.string.expand_editor))
1727− }
1728− OutlinedTextField(
1729− value = value,
1730− onValueChange = { v ->
1731− // Cap input length so a huge paste can't stall the UI. Shares are
1732− // capped separately in MainActivity; this guards typed/pasted drafts.
1733− onValueChange(v.take(NetworkConfig.maxDraftLengthChars))
1734− },
1735− modifier = Modifier
1736− .weight(1f)
1737− .focusRequester(focusRequester)
1738− .testTag("chat_input")
1739− // Intercept image content pasted/dropped into the field (keyboard paste
1740− // of a copied screenshot, drag from Files, etc.) and route it through the
1741− // same staging path as the attach menu. Non-image content (text) falls
1742− // through unchanged so normal typing/paste works.
1743− .contentReceiver(
1744− remember {
1745− androidx.compose.foundation.content.ReceiveContentListener { transferable ->
1746− val clipData = transferable.clipEntry?.clipData
1747− if (clipData != null) {
1748− val imageUris = (0 until clipData.itemCount).mapNotNull { i ->
1749− val item = clipData.getItemAt(i)
1750− item.uri?.takeIf { uri ->
1751− item.text == null && uri.toString().let { s ->
1752− s.startsWith("content:") || s.startsWith("file:")
1753− }
1754− }
1755− }
1756− if (imageUris.isNotEmpty()) {
1757− onPasteImage(imageUris)
1758− }
1759− }
1760− transferable
1761− }
1762− },
1763− )
1764− .onPreviewKeyEvent { event ->
1765− if (event.type != KeyEventType.KeyDown || event.key != Key.Enter) return@onPreviewKeyEvent false
1766− // With "Send on Enter" on, Enter sends (Shift+Enter newlines).
1767− // With it off, Enter inserts a newline and Ctrl+Enter sends.
1768− val send = enterShouldSend(
1769− enabled = enabled,
1770− hasContent = hasContent,
1771− sendOnEnter = sendOnEnter,
1772− shift = event.isShiftPressed,
1773− ctrl = event.isCtrlPressed,
1774− )
1775− if (send) {
1776− if (running) onQueueFollowUp(value) else onSend()
1777− true
1778− } else {
1779− false
1780− }
1781− },
1782− // While a run is active a typed message only queues (sends after the run), so
1783− // the placeholder says so instead of the plain "Message…".
1784− placeholder = {
1785− Text(stringResource(if (running) R.string.composer_hint_running else R.string.message_placeholder))
1786− },
1787− enabled = enabled,
1788− maxLines = 6,
1789− // Show a "N / max" countdown once the draft crosses a high fraction of
1790− // the cap, so the user knows a paste is about to be truncated instead
1791− // of being silently cut off. Hidden for normal short prompts to avoid
1792− // clutter under a typical one-line message.
1793− supportingText = {
1794− val threshold = (NetworkConfig.maxDraftLengthChars * NetworkConfig.draftCountdownThresholdFraction).toInt()
1795− if (value.length >= threshold) {
1796− Text(
1797− stringResource(
1798− R.string.draft_chars_remaining,
1799− NetworkConfig.maxDraftLengthChars - value.length,
1800− NetworkConfig.maxDraftLengthChars,
1801− ),
1802− style = MaterialTheme.typography.labelSmall,
1803− color = if (value.length >= NetworkConfig.maxDraftLengthChars) MaterialTheme.colorScheme.error
1804− else MaterialTheme.colorScheme.onSurfaceVariant,
1805− )
1806− }
1807− },
1808− keyboardOptions = KeyboardOptions(
1809− // When "Send on Enter" is on, expose ImeAction.Send so the soft
1810− // keyboard shows a send key — matching the setting's intent and
1811− // giving touch-only users a keyboard send affordance. When off,
1812− // ImeAction.Default keeps the enter/newline key for multi-line input.
1813− imeAction = if (sendOnEnter) ImeAction.Send else ImeAction.Default,
1814− capitalization = KeyboardCapitalization.Sentences,
1815− ),
1816− keyboardActions = KeyboardActions(
1817− onSend = {
1818− if (enabled && hasContent) onSend()
1819− },
1820− ),
1821− )
1822− ComposerTrailingButton(
1823− running = running,
1824− aborting = aborting,
1825− canSend = enabled && hasContent,
1826− canQueue = enabled && value.isNotBlank(),
1827− onSend = onSend,
1828− onAbort = onAbort,
1829− onQueue = { onQueueFollowUp(value) },
1830− )
1831− }
1832− }
1833− if (showFullScreenEditor) {
1834− FullScreenEditor(
1835− value = value,
1836− onValueChange = onValueChange,
1837− onDismiss = { showFullScreenEditor = false },
1838− onSend = {
1839− showFullScreenEditor = false
1840− // Mirror the inline composer's behavior: while a run is active a send
1841− // can't go immediately, so queue the follow-up instead of silently
1842− // dropping it (vm.send() returns false during a run, which previously
1843− // lost the typed message with no feedback).
1844− if (running) onQueueFollowUp(value) else onSend()
1845− },
1846− canSend = enabled && hasContent,
1847− running = running,
1848− attachments = attachments,
1849− onRemoveAttachment = onRemoveAttachment,
1850− staging = staging,
1851− )
1852− }
1853− }
1854−}
1855−
1856−/** Full-screen editor dialog for composing long prompts. Gives the full viewport height to
1857− * the text field (vs the inline 6-line cap) with a Send button and a collapse action. */
1858−@OptIn(ExperimentalMaterial3Api::class)
1859−@Composable
1860−private fun FullScreenEditor(
1861− value: String,
1862− onValueChange: (String) -> Unit,
1863− onDismiss: () -> Unit,
1864− onSend: () -> Unit,
1865− canSend: Boolean,
1866− running: Boolean = false,
1867− attachments: List<PendingAttachment> = emptyList(),
1868− onRemoveAttachment: (String) -> Unit = {},
1869− staging: Boolean = false,
1870−) {
1871− androidx.compose.ui.window.Dialog(
1872− onDismissRequest = onDismiss,
1873− properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
1874− ) {
1875− Scaffold(
1876− topBar = {
1877− androidx.compose.material3.TopAppBar(
1878− title = { Text(stringResource(R.string.message_placeholder)) },
1879− navigationIcon = {
1880− androidx.compose.material3.TextButton(onClick = onDismiss) {
1881− Text(stringResource(R.string.collapse_editor))
1882− }
1883− },
1884− )
1885− },
1886− bottomBar = {
1887− Surface(tonalElevation = 3.dp) {
1888− Row(
1889− modifier = Modifier.fillMaxWidth().imePadding().padding(12.dp),
1890− horizontalArrangement = Arrangement.End,
1891− ) {
1892− androidx.compose.material3.Button(onClick = onSend, enabled = canSend) {
1893− Text(stringResource(if (running) R.string.queue else R.string.send))
1894− }
1895− }
1896− }
1897− },
1898− ) { padding ->
1899− Column(modifier = Modifier.fillMaxSize().padding(padding)) {
1900− // Show staged attachments in the full-screen editor too, so a user who staged
1901− // images then expanded for a long prompt can still see and remove them without
1902− // collapsing first (mirrors the inline composer's AttachmentStrip).
1903− AttachmentStrip(attachments, onRemove = onRemoveAttachment, staging = staging)
1904− OutlinedTextField(
1905− value = value,
1906− onValueChange = { v -> onValueChange(v.take(NetworkConfig.maxDraftLengthChars)) },
1907− modifier = Modifier.fillMaxSize().weight(1f),
1908− placeholder = { Text(stringResource(R.string.message_placeholder)) },
1909− maxLines = Int.MAX_VALUE,
1910− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default, capitalization = KeyboardCapitalization.Sentences),
1911− )
1912− }
1913− }
1914− }
1915−}
1916−
1917−/** Whether a hardware Enter keypress should send: never when disabled/empty; otherwise
1918− * Enter sends (unless Shift) when send-on-Enter is on, else only Ctrl+Enter sends. */
1919−private fun enterShouldSend(
1920− enabled: Boolean,
1921− hasContent: Boolean,
1922− sendOnEnter: Boolean,
1923− shift: Boolean,
1924− ctrl: Boolean,
1925−): Boolean = when {
1926− !enabled || !hasContent -> false
1927− sendOnEnter -> !shift
1928− else -> ctrl
1929−}
1930−
1931−/** The composer's trailing button: while a run is active a Stop (with in-flight spinner),
1932− * preceded by a Queue button when the user has typed a follow-up; otherwise Send. Extracted so
1933− * [ChatInputBar] stays under the complexity threshold. */
1934−@Composable
1935−private fun ComposerTrailingButton(
1936− running: Boolean,
1937− aborting: Boolean,
1938− canSend: Boolean,
1939− canQueue: Boolean,
1940− onSend: () -> Unit,
1941− onAbort: () -> Unit,
1942− onQueue: () -> Unit,
1943−) {
1944− if (running) {
1945− Row(verticalAlignment = Alignment.CenterVertically) {
1946− // While a run is active the trailing action is Stop, so the only send affordance is
1947− // the keyboard's IME action — which is a plain newline when "Send on Enter" is off.
1948− // That leaves a touch-only user with the setting off no way to queue a follow-up
1949− // (Ctrl+Enter needs a hardware keyboard). Surface an explicit Queue button whenever
1950− // there's typed TEXT so queuing is always reachable, without changing the user's
1951− // Enter-inserts-a-newline preference. Gate on typed text — not the send-oriented
1952− // canSend, which is also true for an attachment-only composer — because queuing "" just
1953− // calls setQueuedFollowUp(null), silently cancelling any already-queued follow-up and
1954− // dropping the staged attachment (queued follow-ups don't carry attachments anyway).
1955− if (canQueue) {
1956− IconButton(
1957− onClick = onQueue,
1958− modifier = Modifier.testTag("queue_button"),
1959− ) {
1960− // PlaylistAdd reads as "add to a queue/list" more clearly than a clock
1961− // icon (which can be read as "snooze" or "later"), and isn't confused with
1962− // the Send action sitting right beside the Stop button.
1963− Icon(
1964− Icons.AutoMirrored.Filled.PlaylistAdd,
1965− contentDescription = stringResource(R.string.queue_followup),
1966− )
1967− }
1968− }
1969− // Show a spinner while the abort REST call is in flight so the user sees the stop
1970− // was sent, and disable to prevent a double-tap.
1971− IconButton(
1972− onClick = onAbort,
1973− enabled = !aborting,
1974− modifier = Modifier.padding(start = 4.dp).testTag("stop_button"),
1975− ) {
1976− if (aborting) {
1977− val stopLabel = stringResource(R.string.stop)
1978− CircularProgressIndicator(
1979− Modifier.size(18.dp).semantics { contentDescription = stopLabel },
1980− strokeWidth = 2.dp,
1981− )
1982− } else {
1983− Icon(Icons.Filled.Stop, contentDescription = stringResource(R.string.stop))
1984− }
1985− }
1986− }
1987− } else {
1988− IconButton(
1989− onClick = onSend,
1990− enabled = canSend,
1991− modifier = Modifier.padding(start = 4.dp).testTag("send_button"),
1992− ) {
1993− Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(R.string.send))
1994− }
1995− }
1996−}
1997−
1998−@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
1999−@Composable
2000−private fun EmptyConversation(
2001− onSuggestion: (String) -> Unit,
2002− modifier: Modifier = Modifier,
2003−) {
2004− // A few example prompts so a first-time user has a one-tap path to their first
2005− // message instead of staring at a blank input. Tapping a chip fills the draft
2006− // (without sending) so the user can edit it before sending.
2007− val suggestions = remember {
2008− listOf(
2009− R.string.empty_chat_suggest_1,
2010− R.string.empty_chat_suggest_2,
2011− R.string.empty_chat_suggest_3,
2012− )
2013− }
2014− Column(
2015− modifier = modifier.padding(32.dp),
2016− horizontalAlignment = Alignment.CenterHorizontally,
2017− ) {
2018− Icon(
2019− Icons.Filled.AutoAwesome,
2020− contentDescription = null,
2021− modifier = Modifier.size(48.dp),
2022− tint = MaterialTheme.colorScheme.onSurfaceVariant,
2023− )
2024− Spacer(Modifier.size(16.dp))
2025− Text(
2026− stringResource(R.string.empty_chat_title),
2027− style = MaterialTheme.typography.titleMedium,
2028− )
2029− Spacer(Modifier.size(8.dp))
2030− Text(
2031− stringResource(R.string.empty_chat_hint),
2032− style = MaterialTheme.typography.bodyMedium,
2033− color = MaterialTheme.colorScheme.onSurfaceVariant,
2034− )
2035− Spacer(Modifier.size(20.dp))
2036− // Suggestion chips wrap across rows on narrow screens instead of stacking full-width,
2037− // so a longer localized prompt doesn't push the chips off-screen on a phone.
2038− FlowRow(
2039− modifier = Modifier.fillMaxWidth(),
2040− horizontalArrangement = Arrangement.spacedBy(8.dp),
2041− verticalArrangement = Arrangement.spacedBy(8.dp),
2042− ) {
2043− suggestions.forEach { resId ->
2044− val text = stringResource(resId)
2045− androidx.compose.material3.AssistChip(
2046− onClick = { onSuggestion(text) },
2047− label = { Text(text, style = MaterialTheme.typography.bodyMedium) },
2048− )
2049− }
2050− }
2051− }
2052−}
2053−
2054−/** A banner shown while a revert checkpoint is active, offering an Undo (unrevert). */
2055−@Composable
2056−private fun RevertBanner(onUndo: () -> Unit) {
2057− Surface(
2058− color = MaterialTheme.colorScheme.tertiaryContainer,
2059− tonalElevation = 2.dp,
2060− modifier = Modifier.fillMaxWidth(),
2061− ) {
2062− Row(
2063− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2064− verticalAlignment = Alignment.CenterVertically,
2065− horizontalArrangement = Arrangement.SpaceBetween,
2066− ) {
2067− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2068− Icon(
2069− Icons.Filled.Restore,
2070− contentDescription = null,
2071− tint = MaterialTheme.colorScheme.onTertiaryContainer,
2072− modifier = Modifier.size(18.dp),
2073− )
2074− Text(
2075− stringResource(R.string.reverted_banner),
2076− style = MaterialTheme.typography.bodySmall,
2077− color = MaterialTheme.colorScheme.onTertiaryContainer,
2078− modifier = Modifier.padding(start = 8.dp),
2079− )
2080− }
2081− TextButton(onClick = onUndo) { Text(stringResource(R.string.undo)) }
2082− }
2083− }
2084−}
2085−
2086−/** A banner shown while messages composed offline are queued in the outbox, with a
2087− * "Send now" nudge and a discard. Shows a spinner while the queue is flushing. */
2088−@Composable
2089−private fun OutboxBanner(
2090− count: Int,
2091− sending: Boolean,
2092− onFlush: () -> Unit,
2093− onDiscard: () -> Unit,
2094−) {
2095− Surface(
2096− color = MaterialTheme.colorScheme.secondaryContainer,
2097− tonalElevation = 2.dp,
2098− modifier = Modifier.fillMaxWidth(),
2099− ) {
2100− Row(
2101− modifier = Modifier.fillMaxWidth().padding(start = 12.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),
2102− verticalAlignment = Alignment.CenterVertically,
2103− horizontalArrangement = Arrangement.SpaceBetween,
2104− ) {
2105− Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f)) {
2106− if (sending) {
2107− CircularProgressIndicator(
2108− Modifier.size(16.dp),
2109− strokeWidth = 2.dp,
2110− color = MaterialTheme.colorScheme.onSecondaryContainer,
2111− )
2112− Spacer(Modifier.size(8.dp))
2113− }
2114− Text(
2115− if (sending) {
2116− stringResource(R.string.outbox_sending)
2117− } else {
2118− val res = if (count == 1) R.string.outbox_pending_one else R.string.outbox_pending_many
2119− stringResource(res, count)
2120− },
2121− style = MaterialTheme.typography.bodySmall,
2122− color = MaterialTheme.colorScheme.onSecondaryContainer,
2123− )
2124− }
2125− if (!sending) {
2126− TextButton(onClick = onFlush) { Text(stringResource(R.string.outbox_flush)) }
2127− TextButton(onClick = onDiscard) {
2128− Text(stringResource(R.string.outbox_discard_all), color = MaterialTheme.colorScheme.error)
2129− }
2130− }
2131− }
2132− }
2133−}
2134−
2135−/** Prompt for a one-off shell command to run in the session's worktree. */
2136−@Composable
2137−private fun ShellCommandDialog(onDismiss: () -> Unit, onRun: (String) -> Unit) {
2138− var command by rememberSaveable { mutableStateOf("") }
2139− AlertDialog(
2140− onDismissRequest = onDismiss,
2141− title = { Text(stringResource(R.string.run_shell_command)) },
2142− text = {
2143− OutlinedTextField(
2144− value = command,
2145− onValueChange = { command = it },
2146− modifier = Modifier.fillMaxWidth(),
2147− placeholder = { Text(stringResource(R.string.shell_command_hint)) },
2148− label = { Text(stringResource(R.string.shell_command_label)) },
2149− singleLine = true,
2150− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2151− keyboardActions = KeyboardActions(onDone = { if (command.isNotBlank()) onRun(command.trim()) }),
2152− )
2153− },
2154− confirmButton = {
2155− TextButton(
2156− onClick = { if (command.isNotBlank()) onRun(command.trim()) },
2157− enabled = command.isNotBlank(),
2158− ) { Text(stringResource(R.string.run)) }
2159− },
2160− dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } },
2161− )
2162−}
2163−
2164−/**
2165− * Change signal for the auto-scroll-on-stream watcher. Primitive fields avoid the
2166− * boxing `Triple<Int, Int, Boolean>` would impose on every snapshot evaluation, and
2167− * equality is structural so `snapshotFlow` emits only when something relevant changes.
2168− */
2169−private data class AutoScrollSignal(val size: Int, val lastTextLength: Int, val pinned: Boolean)
2170−
2171−/** Length of the streaming content carried by [part], driving auto-scroll as it grows.
2172− * Covers text, reasoning, and tool output so a pinned view keeps following non-text
2173− * streaming, not just plain assistant text. O(1). */
2174−private fun streamingContentLength(part: Part?): Int = when (part) {
2175− is TextPart -> part.text.length
2176− is ReasoningPart -> part.text.length
2177− is ToolPart -> when (val st = part.state) {
2178− is ToolCompleted -> st.output?.length ?: 0
2179− is ToolError -> st.error?.length ?: 0
2180− is ToolRunning -> st.title?.length ?: 0
2181− else -> 0
2182− }
2183− else -> 0
2184−}
2185−
2186−/** Rename dialog for the currently-open session. Mirrors the SessionListScreen rename
2187− * dialog but lives in the chat screen so the user can rename without backing out to
2188− * the list. Pre-filled with the current title; the cap matches the list dialog. */
2189−@Composable
2190−private fun RenameSessionChatDialog(
2191− initialTitle: String,
2192− onDismiss: () -> Unit,
2193− onConfirm: (String) -> Unit,
2194−) {
2195− // Seed the field once (no key input) so a later external title change — e.g. opencode
2196− // auto-generating a session title after the first prompt, arriving via SessionUpdated —
2197− // doesn't re-initialize the box and discard the user's in-progress edit.
2198− var title by rememberSaveable { mutableStateOf(initialTitle) }
2199− AlertDialog(
2200− onDismissRequest = onDismiss,
2201− title = { Text(stringResource(R.string.rename_session_chat)) },
2202− text = {
2203− OutlinedTextField(
2204− value = title,
2205− onValueChange = { v -> title = v.take(NetworkConfig.maxSessionTitleChars) },
2206− modifier = Modifier.fillMaxWidth(),
2207− placeholder = { Text(stringResource(R.string.session_title_hint)) },
2208− label = { Text(stringResource(R.string.rename_session_chat)) },
2209− singleLine = true,
2210− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
2211− keyboardActions = KeyboardActions(onDone = { if (title.isNotBlank()) onConfirm(title.trim()) }),
2212− )
2213− },
2214− confirmButton = {
2215− TextButton(onClick = { if (title.isNotBlank()) onConfirm(title.trim()) }, enabled = title.isNotBlank()) {
2216− Text(stringResource(R.string.save))
2217− }
2218− },
2219− dismissButton = {
2220− TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
2221− },
2222− )
2223−}
2224−
2225−/**
2226− * A single item in the chat message list — either a [Message] bubble or a day
2227− * [Separator] inserted before the first message of a new day. The separator shifts
2228− * the LazyColumn indices vs. the raw messages list, so scroll-target math must use
2229− * the [List] of these items (not `messages.size`/`lastIndex`).
2230− */
2231−private sealed interface MessageListItem {
2232− val key: Any
2233− val contentType: Any
2234−
2235− data class Message(val message: MessageWithParts, override val key: Any) : MessageListItem {
2236− override val contentType: Any get() = message.info::class
2237− }
2238−
2239− data class Separator(val label: String, val ordinal: Int) : MessageListItem {
2240− // Key on the day-occurrence ordinal, not the label: two non-contiguous groups
2241− // can share a label (e.g. an untimestamped message — empty label — between two
2242− // same-day messages, or two untimestamped groups), and a label-only key would
2243− // then collide, which makes LazyColumn throw on duplicate keys. The ordinal is
2244− // stable for a given message ordering so slots aren't needlessly recreated.
2245− override val key: Any get() = "sep_${ordinal}_$label"
2246− // Separators share a contentType so the LazyColumn can recycle their slots.
2247− override val contentType: Any get() = "separator"
2248− }
2249−}
2250−
2251−/**
2252− * Build the interleaved list of [MessageListItem]s for the message list, inserting a
2253− * [MessageListItem.Separator] before the first message of each new calendar day. Uses
2254− * the message's `time.created` (falling back to `updated` then `completed`) to bucket.
2255− * Messages with no timestamp are grouped under an empty-label separator only if they
2256− * start the list, so a server that omits timestamps doesn't suppress the first divider.
2257− *
2258− * [todayLabel]/[yesterdayLabel] are resolved by the caller (a @Composable can't call
2259− * stringResource from inside this plain function) and used for the "Today"/"Yesterday"
2260− * labels; older days fall back to a locale-stable medium-date format.
2261− */
2262−private fun buildMessageListItems(
2263− messages: List<MessageWithParts>,
2264− todayLabel: String,
2265− yesterdayLabel: String,
2266−): List<MessageListItem> {
2267− if (messages.isEmpty()) return emptyList()
2268− val today = java.time.LocalDate.now(java.time.ZoneId.systemDefault())
2269− val dateFmt = mediumDateFormat()
2270− val result = ArrayList<MessageListItem>(messages.size + 4)
2271− val seenKeys = HashSet<String>(messages.size * 2)
2272− var lastDayKey: String? = null
2273− var sepOrdinal = 0
2274− var emptyIdOrdinal = 0
2275− var first = true
2276− for (message in messages) {
2277− val ts = message.info.time?.created ?: message.info.time?.updated ?: message.info.time?.completed
2278− val dayKey = ts?.let { dayKey(it) } ?: ""
2279− // Emit a separator before the very first message (so a leading un-timestamped message
2280− // still gets the first divider, empty label and all), and thereafter only when crossing
2281− // into a new NON-empty calendar day. An un-timestamped message mid-list (empty key)
2282− // neither emits its own separator nor resets the day — otherwise a following same-day
2283− // message would see a "" -> "<today>" transition and emit a duplicate "Today" header.
2284− if (first || (dayKey.isNotEmpty() && dayKey != lastDayKey)) {
2285− result.add(MessageListItem.Separator(dayLabel(dayKey, ts ?: 0L, today, todayLabel, yesterdayLabel, dateFmt), sepOrdinal++))
2286− }
2287− if (dayKey.isNotEmpty()) lastDayKey = dayKey
2288− first = false
2289− // Most messages have a unique non-empty id. An unrecognized-role message can carry an
2290− // empty id — and the reducer intentionally keeps several such messages as distinct
2291− // holders — so give each a stable synthetic key and defensively de-collide any remaining
2292− // duplicate; otherwise LazyColumn throws on a duplicate key and the whole screen crashes.
2293− var key = message.info.id.ifEmpty { "msg-empty-${emptyIdOrdinal++}" }
2294− if (!seenKeys.add(key)) {
2295− var suffix = 1
2296− while (!seenKeys.add("$key#$suffix")) suffix++
2297− key = "$key#$suffix"
2298− }
2299− result.add(MessageListItem.Message(message, key))
2300− }
2301− return result
2302−}
2303−
2304−/**
2305− * A stable bucket key for a timestamp's calendar day (epoch-days as a string).
2306− *
2307− * [buildMessageListItems] re-runs on every streaming snapshot (the memo is keyed on the
2308− * whole `messages` list, which must stay so the live message's fresh parts render), so a
2309− * naive implementation would re-allocate an `Instant`/`ZonedDateTime`/`LocalDate` for
2310− * every message on every token. Message timestamps are immutable once assigned, so we
2311− * memoize the parse per epoch-millis: after the first snapshot, each unchanged message is
2312− * a cheap hash lookup. Bounded LRU (access-order) caps memory; only touched on the main
2313− * thread during composition, so the coarse lock is uncontended.
2314− */
2315−private val dayKeyCache = object : LinkedHashMap<Long, String>(128, 0.75f, true) {
2316− override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, String>): Boolean = size > 1024
2317−}
2318−
2319−private fun dayKey(epochMillis: Long): String = synchronized(dayKeyCache) {
2320− dayKeyCache.getOrPut(epochMillis) {
2321− java.time.Instant.ofEpochMilli(epochMillis)
2322− .atZone(java.time.ZoneId.systemDefault()).toLocalDate().toEpochDay().toString()
2323− }
2324−}
2325−
2326−// The medium-date formatter is an ICU locale lookup; cache one instance instead of
2327−// allocating a fresh one per buildMessageListItems call, rebuilding only if the default
2328−// locale changes at runtime. Main-thread-only, so no synchronization is needed.
2329−private var cachedDateFmt: java.text.DateFormat? = null
2330−private var cachedDateFmtLocale: java.util.Locale? = null
2331−
2332−private fun mediumDateFormat(): java.text.DateFormat {
2333− val locale = java.util.Locale.getDefault()
2334− val existing = cachedDateFmt
2335− if (existing != null && cachedDateFmtLocale == locale) return existing
2336− return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM).also {
2337− cachedDateFmt = it
2338− cachedDateFmtLocale = locale
2339− }
2340−}
2341−
2342−/**
2343− * Resolve a day-key back to a human-readable label. "Today" / "Yesterday" for the
2344− * recent days, otherwise a locale-stable medium-date format. Returns an empty string
2345− * when [dayKey] is empty (no timestamp) so no separator is rendered for un-timestamped
2346− * messages.
2347− */
2348−private fun dayLabel(
2349− dayKey: String,
2350− ts: Long,
2351− today: java.time.LocalDate,
2352− todayLabel: String,
2353− yesterdayLabel: String,
2354− dateFmt: java.text.DateFormat,
2355−): String {
2356− if (dayKey.isEmpty()) return ""
2357− val epochDay = dayKey.toLongOrNull() ?: return ""
2358− val date = java.time.LocalDate.ofEpochDay(epochDay)
2359− return when {
2360− date == today -> todayLabel
2361− date == today.minusDays(1) -> yesterdayLabel
2362− else -> dateFmt.format(java.util.Date(ts))
2363− }
2364−}
2365−
2366−/**
2367− * A centered day divider in the message list. Renders nothing for an empty label
2368− * (the no-timestamp case) so un-timestamped messages don't get a stray blank divider.
2369− */
2370−@Composable
2371−private fun DateSeparator(label: String) {
2372− if (label.isBlank()) return
2373− Row(
2374− modifier = Modifier.fillMaxWidth(),
2375− horizontalArrangement = Arrangement.Center,
2376− ) {
2377− Surface(
2378− color = MaterialTheme.colorScheme.surfaceVariant,
2379− shape = MaterialTheme.shapes.small,
2380− ) {
2381− Text(
2382− label,
2383− style = MaterialTheme.typography.labelSmall,
2384− color = MaterialTheme.colorScheme.onSurfaceVariant,
2385− modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),
2386− )
2387− }
2388− }
2389−}