@@ -1,87 +1,43 @@
11package soy.iko.opencode.ui.screens
22
3−import android.content.ClipData
4−import android.content.ClipboardManager
5−import android.content.Context
6−import android.widget.Toast
7−import 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
13−import androidx.compose.animation.fadeIn
14−import androidx.compose.animation.fadeOut
15−import androidx.compose.animation.scaleIn
16−import androidx.compose.animation.scaleOut
17−import androidx.compose.foundation.ExperimentalFoundationApi
18−import androidx.compose.foundation.background
19−import androidx.compose.foundation.clickable
20−import androidx.compose.foundation.combinedClickable
213import androidx.compose.foundation.layout.Arrangement
224import androidx.compose.foundation.layout.Box
23−import androidx.compose.foundation.layout.BoxScope
245import androidx.compose.foundation.layout.Column
256import androidx.compose.foundation.layout.Row
26−import androidx.compose.foundation.layout.Spacer
277import androidx.compose.foundation.layout.fillMaxSize
288import androidx.compose.foundation.layout.fillMaxWidth
29−import androidx.compose.foundation.layout.heightIn
309import androidx.compose.foundation.layout.PaddingValues
31−import androidx.compose.foundation.layout.WindowInsets
32−import androidx.compose.foundation.layout.ime
3310import androidx.compose.foundation.layout.imePadding
3411import androidx.compose.foundation.layout.padding
3512import androidx.compose.foundation.layout.size
3613import androidx.compose.foundation.lazy.LazyColumn
37−import androidx.compose.foundation.lazy.itemsIndexed
14+import androidx.compose.foundation.lazy.items
3815import androidx.compose.foundation.lazy.rememberLazyListState
39−import androidx.compose.foundation.shape.CircleShape
40−import androidx.compose.foundation.shape.RoundedCornerShape
41−import androidx.compose.foundation.text.KeyboardActions
42−import androidx.compose.foundation.text.KeyboardOptions
4316import androidx.compose.material.icons.Icons
4417import androidx.compose.material.icons.automirrored.filled.ArrowBack
4518import androidx.compose.material.icons.automirrored.filled.Send
46−import androidx.compose.material.icons.filled.ChatBubbleOutline
47−import androidx.compose.material.icons.filled.Close
4819import androidx.compose.material.icons.filled.KeyboardArrowDown
49−import androidx.compose.material.icons.filled.KeyboardArrowUp
5020import androidx.compose.material.icons.filled.Stop
5121import androidx.compose.material3.CircularProgressIndicator
5222import androidx.compose.material3.ExperimentalMaterial3Api
5323import androidx.compose.material3.FilledIconButton
54−import androidx.compose.material3.FilledTonalButton
5524import androidx.compose.material3.FloatingActionButton
5625import androidx.compose.material3.Icon
5726import androidx.compose.material3.IconButton
58−import androidx.compose.material3.LinearProgressIndicator
5927import androidx.compose.material3.MaterialTheme
6028import androidx.compose.material3.OutlinedTextField
6129import androidx.compose.material3.Scaffold
6230import androidx.compose.material3.Surface
6331import androidx.compose.material3.Text
64−import androidx.compose.material3.TextButton
6532import androidx.compose.material3.TopAppBar
6633import androidx.compose.runtime.Composable
6734import androidx.compose.runtime.LaunchedEffect
6835import androidx.compose.runtime.derivedStateOf
6936import androidx.compose.runtime.getValue
70−import androidx.compose.runtime.mutableStateOf
7137import androidx.compose.runtime.remember
7238import androidx.compose.runtime.rememberCoroutineScope
73−import androidx.compose.runtime.setValue
7439import androidx.compose.ui.Alignment
7540import androidx.compose.ui.Modifier
76−import androidx.compose.ui.draw.clip
77−import 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
81−import androidx.compose.ui.platform.LocalHapticFeedback
82−import androidx.compose.ui.text.font.FontStyle
83−import androidx.compose.ui.text.input.ImeAction
84−import androidx.compose.ui.text.style.TextAlign
8541import androidx.compose.ui.text.style.TextOverflow
8642import androidx.compose.ui.unit.dp
8743import kotlinx.coroutines.launch
@@ -89,17 +45,11 @@ import soy.iko.opencode.core.Event
8945import soy.iko.opencode.core.UiState
9046import soy.iko.opencode.ui.components.MessageBubble
9147
92−@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
48+@OptIn(ExperimentalMaterial3Api::class)
9349@Composable
9450fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
9551 val listState = rememberLazyListState()
9652 val coroutineScope = rememberCoroutineScope()
97− val context = LocalContext.current
98−
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
10353
10454 // Show a jump-to-bottom button once the user scrolls up away from the latest
10555 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -113,22 +63,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
11363 }
11464 }
11565
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 }
120− }
121−
122− // 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.
124− var lastSeenCount by remember { mutableStateOf(0) }
125− LaunchedEffect(showScrollButton, state.messages.size) {
126− if (!showScrollButton) {
127− lastSeenCount = state.messages.size
128− }
129− }
130− val hasUnseenMessages = showScrollButton && state.messages.size > lastSeenCount
131−
13266 // Keep the newest content in view as it streams in, but only when the user is
13367 // already near the bottom. If they've scrolled up to read history, leave it alone.
13468 val lastLen = state.messages.lastOrNull()?.text?.length ?: 0
@@ -148,20 +82,10 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
14882 topBar = {
14983 TopAppBar(
15084 title = {
151− val title = state.currentSessionTitle.ifEmpty { "Chat" }
15285 Text(
153− text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
86+ text = state.currentSessionTitle.ifEmpty { "Chat" },
15487 maxLines = 1,
15588 overflow = TextOverflow.Ellipsis,
156− modifier = Modifier.combinedClickable(
157− onClick = { dispatch(Event.NavigateToSessions) },
158− onLongClick = {
159− state.currentSessionId?.let { id ->
160− copyToClipboard(context, id)
161− Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
162− }
163− },
164− ),
16589 )
16690 },
16791 navigationIcon = {
@@ -183,7 +107,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
183107 ChatInputBar(
184108 draft = state.draft,
185109 generating = state.generating,
186− loading = state.loading && state.messages.isEmpty(),
187110 onDraftChange = { dispatch(Event.DraftChanged(it)) },
188111 onSend = { dispatch(Event.SendMessage(state.draft)) },
189112 onStop = { dispatch(Event.CancelGeneration) },
@@ -194,239 +117,43 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
194117 if (!state.sseConnected && !state.generating) {
195118 ReconnectingBanner()
196119 }
197− if (state.loading && state.messages.isEmpty()) {
198− LinearProgressIndicator(Modifier.fillMaxWidth())
199− }
200− if (state.error != null && state.messages.isNotEmpty()) {
201− ErrorBanner(
202− message = state.error,
203− onDismiss = { dispatch(Event.DismissError) },
204− )
205− }
206120 Box(Modifier.fillMaxWidth().weight(1f)) {
207121 if (state.messages.isEmpty() && !state.loading) {
208− Column(
122+ Text(
123+ text = "Send a message to start the conversation.",
124+ style = MaterialTheme.typography.bodyMedium,
125+ color = MaterialTheme.colorScheme.onSurfaceVariant,
209126 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210− horizontalAlignment = Alignment.CenterHorizontally,
211− ) {
212− Icon(
213− Icons.Filled.ChatBubbleOutline,
214− contentDescription = null,
215− modifier = Modifier.size(48.dp),
216− tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
217− )
218− Spacer(Modifier.size(16.dp))
219− Text(
220− text = "Send a message to start the conversation.",
221− style = MaterialTheme.typography.bodyMedium,
222− color = MaterialTheme.colorScheme.onSurfaceVariant,
223− textAlign = TextAlign.Center,
224− )
225− }
127+ )
226128 }
227129 LazyColumn(
228130 state = listState,
229131 modifier = Modifier.fillMaxSize(),
230132 contentPadding = PaddingValues(vertical = 8.dp),
231133 ) {
232− itemsIndexed(state.messages, key = { _, message -> message.id }) { index, 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)
238− }
239− val sameSenderAsPrevious = index > 0 && state.messages[index - 1].isUser == message.isUser
240− MessageBubble(
241− message,
242− onRetry = { dispatch(Event.SendMessage(message.text)) },
243− compactSpacing = sameSenderAsPrevious,
244− )
245− }
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") {
251− TypingIndicator()
252− }
134+ items(state.messages, key = { it.id }) { message ->
135+ MessageBubble(message)
253136 }
254137 }
255− ScrollToBottomButton(
256− visible = showScrollButton && !isImeVisible,
257− showBadge = hasUnseenMessages,
258− onClick = {
259− coroutineScope.launch {
260− 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 })
264− state.messages.size
265− else
266− state.messages.size - 1
267− listState.animateScrollToItem(target)
138+ if (showScrollButton) {
139+ FloatingActionButton(
140+ onClick = {
141+ coroutineScope.launch {
142+ if (state.messages.isNotEmpty()) {
143+ listState.animateScrollToItem(state.messages.size - 1)
144+ }
268145 }
269− }
270− },
271− )
272− ScrollToTopButton(
273− visible = showScrollTop,
274− onClick = {
275− coroutineScope.launch {
276− listState.animateScrollToItem(0)
277− }
278− },
279− )
280− }
281− }
282− }
283−}
284−
285−// Extracted into a BoxScope extension so the top-level AnimatedVisibility overload
286−// resolves cleanly. Called inline inside a Column, the enclosing ColumnScope receiver
287−// would otherwise capture the ColumnScope.AnimatedVisibility overload and fail to compile.
288−@Composable
289−private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean, onClick: () -> Unit) {
290− AnimatedVisibility(
291− visible = visible,
292− modifier = Modifier.align(Alignment.BottomEnd),
293− enter = scaleIn() + fadeIn(),
294− exit = scaleOut() + fadeOut(),
295− ) {
296− Box(Modifier.padding(16.dp)) {
297− FloatingActionButton(
298− onClick = onClick,
299− modifier = Modifier.size(44.dp),
300− ) {
301− Icon(
302− Icons.Filled.KeyboardArrowDown,
303− contentDescription = "Scroll to latest message",
304− )
305− }
306− if (showBadge) {
307− Box(
308− modifier = Modifier
309− .align(Alignment.TopEnd)
310− .size(8.dp)
311− .clip(CircleShape)
312− .background(MaterialTheme.colorScheme.error),
313− )
314− }
315− }
316− }
317−}
318−
319−// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
320−// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
321−@Composable
322−private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
323− AnimatedVisibility(
324− visible = visible,
325− modifier = Modifier.align(Alignment.TopStart),
326− enter = scaleIn() + fadeIn(),
327− exit = scaleOut() + fadeOut(),
328− ) {
329− Box(Modifier.padding(16.dp)) {
330− FloatingActionButton(
331− onClick = onClick,
332− modifier = Modifier.size(44.dp),
333− ) {
334− Icon(
335− Icons.Filled.KeyboardArrowUp,
336− contentDescription = "Scroll to top",
337− )
338− }
339− }
340− }
341−}
342−
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))
346−}
347−
348−private val dateSeparatorFormat = java.time.format.DateTimeFormatter.ofPattern("MMM d")
349−
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())
354− .toLocalDate()
355−
356−/**
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.
360− */
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)
365−}
366−
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()
370− return when (day) {
371− today -> "Today"
372− today.minusDays(1) -> "Yesterday"
373− else -> day.format(dateSeparatorFormat)
374− }
375−}
376−
377−@Composable
378−private fun DateSeparator(epochMillis: Long) {
379− Text(
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),
385− )
386−}
387−
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.
391−@Composable
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")
395− Row(
396− modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
397− horizontalArrangement = Arrangement.Start,
398− ) {
399− Row(
400− modifier = Modifier
401− .clip(shape)
402− .background(MaterialTheme.colorScheme.surfaceVariant)
403− .padding(horizontal = 14.dp, vertical = 12.dp),
404− verticalAlignment = Alignment.CenterVertically,
405− horizontalArrangement = Arrangement.spacedBy(6.dp),
406− ) {
407− Text(
408− text = "Thinking",
409− style = MaterialTheme.typography.bodyMedium.copy(fontStyle = FontStyle.Italic),
410− color = MaterialTheme.colorScheme.onSurfaceVariant,
411− )
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,
417− targetValue = 1f,
418− animationSpec = infiniteRepeatable(
419− animation = tween(durationMillis = 600, delayMillis = staggerMs),
420− repeatMode = RepeatMode.Reverse,
421− ),
422− label = "dot",
423− )
424− Box(
146+ },
425147 modifier = Modifier
426− .size(6.dp)
427− .clip(CircleShape)
428− .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)),
429− )
148+ .align(Alignment.BottomEnd)
149+ .padding(16.dp)
150+ .size(44.dp),
151+ ) {
152+ Icon(
153+ Icons.Filled.KeyboardArrowDown,
154+ contentDescription = "Scroll to latest message",
155+ )
156+ }
430157 }
431158 }
432159 }
@@ -458,133 +185,39 @@ private fun ReconnectingBanner() {
458185 }
459186}
460187
461−@Composable
462−private fun ErrorBanner(message: String, onDismiss: () -> Unit) {
463− Surface(
464− modifier = Modifier.fillMaxWidth(),
465− color = MaterialTheme.colorScheme.errorContainer,
466− ) {
467− Row(
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),
471− ) {
472− Text(
473− text = message,
474− style = MaterialTheme.typography.bodySmall,
475− color = MaterialTheme.colorScheme.onErrorContainer,
476− modifier = Modifier.weight(1f),
477− )
478− IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
479− Icon(
480− Icons.Filled.Close,
481− contentDescription = "Dismiss error",
482− tint = MaterialTheme.colorScheme.onErrorContainer,
483− modifier = Modifier.size(18.dp),
484− )
485− }
486− }
487− }
488−}
489−
490188@Composable
491189private fun ChatInputBar(
492190 draft: String,
493191 generating: Boolean,
494− loading: Boolean,
495192 onDraftChange: (String) -> Unit,
496193 onSend: () -> Unit,
497194 onStop: () -> Unit,
498195) {
499− val haptic = LocalHapticFeedback.current
500− val clipboardManager = LocalClipboardManager.current
501196 Surface(tonalElevation = 3.dp) {
502− Column(
503− modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504− ) {
505197 Row(
506− modifier = Modifier.fillMaxWidth(),
198+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
507199 verticalAlignment = Alignment.Bottom,
508200 horizontalArrangement = Arrangement.spacedBy(8.dp),
509201 ) {
510202 OutlinedTextField(
511203 value = draft,
512204 onValueChange = onDraftChange,
513− modifier = Modifier.weight(1f).heightIn(min = 48.dp),
514− enabled = !loading,
205+ modifier = Modifier.weight(1f),
515206 placeholder = { Text("Message opencode…") },
516207 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) {
520− {
521− IconButton(
522− onClick = { onDraftChange("") },
523− modifier = Modifier.size(20.dp),
524− ) {
525− Icon(
526− Icons.Filled.Close,
527− contentDescription = "Clear draft",
528− modifier = Modifier.size(16.dp),
529− )
530− }
531− }
532− } else {
533− null
534− },
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) {
538− {
539− Text(
540− text = "${draft.length} characters",
541− style = MaterialTheme.typography.labelSmall,
542− color = MaterialTheme.colorScheme.onSurfaceVariant,
543− textAlign = TextAlign.End,
544− modifier = Modifier.fillMaxWidth(),
545− )
546− }
547− } else {
548− null
549− },
550− keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551− keyboardActions = KeyboardActions(onSend = {
552− if (!generating && !loading && draft.isNotBlank()) onSend()
553− }),
554208 )
555209 if (generating) {
556− FilledTonalButton(onClick = onStop) {
557− Icon(
558− Icons.Filled.Stop,
559− contentDescription = null,
560− modifier = Modifier.size(18.dp),
561− )
562− Spacer(Modifier.size(6.dp))
563− Text("Stop")
210+ FilledIconButton(onClick = onStop) {
211+ Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
564212 }
565213 } else {
566214 FilledIconButton(
567− onClick = {
568− haptic.performHapticFeedback(HapticFeedbackType.LongPress)
569− onSend()
570− },
571− enabled = draft.isNotBlank() && !loading,
215+ onClick = onSend,
216+ enabled = draft.isNotBlank(),
572217 ) {
573218 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
574219 }
575220 }
576221 }
577− // With nothing typed yet, offer a one-tap way to drop in clipboard contents.
578− if (draft.isEmpty() && !generating && !loading) {
579− TextButton(
580− onClick = {
581− clipboardManager.getText()?.text?.let { onDraftChange(it) }
582− },
583− contentPadding = PaddingValues(0.dp),
584− ) {
585− Text("Paste")
586− }
587− }
588− }
589222 }
590223}