@@ -1,57 +1,36 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
3−import android.content.ClipData
4−import android.content.ClipboardManager
5−import android.content.Context
6−import android.widget.Toast
7import androidx.compose.animation.AnimatedVisibility
3import androidx.compose.animation.AnimatedVisibility
8−import androidx.compose.animation.core.RepeatMode
9−import androidx.compose.animation.core.animateFloat
10−import androidx.compose.animation.core.infiniteRepeatable
11−import androidx.compose.animation.core.rememberInfiniteTransition
12−import androidx.compose.animation.core.tween
13import androidx.compose.animation.fadeIn
4import androidx.compose.animation.fadeIn
14import androidx.compose.animation.fadeOut
5import androidx.compose.animation.fadeOut
15import androidx.compose.animation.scaleIn
6import androidx.compose.animation.scaleIn
16import androidx.compose.animation.scaleOut
7import androidx.compose.animation.scaleOut
17−import androidx.compose.foundation.ExperimentalFoundationApi
18import androidx.compose.foundation.background
8import androidx.compose.foundation.background
19−import androidx.compose.foundation.clickable
20−import androidx.compose.foundation.combinedClickable
21import androidx.compose.foundation.layout.Arrangement
9import androidx.compose.foundation.layout.Arrangement
22import androidx.compose.foundation.layout.Box
10import androidx.compose.foundation.layout.Box
23import androidx.compose.foundation.layout.BoxScope
11import androidx.compose.foundation.layout.BoxScope
24import androidx.compose.foundation.layout.Column
12import androidx.compose.foundation.layout.Column
25import androidx.compose.foundation.layout.Row
13import androidx.compose.foundation.layout.Row
26−import androidx.compose.foundation.layout.Spacer
27import androidx.compose.foundation.layout.fillMaxSize
14import androidx.compose.foundation.layout.fillMaxSize
28import androidx.compose.foundation.layout.fillMaxWidth
15import androidx.compose.foundation.layout.fillMaxWidth
29−import androidx.compose.foundation.layout.heightIn
30import androidx.compose.foundation.layout.PaddingValues
16import androidx.compose.foundation.layout.PaddingValues
31−import androidx.compose.foundation.layout.WindowInsets
32−import androidx.compose.foundation.layout.ime
33import androidx.compose.foundation.layout.imePadding
17import androidx.compose.foundation.layout.imePadding
34import androidx.compose.foundation.layout.padding
18import androidx.compose.foundation.layout.padding
35import androidx.compose.foundation.layout.size
19import androidx.compose.foundation.layout.size
36import androidx.compose.foundation.lazy.LazyColumn
20import androidx.compose.foundation.lazy.LazyColumn
37−import androidx.compose.foundation.lazy.itemsIndexed
21+import androidx.compose.foundation.lazy.items
38import androidx.compose.foundation.lazy.rememberLazyListState
22import androidx.compose.foundation.lazy.rememberLazyListState
39import androidx.compose.foundation.shape.CircleShape
23import androidx.compose.foundation.shape.CircleShape
40−import androidx.compose.foundation.shape.RoundedCornerShape
41import androidx.compose.foundation.text.KeyboardActions
24import androidx.compose.foundation.text.KeyboardActions
42import androidx.compose.foundation.text.KeyboardOptions
25import androidx.compose.foundation.text.KeyboardOptions
43import androidx.compose.material.icons.Icons
26import androidx.compose.material.icons.Icons
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
45import androidx.compose.material.icons.automirrored.filled.Send
28import androidx.compose.material.icons.automirrored.filled.Send
46−import androidx.compose.material.icons.filled.ChatBubbleOutline
47−import androidx.compose.material.icons.filled.Close
48import androidx.compose.material.icons.filled.KeyboardArrowDown
29import androidx.compose.material.icons.filled.KeyboardArrowDown
49−import androidx.compose.material.icons.filled.KeyboardArrowUp
50import androidx.compose.material.icons.filled.Stop
30import androidx.compose.material.icons.filled.Stop
51import androidx.compose.material3.CircularProgressIndicator
31import androidx.compose.material3.CircularProgressIndicator
52import androidx.compose.material3.ExperimentalMaterial3Api
32import androidx.compose.material3.ExperimentalMaterial3Api
53import androidx.compose.material3.FilledIconButton
33import androidx.compose.material3.FilledIconButton
54−import androidx.compose.material3.FilledTonalButton
55import androidx.compose.material3.FloatingActionButton
34import androidx.compose.material3.FloatingActionButton
56import androidx.compose.material3.Icon
35import androidx.compose.material3.Icon
57import androidx.compose.material3.IconButton
36import androidx.compose.material3.IconButton
@@ -61,7 +40,6 @@ import androidx.compose.material3.OutlinedTextField
61import androidx.compose.material3.Scaffold
40import androidx.compose.material3.Scaffold
62import androidx.compose.material3.Surface
41import androidx.compose.material3.Surface
63import androidx.compose.material3.Text
42import androidx.compose.material3.Text
64−import androidx.compose.material3.TextButton
65import androidx.compose.material3.TopAppBar
43import androidx.compose.material3.TopAppBar
66import androidx.compose.runtime.Composable
44import androidx.compose.runtime.Composable
67import androidx.compose.runtime.LaunchedEffect
45import androidx.compose.runtime.LaunchedEffect
@@ -75,13 +53,8 @@ import androidx.compose.ui.Alignment
75import androidx.compose.ui.Modifier
53import androidx.compose.ui.Modifier
76import androidx.compose.ui.draw.clip
54import androidx.compose.ui.draw.clip
77import androidx.compose.ui.hapticfeedback.HapticFeedbackType
55import androidx.compose.ui.hapticfeedback.HapticFeedbackType
78−import androidx.compose.ui.platform.LocalClipboardManager
79−import androidx.compose.ui.platform.LocalContext
80−import androidx.compose.ui.platform.LocalDensity
81import androidx.compose.ui.platform.LocalHapticFeedback
56import androidx.compose.ui.platform.LocalHapticFeedback
82−import androidx.compose.ui.text.font.FontStyle
83import androidx.compose.ui.text.input.ImeAction
57import androidx.compose.ui.text.input.ImeAction
84−import androidx.compose.ui.text.style.TextAlign
85import androidx.compose.ui.text.style.TextOverflow
58import androidx.compose.ui.text.style.TextOverflow
86import androidx.compose.ui.unit.dp
59import androidx.compose.ui.unit.dp
87import kotlinx.coroutines.launch
60import kotlinx.coroutines.launch
@@ -89,17 +62,11 @@ import soy.iko.opencode.core.Event
89import soy.iko.opencode.core.UiState
62import soy.iko.opencode.core.UiState
90import soy.iko.opencode.ui.components.MessageBubble
63import soy.iko.opencode.ui.components.MessageBubble
92−@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
65+@OptIn(ExperimentalMaterial3Api::class)
93@Composable
66@Composable
94fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
67fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
95 val listState = rememberLazyListState()
68 val listState = rememberLazyListState()
96 val coroutineScope = rememberCoroutineScope()
69 val coroutineScope = rememberCoroutineScope()
97− val context = LocalContext.current
99− // Hide the jump-to-bottom FAB while the keyboard is up: it would otherwise
100− // sit over the top of the IME. Reading the ime inset bottom during composition
101− // observes snapshot state, so this flips as the keyboard opens/closes.
102− val isImeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
104 // Show a jump-to-bottom button once the user scrolls up away from the latest
71 // Show a jump-to-bottom button once the user scrolls up away from the latest
105 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
72 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -113,12 +80,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
116− // Offer a jump-to-top shortcut once the conversation is long and the user has
117− // scrolled a few messages down — saves flick-scrolling back through history.
118− val showScrollTop by remember {
119− derivedStateOf { state.messages.size > 10 && listState.firstVisibleItemIndex > 3 }
122 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
83 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
123 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
84 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
124 var lastSeenCount by remember { mutableStateOf(0) }
85 var lastSeenCount by remember { mutableStateOf(0) }
@@ -148,20 +109,10 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
148 topBar = {
109 topBar = {
149 TopAppBar(
110 TopAppBar(
150 title = {
111 title = {
151− val title = state.currentSessionTitle.ifEmpty { "Chat" }
153− text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
113+ text = state.currentSessionTitle.ifEmpty { "Chat" },
154 maxLines = 1,
114 maxLines = 1,
155 overflow = TextOverflow.Ellipsis,
115 overflow = TextOverflow.Ellipsis,
156− modifier = Modifier.combinedClickable(
157− onClick = { dispatch(Event.NavigateToSessions) },
159− state.currentSessionId?.let { id ->
160− copyToClipboard(context, id)
161− Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
167 navigationIcon = {
118 navigationIcon = {
@@ -183,7 +134,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
183 ChatInputBar(
134 ChatInputBar(
184 draft = state.draft,
135 draft = state.draft,
185 generating = state.generating,
136 generating = state.generating,
186− loading = state.loading && state.messages.isEmpty(),
187 onDraftChange = { dispatch(Event.DraftChanged(it)) },
137 onDraftChange = { dispatch(Event.DraftChanged(it)) },
188 onSend = { dispatch(Event.SendMessage(state.draft)) },
138 onSend = { dispatch(Event.SendMessage(state.draft)) },
189 onStop = { dispatch(Event.CancelGeneration) },
139 onStop = { dispatch(Event.CancelGeneration) },
@@ -197,86 +147,35 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
197 if (state.loading && state.messages.isEmpty()) {
147 if (state.loading && state.messages.isEmpty()) {
198 LinearProgressIndicator(Modifier.fillMaxWidth())
148 LinearProgressIndicator(Modifier.fillMaxWidth())
200− if (state.error != null && state.messages.isNotEmpty()) {
202− message = state.error,
203− onDismiss = { dispatch(Event.DismissError) },
206 Box(Modifier.fillMaxWidth().weight(1f)) {
150 Box(Modifier.fillMaxWidth().weight(1f)) {
207 if (state.messages.isEmpty() && !state.loading) {
151 if (state.messages.isEmpty() && !state.loading) {
153+ text = "Send a message to start the conversation.",
154+ style = MaterialTheme.typography.bodyMedium,
155+ color = MaterialTheme.colorScheme.onSurfaceVariant,
209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
156 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210− horizontalAlignment = Alignment.CenterHorizontally,
213− Icons.Filled.ChatBubbleOutline,
214− contentDescription = null,
215− modifier = Modifier.size(48.dp),
216− tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
218− Spacer(Modifier.size(16.dp))
220− text = "Send a message to start the conversation.",
221− style = MaterialTheme.typography.bodyMedium,
222− color = MaterialTheme.colorScheme.onSurfaceVariant,
223− textAlign = TextAlign.Center,
227 LazyColumn(
159 LazyColumn(
228 state = listState,
160 state = listState,
229 modifier = Modifier.fillMaxSize(),
161 modifier = Modifier.fillMaxSize(),
230 contentPadding = PaddingValues(vertical = 8.dp),
162 contentPadding = PaddingValues(vertical = 8.dp),
232− itemsIndexed(state.messages, key = { _, message -> message.id }) { index, message ->
164+ items(state.messages, key = { it.id }) { message ->
233− // Insert a date separator whenever a message falls on a different
234− // calendar day than the one before it (and above the first message).
235− val previous = state.messages.getOrNull(index - 1)
236− if (shouldShowDateSeparator(previous, message)) {
237− DateSeparator(message.time)
239− val sameSenderAsPrevious = index > 0 && state.messages[index - 1].isUser == message.isUser
240− MessageBubble(
165+ MessageBubble(message)
242− onRetry = { dispatch(Event.SendMessage(message.text)) },
243− compactSpacing = sameSenderAsPrevious,
246− // While the assistant is spinning up but hasn't emitted a streaming
247− // message yet (only the user's message is present), show a typing
248− // indicator so the wait doesn't look like a stall.
249− if (state.generating && state.messages.none { it.streaming }) {
250− item(key = "typing-indicator") {
255 ScrollToBottomButton(
168 ScrollToBottomButton(
256− visible = showScrollButton && !isImeVisible,
169+ visible = showScrollButton,
257 showBadge = hasUnseenMessages,
170 showBadge = hasUnseenMessages,
258 onClick = {
171 onClick = {
259 coroutineScope.launch {
172 coroutineScope.launch {
260 if (state.messages.isNotEmpty()) {
173 if (state.messages.isNotEmpty()) {
261− // When the typing indicator is showing it occupies the item
262− // just past the last message, so scroll one further to reach it.
263− val target = if (state.generating && state.messages.none { it.streaming })
266− state.messages.size - 1
174+ listState.animateScrollToItem(state.messages.size - 1)
267− listState.animateScrollToItem(target)
273− visible = showScrollTop,
275− coroutineScope.launch {
276− listState.animateScrollToItem(0)
@@ -316,123 +215,6 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
319−// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
320−// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
322−private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
325− modifier = Modifier.align(Alignment.TopStart),
326− enter = scaleIn() + fadeIn(),
327− exit = scaleOut() + fadeOut(),
329− Box(Modifier.padding(16.dp)) {
330− FloatingActionButton(
332− modifier = Modifier.size(44.dp),
335− Icons.Filled.KeyboardArrowUp,
336− contentDescription = "Scroll to top",
343−private fun copyToClipboard(context: Context, text: String) {
344− val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
345− clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
348−private val dateSeparatorFormat = java.time.format.DateTimeFormatter.ofPattern("MMM d")
350−/** Convert an epoch-millis timestamp to the local calendar day it falls on. */
351−private fun localDayOf(epochMillis: Long): java.time.LocalDate =
352− java.time.Instant.ofEpochMilli(epochMillis)
353− .atZone(java.time.ZoneId.systemDefault())
357− * A separator is shown above a message when it starts a new calendar day — i.e. the
358− * first timestamped message, or one whose day differs from the previous message's.
359− * Messages without a valid time (time <= 0) never get one.
361−private fun shouldShowDateSeparator(previous: soy.iko.opencode.core.MessageView?, current: soy.iko.opencode.core.MessageView): Boolean {
362− if (current.time <= 0) return false
363− if (previous == null || previous.time <= 0) return true
364− return localDayOf(previous.time) != localDayOf(current.time)
367−/** Human-friendly day label: "Today", "Yesterday", or "MMM d" (e.g. "Jul 8"). */
368−private fun dateSeparatorLabel(day: java.time.LocalDate): String {
369− val today = java.time.LocalDate.now()
372− today.minusDays(1) -> "Yesterday"
373− else -> day.format(dateSeparatorFormat)
378−private fun DateSeparator(epochMillis: Long) {
380− text = dateSeparatorLabel(localDayOf(epochMillis)),
381− style = MaterialTheme.typography.labelSmall,
382− color = MaterialTheme.colorScheme.onSurfaceVariant,
383− textAlign = TextAlign.Center,
384− modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
388−// Assistant-style bubble with three sequentially-pulsing dots, shown as a stand-in
389−// until the real streaming reply starts. Mirrors MessageBubble's left-aligned,
390−// surfaceVariant look so it reads as an incoming message.
392−private fun TypingIndicator() {
393− val shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp, bottomStart = 4.dp, bottomEnd = 16.dp)
394− val transition = rememberInfiniteTransition(label = "typing")
396− modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
397− horizontalArrangement = Arrangement.Start,
402− .background(MaterialTheme.colorScheme.surfaceVariant)
403− .padding(horizontal = 14.dp, vertical = 12.dp),
404− verticalAlignment = Alignment.CenterVertically,
405− horizontalArrangement = Arrangement.spacedBy(6.dp),
409− style = MaterialTheme.typography.bodyMedium.copy(fontStyle = FontStyle.Italic),
410− color = MaterialTheme.colorScheme.onSurfaceVariant,
412− Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
413− // Stagger the three dots so they fade in and out in sequence.
414− listOf(0, 150, 300).forEach { staggerMs ->
415− val alpha by transition.animateFloat(
416− initialValue = 0.2f,
418− animationSpec = infiniteRepeatable(
419− animation = tween(durationMillis = 600, delayMillis = staggerMs),
420− repeatMode = RepeatMode.Reverse,
428− .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)),
436@Composable
218@Composable
437private fun ReconnectingBanner() {
219private fun ReconnectingBanner() {
@@ -458,109 +240,35 @@ private fun ReconnectingBanner() {
462−private fun ErrorBanner(message: String, onDismiss: () -> Unit) {
464− modifier = Modifier.fillMaxWidth(),
465− color = MaterialTheme.colorScheme.errorContainer,
468− modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 6.dp, bottom = 6.dp, end = 4.dp),
469− verticalAlignment = Alignment.CenterVertically,
470− horizontalArrangement = Arrangement.spacedBy(8.dp),
474− style = MaterialTheme.typography.bodySmall,
475− color = MaterialTheme.colorScheme.onErrorContainer,
476− modifier = Modifier.weight(1f),
478− IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
481− contentDescription = "Dismiss error",
482− tint = MaterialTheme.colorScheme.onErrorContainer,
483− modifier = Modifier.size(18.dp),
490@Composable
243@Composable
491private fun ChatInputBar(
244private fun ChatInputBar(
492 draft: String,
245 draft: String,
493 generating: Boolean,
246 generating: Boolean,
495 onDraftChange: (String) -> Unit,
247 onDraftChange: (String) -> Unit,
496 onSend: () -> Unit,
248 onSend: () -> Unit,
497 onStop: () -> Unit,
249 onStop: () -> Unit,
499 val haptic = LocalHapticFeedback.current
251 val haptic = LocalHapticFeedback.current
500− val clipboardManager = LocalClipboardManager.current
501 Surface(tonalElevation = 3.dp) {
252 Surface(tonalElevation = 3.dp) {
503− modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
506− modifier = Modifier.fillMaxWidth(),
254+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
507 verticalAlignment = Alignment.Bottom,
255 verticalAlignment = Alignment.Bottom,
508 horizontalArrangement = Arrangement.spacedBy(8.dp),
256 horizontalArrangement = Arrangement.spacedBy(8.dp),
510 OutlinedTextField(
258 OutlinedTextField(
511 value = draft,
259 value = draft,
512 onValueChange = onDraftChange,
260 onValueChange = onDraftChange,
513− modifier = Modifier.weight(1f).heightIn(min = 48.dp),
261+ modifier = Modifier.weight(1f),
515 placeholder = { Text("Message opencode…") },
262 placeholder = { Text("Message opencode…") },
516 maxLines = 5,
263 maxLines = 5,
517− // Offer a quick way to wipe the draft once there's something to clear
518− // and we're not mid-generation (where the field is a poor place to fuss).
519− trailingIcon = if (draft.isNotEmpty() && !generating) {
522− onClick = { onDraftChange("") },
523− modifier = Modifier.size(20.dp),
527− contentDescription = "Clear draft",
528− modifier = Modifier.size(16.dp),
535− // Surface a running count once the draft gets long, so the user has a
536− // sense of scale before sending a wall of text.
537− supportingText = if (draft.length > 500) {
540− text = "${draft.length} characters",
541− style = MaterialTheme.typography.labelSmall,
542− color = MaterialTheme.colorScheme.onSurfaceVariant,
543− textAlign = TextAlign.End,
544− modifier = Modifier.fillMaxWidth(),
550 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
264 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551 keyboardActions = KeyboardActions(onSend = {
265 keyboardActions = KeyboardActions(onSend = {
552− if (!generating && !loading && draft.isNotBlank()) onSend()
266+ if (!generating && draft.isNotBlank()) onSend()
555 if (generating) {
269 if (generating) {
556− FilledTonalButton(onClick = onStop) {
270+ FilledIconButton(onClick = onStop) {
559− contentDescription = null,
271+ Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
560− modifier = Modifier.size(18.dp),
562− Spacer(Modifier.size(6.dp))
566 FilledIconButton(
274 FilledIconButton(
@@ -568,23 +276,11 @@ private fun ChatInputBar(
568 haptic.performHapticFeedback(HapticFeedbackType.LongPress)
276 haptic.performHapticFeedback(HapticFeedbackType.LongPress)
571− enabled = draft.isNotBlank() && !loading,
279+ enabled = draft.isNotBlank(),
573 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
281 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
577− // With nothing typed yet, offer a one-tap way to drop in clipboard contents.
578− if (draft.isEmpty() && !generating && !loading) {
581− clipboardManager.getText()?.text?.let { onDraftChange(it) }
583− contentPadding = PaddingValues(0.dp),