git.iko.soy/opencode-android
on master help sign in
11 files changed+831−49
since splitsnapshots
unifiedsplit
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+14 app/src/main/java/soy/iko/opencode/core/HttpClient.kt+1 app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+95−9 app/src/main/java/soy/iko/opencode/core/SseClient.kt+1 app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+55−2 app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+237−7 app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+270−15 app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+49−2 app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+84−14 app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+22 shared/src/app.rs+3
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+14
@@ -23,11 +23,23 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
2323 init {
2424 prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
2525 prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
26+ // The password is stored in plain text in SharedPreferences — a deliberate
27+ // convenience trade-off for a local dev tool so reconnecting is one tap.
28+ prefs.getString(KEY_PASSWORD, null)?.let { core.dispatch(Event.PasswordChanged(it)) }
2629
2730 // On a fresh process after a configuration change, resume the SSE stream if
2831 // the core is already connected (no-op otherwise — it guards on `connected`).
2932 core.resumeStreamingIfConnected()
3033
34+ // Returning users shouldn't have to tap Connect: if a URL was restored and we
35+ // aren't already connected, kick off the connection attempt on launch. The core
36+ // handles an empty/invalid URL, so this only fires when there's something to try.
37+ core.view.value.let { restored ->
38+ if (restored.serverUrl.isNotEmpty() && !restored.connected) {
39+ core.dispatch(Event.Connect)
40+ }
41+ }
42+
3143 // Persist connection details once a connection succeeds.
3244 viewModelScope.launch {
3345 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
@@ -35,6 +47,7 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
3547 prefs.edit {
3648 putString(KEY_URL, state.serverUrl)
3749 putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
3851 }
3952 }
4053 }
@@ -48,5 +61,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
4861 private companion object {
4962 const val KEY_URL = "serverUrl"
5063 const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
5165 }
5266}
app/src/main/java/soy/iko/opencode/core/HttpClient.kt+1
@@ -51,6 +51,7 @@ class HttpClient(
5151 ): Result<HttpResp> = withContext(Dispatchers.IO) {
5252 runCatching {
5353 val builder = Request.Builder().url(url).method()
54+ builder.header("User-Agent", "opencode-android/1.0")
5455 if (auth != null) builder.header("Authorization", auth)
5556 await(okhttp.newCall(builder.build()))
5657 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+95−9
@@ -54,6 +54,24 @@ class OpencodeCore(
5454 // Guards against overlapping session refreshes: rapid taps launch multiple
5555 // loadSessions coroutines and the slowest-to-return would otherwise win.
5656 private var loadSessionsJob: Job? = null
57+ // Tracks the in-flight createSession coroutine so navigating away can cancel it
58+ // before it dispatches SelectSession into a screen the user already left.
59+ private var createSessionJob: Job? = null
60+ // Tracks the in-flight loadMessages coroutine. Rapidly switching sessions launches
61+ // several; cancel the prior one so only the newest fetch runs (saves needless requests).
62+ private var loadMessagesJob: Job? = null
63+ // Tracks the in-flight probeHealth coroutine. Rapid double-taps on Connect would
64+ // otherwise launch two concurrent health probes; cancel the prior one first.
65+ private var connectJob: Job? = null
66+ // Tracks the in-flight DeleteSession coroutine so navigating away can cancel it
67+ // before its response handler mutates the sessions list / screen the user already left.
68+ private var deleteSessionJob: Job? = null
69+ // Tracks the in-flight sendMessage coroutine so navigating away or switching sessions
70+ // can cancel it before its response handler touches stale message state.
71+ private var sendMessageJob: Job? = null
72+ // Tracks the in-flight abort coroutine (CancelGeneration) so rapid cancel taps don't
73+ // fire multiple abort requests, and navigating away can cancel it.
74+ private var abortJob: Job? = null
5775 // Message IDs removed via SSE; a late MessageUpdated for one must not resurrect it.
5876 private val removedMessageIds = mutableSetOf<String>()
5977
@@ -78,10 +96,12 @@ class OpencodeCore(
7896 // Leave authRequired as-is; probeHealth sets it from the response (true on
7997 // 401, false on success). Resetting it here just flickers the auth fields.
8098 loading = true; error = null; emit()
81− scope.launch { probeHealth() }
99+ connectJob?.cancel()
100+ connectJob = scope.launch { probeHealth() }
82101 }
83102
84103 Event.LoadSessions -> {
104+ if (!connected) { error = "Not connected"; emit(); return }
85105 loading = true; emit()
86106 loadSessionsJob?.cancel()
87107 loadSessionsJob = scope.launch { loadSessions() }
@@ -101,17 +121,29 @@ class OpencodeCore(
101121 generating = false
102122 error = null
103123 emit()
104− scope.launch { loadMessages(event.id) }
124+ connectJob?.cancel()
125+ abortJob?.cancel()
126+ sendMessageJob?.cancel()
127+ deleteSessionJob?.cancel()
128+ loadMessagesJob?.cancel()
129+ loadMessagesJob = scope.launch { loadMessages(event.id) }
105130 }
106131
107− Event.CreateSession -> { loading = true; error = null; emit(); scope.launch { createSession() } }
132+ Event.CreateSession -> {
133+ if (!connected) { error = "Not connected"; emit(); return }
134+ loading = true; error = null; emit()
135+ createSessionJob?.cancel()
136+ createSessionJob = scope.launch { createSession() }
137+ }
108138
109139 is Event.DeleteSession -> {
140+ if (!connected) { error = "Not connected"; emit(); return }
110141 val id = event.id
111142 // Delete on the server first; only drop it from the UI once that
112143 // succeeds, so a failed request leaves the session recoverable.
113144 loading = true; error = null; emit()
114− scope.launch {
145+ deleteSessionJob?.cancel()
146+ deleteSessionJob = scope.launch {
115147 http.delete("$serverUrl/session/$id", authHeader()).fold(
116148 onSuccess = { resp ->
117149 if (resp.code in 200..299) {
@@ -144,7 +176,10 @@ class OpencodeCore(
144176 messages.forEach { it.streaming = false }
145177 emit()
146178 val id = currentSessionId ?: return
147− scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
179+ // Debounce rapid cancel taps: cancel any in-flight abort before firing
180+ // another so we don't stack duplicate abort requests.
181+ abortJob?.cancel()
182+ abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
148183 }
149184
150185 Event.NavigateToSessions -> {
@@ -152,9 +187,19 @@ class OpencodeCore(
152187 currentSessionId = null
153188 messages.clear()
154189 removedMessageIds.clear()
190+ draft = ""
155191 generating = false
192+ // Clear any error from the chat (e.g. a failed send) so it doesn't
193+ // linger on the sessions list after the user navigates back.
194+ error = null
156195 loading = true
157196 emit()
197+ connectJob?.cancel()
198+ abortJob?.cancel()
199+ createSessionJob?.cancel()
200+ deleteSessionJob?.cancel()
201+ sendMessageJob?.cancel()
202+ loadMessagesJob?.cancel()
158203 loadSessionsJob?.cancel()
159204 loadSessionsJob = scope.launch { loadSessions() }
160205 }
@@ -168,9 +213,16 @@ class OpencodeCore(
168213 messages.clear()
169214 removedMessageIds.clear()
170215 currentSessionId = null
216+ draft = ""
171217 // Reset to the default so a late-firing close callback from the old
172218 // SSE connection can't flash the reconnecting banner on the next connect.
173219 sseConnected = true
220+ connectJob?.cancel()
221+ abortJob?.cancel()
222+ createSessionJob?.cancel()
223+ deleteSessionJob?.cancel()
224+ sendMessageJob?.cancel()
225+ loadMessagesJob?.cancel()
174226 closeSse()
175227 emit()
176228 }
@@ -184,13 +236,27 @@ class OpencodeCore(
184236 if (connected && sse == null) startSse()
185237 }
186238
187− fun shutdown() = closeSse()
239+ fun shutdown() {
240+ // Cancel every tracked coroutine before tearing down the stream so none can
241+ // emit into a cancelled scope after the ViewModel is cleared.
242+ connectJob?.cancel()
243+ loadSessionsJob?.cancel()
244+ createSessionJob?.cancel()
245+ loadMessagesJob?.cancel()
246+ deleteSessionJob?.cancel()
247+ sendMessageJob?.cancel()
248+ abortJob?.cancel()
249+ closeSse()
250+ }
188251
189252 // ── Effects ────────────────────────────────────────────────────────────────
190253 private fun sendMessage(raw: String) {
191254 val text = raw.trim()
192255 val session = currentSessionId ?: return
193256 if (text.isEmpty()) return
257+ // Debounce rapid double-taps on send: a send is already in flight, so a second
258+ // tap would create a duplicate user message and fire a duplicate request.
259+ if (generating) return
194260 localSeq += 1
195261 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
196262 status = MessageStatus.Pending
@@ -206,7 +272,8 @@ class OpencodeCore(
206272 emit()
207273
208274 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
209− scope.launch {
275+ sendMessageJob?.cancel()
276+ sendMessageJob = scope.launch {
210277 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
211278 result.fold(
212279 onSuccess = { resp ->
@@ -239,6 +306,10 @@ class OpencodeCore(
239306 when {
240307 resp.code == 401 -> {
241308 loading = false
309+ // A prior connection may have succeeded (connected = true); a
310+ // re-probe returning 401 (e.g. expired credentials) means we're
311+ // no longer authenticated, so drop the connected flag.
312+ connected = false
242313 // Always reveal the auth fields so the user can see/edit
243314 // their credentials — even when the ones supplied were wrong.
244315 authRequired = true
@@ -253,10 +324,14 @@ class OpencodeCore(
253324 loading = true
254325 emit()
255326 startSse()
256− loadSessions()
327+ // Route through loadSessionsJob so a prior in-flight loadSessions
328+ // (e.g. from a rapid double-connect) is cancelled first.
329+ loadSessionsJob?.cancel()
330+ loadSessionsJob = scope.launch { loadSessions() }
257331 }
258332 else -> {
259333 loading = false
334+ connected = false
260335 error = "Server returned status ${resp.code}"
261336 emit()
262337 }
@@ -264,6 +339,7 @@ class OpencodeCore(
264339 },
265340 onFailure = { e ->
266341 loading = false
342+ connected = false
267343 error = "Connection failed: ${e.message}"
268344 emit()
269345 },
@@ -276,6 +352,9 @@ class OpencodeCore(
276352 if (resp.code in 200..299) {
277353 sessions.clear()
278354 sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
355+ // Impose a stable alphabetical order so the list doesn't shuffle with
356+ // whatever order the server happens to return sessions in.
357+ sessions.sortBy { it.title.lowercase() }
279358 } else {
280359 error = "Server returned status ${resp.code}"
281360 }
@@ -293,6 +372,10 @@ class OpencodeCore(
293372 if (session != null) {
294373 if (sessions.none { it.id == session.id }) {
295374 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
375+ // Restore the alphabetical order immediately (matching loadSessions /
376+ // SessionUpserted) so the new session doesn't sit out-of-order at the
377+ // top until the SSE SessionUpserted event arrives to re-sort.
378+ sessions.sortBy { it.title.lowercase() }
296379 }
297380 emit()
298381 // SelectSession takes over the loading state (loads messages).
@@ -399,7 +482,7 @@ class OpencodeCore(
399482 } else {
400483 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
401484 }
402− info.error?.let { error = it.message(); generating = false }
485+ info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
403486 return true
404487 }
405488
@@ -462,6 +545,9 @@ class OpencodeCore(
462545 } else {
463546 sessions.add(0, SessionView(event.info.id, title))
464547 }
548+ // Keep the list alphabetically sorted (matching loadSessions) so an
549+ // upserted session doesn't jump to the top and break the ordering.
550+ sessions.sortBy { it.title.lowercase() }
465551 if (isCurrent(event.info.id)) currentSessionTitle = title
466552 return true
467553 }
app/src/main/java/soy/iko/opencode/core/SseClient.kt+1
@@ -33,6 +33,7 @@ class SseClient(
3333
3434 fun connect() {
3535 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36+ builder.header("User-Agent", "opencode-android/1.0")
3637 if (auth != null) builder.header("Authorization", auth)
3738 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
3839 }
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+55−2
@@ -7,13 +7,19 @@ import androidx.compose.animation.slideOutHorizontally
77import androidx.compose.animation.togetherWith
88import androidx.compose.foundation.layout.fillMaxSize
99import androidx.compose.foundation.layout.padding
10+import androidx.compose.material3.AlertDialog
1011import androidx.compose.material3.Scaffold
1112import androidx.compose.material3.SnackbarDuration
1213import androidx.compose.material3.SnackbarHost
1314import androidx.compose.material3.SnackbarHostState
15+import androidx.compose.material3.Text
16+import androidx.compose.material3.TextButton
1417import androidx.compose.runtime.Composable
1518import androidx.compose.runtime.LaunchedEffect
19+import androidx.compose.runtime.getValue
20+import androidx.compose.runtime.mutableStateOf
1621import androidx.compose.runtime.remember
22+import androidx.compose.runtime.setValue
1723import androidx.compose.ui.Modifier
1824import soy.iko.opencode.core.Event
1925import soy.iko.opencode.core.Screen
@@ -25,6 +31,8 @@ import soy.iko.opencode.ui.screens.SessionsScreen
2531@Composable
2632fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
2733 val snackbar = remember { SnackbarHostState() }
34+ var showStopConfirm by remember { mutableStateOf(false) }
35+ var showDisconnectConfirm by remember { mutableStateOf(false) }
2836
2937 LaunchedEffect(state.error) {
3038 state.error?.let {
@@ -40,12 +48,57 @@ fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
4048
4149 BackHandler(enabled = state.screen != Screen.Connect) {
4250 when (state.screen) {
43− Screen.Chat -> dispatch(Event.NavigateToSessions)
44− Screen.Sessions -> dispatch(Event.NavigateToConnect)
51+ // Leaving mid-generation would silently drop the reply, so confirm first.
52+ Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
53+ // Disconnecting drops the server session, so guard the back button.
54+ Screen.Sessions -> showDisconnectConfirm = true
4555 Screen.Connect -> Unit
4656 }
4757 }
4858
59+ if (showStopConfirm) {
60+ AlertDialog(
61+ onDismissRequest = { showStopConfirm = false },
62+ title = { Text("Stop generation?") },
63+ text = { Text("Leaving will stop the current generation.") },
64+ confirmButton = {
65+ TextButton(onClick = {
66+ showStopConfirm = false
67+ dispatch(Event.CancelGeneration)
68+ dispatch(Event.NavigateToSessions)
69+ }) {
70+ Text("Stop and leave")
71+ }
72+ },
73+ dismissButton = {
74+ TextButton(onClick = { showStopConfirm = false }) {
75+ Text("Stay")
76+ }
77+ },
78+ )
79+ }
80+
81+ if (showDisconnectConfirm) {
82+ AlertDialog(
83+ onDismissRequest = { showDisconnectConfirm = false },
84+ title = { Text("Disconnect?") },
85+ text = { Text("You will be disconnected from the server.") },
86+ confirmButton = {
87+ TextButton(onClick = {
88+ showDisconnectConfirm = false
89+ dispatch(Event.NavigateToConnect)
90+ }) {
91+ Text("Disconnect")
92+ }
93+ },
94+ dismissButton = {
95+ TextButton(onClick = { showDisconnectConfirm = false }) {
96+ Text("Cancel")
97+ }
98+ },
99+ )
100+ }
101+
49102 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
50103 AnimatedContent(
51104 targetState = state.screen,
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+237−7
@@ -3,6 +3,8 @@ package soy.iko.opencode.ui.components
33import android.content.ClipData
44import android.content.ClipboardManager
55import android.content.Context
6+import android.content.Intent
7+import android.net.Uri
68import android.widget.Toast
79import androidx.compose.foundation.ExperimentalFoundationApi
810import androidx.compose.foundation.background
@@ -13,6 +15,7 @@ import androidx.compose.foundation.layout.Column
1315import androidx.compose.foundation.layout.Row
1416import androidx.compose.foundation.layout.fillMaxWidth
1517import androidx.compose.foundation.layout.padding
18+import androidx.compose.foundation.layout.size
1619import androidx.compose.foundation.layout.widthIn
1720import androidx.compose.foundation.shape.RoundedCornerShape
1821import androidx.compose.foundation.text.selection.SelectionContainer
@@ -23,6 +26,9 @@ import androidx.compose.material.icons.filled.ErrorOutline
2326import androidx.compose.material.icons.filled.ExpandLess
2427import androidx.compose.material.icons.filled.ExpandMore
2528import androidx.compose.material.icons.filled.Schedule
29+import androidx.compose.material.icons.filled.SmartToy
30+import androidx.compose.material3.DropdownMenu
31+import androidx.compose.material3.DropdownMenuItem
2632import androidx.compose.material3.Icon
2733import androidx.compose.material3.MaterialTheme
2834import androidx.compose.material3.Text
@@ -36,10 +42,17 @@ import androidx.compose.ui.Modifier
3642import androidx.compose.ui.draw.clip
3743import androidx.compose.ui.graphics.Color
3844import androidx.compose.ui.platform.LocalContext
45+import androidx.compose.ui.text.AnnotatedString
46+import androidx.compose.ui.text.LinkAnnotation
3947import androidx.compose.ui.text.SpanStyle
48+import androidx.compose.ui.text.TextLinkStyles
4049import androidx.compose.ui.text.buildAnnotatedString
50+import androidx.compose.ui.text.font.FontFamily
4151import androidx.compose.ui.text.font.FontStyle
52+import androidx.compose.ui.text.font.FontWeight
53+import androidx.compose.ui.text.withLink
4254import androidx.compose.ui.text.withStyle
55+import androidx.compose.ui.text.style.TextDecoration
4356import androidx.compose.ui.text.style.TextOverflow
4457import androidx.compose.ui.unit.dp
4558import androidx.compose.ui.unit.sp
@@ -52,7 +65,7 @@ private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
5265
5366@OptIn(ExperimentalFoundationApi::class)
5467@Composable
55−fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
68+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
5669 val isUser = message.isUser
5770 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
5871 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
@@ -65,11 +78,20 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
6578 )
6679
6780 val context = LocalContext.current
81+ var showMenu by remember { mutableStateOf(false) }
6882
6983 Row(
70− modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
84+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
7185 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
7286 ) {
87+ if (!isUser) {
88+ Icon(
89+ Icons.Filled.SmartToy,
90+ contentDescription = null,
91+ tint = MaterialTheme.colorScheme.primary,
92+ modifier = Modifier.align(Alignment.Top).padding(end = 6.dp, top = 2.dp).size(28.dp),
93+ )
94+ }
7395 Column(
7496 modifier = Modifier
7597 .fillMaxWidth(0.85f)
@@ -80,21 +102,55 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
80102 onClick = {},
81103 onLongClick = {
82104 if (message.text.isNotEmpty()) {
83− copyToClipboard(context, message.text)
84− Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
105+ showMenu = true
85106 }
86107 },
87108 )
88109 .padding(horizontal = 14.dp, vertical = 10.dp),
89110 ) {
111+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
112+ DropdownMenuItem(
113+ text = { Text("Copy") },
114+ onClick = {
115+ copyToClipboard(context, message.text)
116+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
117+ showMenu = false
118+ },
119+ )
120+ DropdownMenuItem(
121+ text = { Text("Share") },
122+ onClick = {
123+ shareText(context, message.text)
124+ showMenu = false
125+ },
126+ )
127+ }
128+
90129 message.reasoning?.let { ReasoningBlock(it, context) }
91130
131+ // Give a quick overview of how many tools ran before listing them.
132+ if (message.tools.size > 1) {
133+ Text(
134+ text = "${message.tools.size} tool calls",
135+ style = MaterialTheme.typography.labelSmall,
136+ color = MaterialTheme.colorScheme.onSurfaceVariant,
137+ modifier = Modifier.padding(bottom = 4.dp),
138+ )
139+ }
140+
92141 message.tools.forEach { ToolRow(it) }
93142
94143 SelectionContainer {
95144 if (message.text.isNotEmpty()) {
145+ val linkColor = MaterialTheme.colorScheme.primary
146+ // Tint the code background off the bubble's own foreground colour so it
147+ // contrasts on both bubble types (user bubbles use primaryContainer).
148+ val codeBackground = (if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface).copy(alpha = 0.08f)
149+ val annotatedText = remember(message.text, message.streaming, linkColor, codeBackground, context) {
150+ buildLinkedText(message.text, message.streaming, linkColor, codeBackground, context)
151+ }
96152 Text(
97− text = message.text + if (message.streaming) " ▌" else "",
153+ text = annotatedText,
98154 color = textColor,
99155 // Give assistant replies (often long, code-heavy) extra line
100156 // spacing for readability; user bubbles keep the default.
@@ -119,7 +175,7 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
119175 }
120176
121177 if (isUser && message.status != MessageStatus.Sent) {
122− StatusLine(message.status)
178+ StatusLine(message.status, onRetry = onRetry)
123179 }
124180 }
125181 }
@@ -130,6 +186,170 @@ private fun copyToClipboard(context: Context, text: String) {
130186 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
131187}
132188
189+private val urlRegex = Regex("""https?://[^\s]+""")
190+
191+/**
192+ * Render [text] as an AnnotatedString. Triple-backtick fences split the text into
193+ * prose and code segments: code segments are rendered monospace on a tinted
194+ * [codeBackground] (fences dropped), while prose has each http(s) URL turned into a
195+ * clickable link. The streaming cursor (" ▌") is appended outside any annotation.
196+ */
197+private fun buildLinkedText(
198+ text: String,
199+ streaming: Boolean,
200+ linkColor: Color,
201+ codeBackground: Color,
202+ context: Context,
203+): AnnotatedString = buildAnnotatedString {
204+ // Odd-indexed segments sit between a pair of ``` fences, so they're code. An
205+ // unclosed fence leaves the trailing segment styled as code, mirroring markdown.
206+ val segments = text.split("```")
207+ segments.forEachIndexed { index, segment ->
208+ if (index % 2 == 1) {
209+ withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
210+ append(segment)
211+ }
212+ } else {
213+ appendLinkedText(segment, linkColor, codeBackground, context)
214+ }
215+ }
216+ if (streaming) append(" ▌")
217+}
218+
219+/**
220+ * Append [text] to the builder. Double-asterisk pairs are rendered bold; within each
221+ * segment, single-backtick pairs are rendered as inline code (monospace, backticks
222+ * dropped), and the remaining prose has each http(s) URL turned into a clickable link.
223+ * Triple-backtick fences are already stripped upstream in [buildLinkedText], so only
224+ * inline spans reach here.
225+ */
226+private fun AnnotatedString.Builder.appendLinkedText(
227+ text: String,
228+ linkColor: Color,
229+ codeBackground: Color,
230+ context: Context,
231+) {
232+ // Bold is the outermost inline layer: split on ** first so a bold span can wrap
233+ // inline code and links inside it. Odd-indexed segments sit between a pair of **
234+ // markers, so they're bold (markers dropped); even segments are ordinary prose.
235+ // Only the non-bold (even) segments get single-* italic handling — splitting a bold
236+ // segment on "*" would misfire on the leftover asterisks from the ** markers.
237+ val segments = text.split("**")
238+ // An even segment count means an odd number of ** markers, so the final ** is unclosed:
239+ // its trailing segment isn't bold. Restore the literal ** and render it as ordinary prose.
240+ val unclosed = segments.size % 2 == 0
241+ segments.forEachIndexed { index, segment ->
242+ val isUnclosedTail = unclosed && index == segments.size - 1
243+ if (index % 2 == 1 && !isUnclosedTail) {
244+ withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
245+ appendInlineCode(segment, linkColor, codeBackground, context)
246+ }
247+ } else {
248+ if (isUnclosedTail) append("**")
249+ appendItalicText(segment, linkColor, codeBackground, context)
250+ }
251+ }
252+}
253+
254+/**
255+ * Append [text] to the builder, rendering single-asterisk pairs as italic. Double
256+ * asterisks are already consumed as bold upstream in [appendLinkedText], so only lone
257+ * `*` markers reach here. Each segment then flows through inline-code and URL handling.
258+ */
259+private fun AnnotatedString.Builder.appendItalicText(
260+ text: String,
261+ linkColor: Color,
262+ codeBackground: Color,
263+ context: Context,
264+) {
265+ // Odd-indexed segments sit between a pair of single asterisks, so they're italic
266+ // (markers dropped); even segments are ordinary prose.
267+ val segments = text.split("*")
268+ // An even segment count means an odd number of * markers, so the final * is unclosed:
269+ // its trailing segment isn't italic. Restore the literal * and render it as prose.
270+ val unclosed = segments.size % 2 == 0
271+ segments.forEachIndexed { index, segment ->
272+ val isUnclosedTail = unclosed && index == segments.size - 1
273+ if (index % 2 == 1 && !isUnclosedTail) {
274+ withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
275+ appendInlineCode(segment, linkColor, codeBackground, context)
276+ }
277+ } else {
278+ if (isUnclosedTail) append("*")
279+ appendInlineCode(segment, linkColor, codeBackground, context)
280+ }
281+ }
282+}
283+
284+/**
285+ * Append [text] to the builder, rendering single-backtick pairs as inline code
286+ * (monospace, backticks dropped) and turning each http(s) URL in the remaining prose
287+ * into a clickable link.
288+ */
289+private fun AnnotatedString.Builder.appendInlineCode(
290+ text: String,
291+ linkColor: Color,
292+ codeBackground: Color,
293+ context: Context,
294+) {
295+ // Odd-indexed segments sit between a pair of single backticks, so they're inline
296+ // code. Even segments are ordinary prose and get URL linking applied.
297+ val segments = text.split("`")
298+ // An even segment count means an odd number of backtick markers, so the final backtick
299+ // is unclosed: its trailing segment isn't code. Restore the literal ` and treat as prose.
300+ val unclosed = segments.size % 2 == 0
301+ segments.forEachIndexed { index, segment ->
302+ val isUnclosedTail = unclosed && index == segments.size - 1
303+ if (index % 2 == 1 && !isUnclosedTail) {
304+ withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
305+ append(segment)
306+ }
307+ } else {
308+ if (isUnclosedTail) append("`")
309+ appendUrls(segment, linkColor, context)
310+ }
311+ }
312+}
313+
314+/** Append [text] to the builder, turning each http(s) URL into a clickable link. */
315+private fun AnnotatedString.Builder.appendUrls(
316+ text: String,
317+ linkColor: Color,
318+ context: Context,
319+) {
320+ val matches = urlRegex.findAll(text).toList()
321+ var cursor = 0
322+ for (match in matches) {
323+ append(text.substring(cursor, match.range.first))
324+ val url = match.value
325+ withLink(
326+ LinkAnnotation.Clickable(
327+ tag = url,
328+ styles = TextLinkStyles(
329+ SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline),
330+ ),
331+ linkInteractionListener = {
332+ runCatching {
333+ context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
334+ }
335+ },
336+ ),
337+ ) {
338+ append(url)
339+ }
340+ cursor = match.range.last + 1
341+ }
342+ append(text.substring(cursor))
343+}
344+
345+private fun shareText(context: Context, text: String) {
346+ val intent = Intent(Intent.ACTION_SEND).apply {
347+ type = "text/plain"
348+ putExtra(Intent.EXTRA_TEXT, text)
349+ }
350+ context.startActivity(Intent.createChooser(intent, null))
351+}
352+
133353@Composable
134354private fun ReasoningBlock(text: String, context: Context) {
135355 var expanded by remember { mutableStateOf(false) }
@@ -227,7 +447,7 @@ private fun ToolRow(tool: ToolView) {
227447}
228448
229449@Composable
230−private fun StatusLine(status: MessageStatus) {
450+private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
231451 val (icon, label, tint) = when (status) {
232452 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
233453 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
@@ -245,5 +465,15 @@ private fun StatusLine(status: MessageStatus) {
245465 color = tint,
246466 modifier = Modifier.padding(start = 4.dp),
247467 )
468+ if (status == MessageStatus.Failed) {
469+ Text(
470+ text = "Retry",
471+ style = MaterialTheme.typography.labelSmall,
472+ color = MaterialTheme.colorScheme.primary,
473+ modifier = Modifier
474+ .padding(start = 12.dp)
475+ .clickable { onRetry() },
476+ )
477+ }
248478 }
249479}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+270−15
@@ -1,12 +1,23 @@
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
37import 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
413import androidx.compose.animation.fadeIn
514import androidx.compose.animation.fadeOut
615import androidx.compose.animation.scaleIn
716import androidx.compose.animation.scaleOut
17+import androidx.compose.foundation.ExperimentalFoundationApi
818import androidx.compose.foundation.background
919import androidx.compose.foundation.clickable
20+import androidx.compose.foundation.combinedClickable
1021import androidx.compose.foundation.layout.Arrangement
1122import androidx.compose.foundation.layout.Box
1223import androidx.compose.foundation.layout.BoxScope
@@ -15,21 +26,27 @@ import androidx.compose.foundation.layout.Row
1526import androidx.compose.foundation.layout.Spacer
1627import androidx.compose.foundation.layout.fillMaxSize
1728import androidx.compose.foundation.layout.fillMaxWidth
29+import androidx.compose.foundation.layout.heightIn
1830import androidx.compose.foundation.layout.PaddingValues
31+import androidx.compose.foundation.layout.WindowInsets
32+import androidx.compose.foundation.layout.ime
1933import androidx.compose.foundation.layout.imePadding
2034import androidx.compose.foundation.layout.padding
2135import androidx.compose.foundation.layout.size
2236import androidx.compose.foundation.lazy.LazyColumn
23−import androidx.compose.foundation.lazy.items
37+import androidx.compose.foundation.lazy.itemsIndexed
2438import androidx.compose.foundation.lazy.rememberLazyListState
2539import androidx.compose.foundation.shape.CircleShape
40+import androidx.compose.foundation.shape.RoundedCornerShape
2641import androidx.compose.foundation.text.KeyboardActions
2742import androidx.compose.foundation.text.KeyboardOptions
2843import androidx.compose.material.icons.Icons
2944import androidx.compose.material.icons.automirrored.filled.ArrowBack
3045import androidx.compose.material.icons.automirrored.filled.Send
46+import androidx.compose.material.icons.filled.ChatBubbleOutline
3147import androidx.compose.material.icons.filled.Close
3248import androidx.compose.material.icons.filled.KeyboardArrowDown
49+import androidx.compose.material.icons.filled.KeyboardArrowUp
3350import androidx.compose.material.icons.filled.Stop
3451import androidx.compose.material3.CircularProgressIndicator
3552import androidx.compose.material3.ExperimentalMaterial3Api
@@ -44,6 +61,7 @@ import androidx.compose.material3.OutlinedTextField
4461import androidx.compose.material3.Scaffold
4562import androidx.compose.material3.Surface
4663import androidx.compose.material3.Text
64+import androidx.compose.material3.TextButton
4765import androidx.compose.material3.TopAppBar
4866import androidx.compose.runtime.Composable
4967import androidx.compose.runtime.LaunchedEffect
@@ -57,8 +75,13 @@ import androidx.compose.ui.Alignment
5775import androidx.compose.ui.Modifier
5876import androidx.compose.ui.draw.clip
5977import 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
6081import androidx.compose.ui.platform.LocalHapticFeedback
82+import androidx.compose.ui.text.font.FontStyle
6183import androidx.compose.ui.text.input.ImeAction
84+import androidx.compose.ui.text.style.TextAlign
6285import androidx.compose.ui.text.style.TextOverflow
6386import androidx.compose.ui.unit.dp
6487import kotlinx.coroutines.launch
@@ -66,11 +89,17 @@ import soy.iko.opencode.core.Event
6689import soy.iko.opencode.core.UiState
6790import soy.iko.opencode.ui.components.MessageBubble
6891
69−@OptIn(ExperimentalMaterial3Api::class)
92+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
7093@Composable
7194fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
7295 val listState = rememberLazyListState()
7396 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
74103
75104 // Show a jump-to-bottom button once the user scrolls up away from the latest
76105 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -84,6 +113,12 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
84113 }
85114 }
86115
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+
87122 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
88123 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
89124 var lastSeenCount by remember { mutableStateOf(0) }
@@ -113,11 +148,20 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
113148 topBar = {
114149 TopAppBar(
115150 title = {
151+ val title = state.currentSessionTitle.ifEmpty { "Chat" }
116152 Text(
117− text = state.currentSessionTitle.ifEmpty { "Chat" },
153+ text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
118154 maxLines = 1,
119155 overflow = TextOverflow.Ellipsis,
120− modifier = Modifier.clickable { dispatch(Event.NavigateToSessions) },
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+ ),
121165 )
122166 },
123167 navigationIcon = {
@@ -161,33 +205,78 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
161205 }
162206 Box(Modifier.fillMaxWidth().weight(1f)) {
163207 if (state.messages.isEmpty() && !state.loading) {
164− Text(
165− text = "Send a message to start the conversation.",
166− style = MaterialTheme.typography.bodyMedium,
167− color = MaterialTheme.colorScheme.onSurfaceVariant,
208+ Column(
168209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
169− )
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+ }
170226 }
171227 LazyColumn(
172228 state = listState,
173229 modifier = Modifier.fillMaxSize(),
174230 contentPadding = PaddingValues(vertical = 8.dp),
175231 ) {
176− items(state.messages, key = { it.id }) { message ->
177− MessageBubble(message)
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+ }
178253 }
179254 }
180255 ScrollToBottomButton(
181− visible = showScrollButton,
256+ visible = showScrollButton && !isImeVisible,
182257 showBadge = hasUnseenMessages,
183258 onClick = {
184259 coroutineScope.launch {
185260 if (state.messages.isNotEmpty()) {
186− listState.animateScrollToItem(state.messages.size - 1)
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)
187268 }
188269 }
189270 },
190271 )
272+ ScrollToTopButton(
273+ visible = showScrollTop,
274+ onClick = {
275+ coroutineScope.launch {
276+ listState.animateScrollToItem(0)
277+ }
278+ },
279+ )
191280 }
192281 }
193282 }
@@ -227,6 +316,123 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
227316 }
228317}
229318
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(
425+ modifier = Modifier
426+ .size(6.dp)
427+ .clip(CircleShape)
428+ .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)),
429+ )
430+ }
431+ }
432+ }
433+ }
434+}
435+
230436@Composable
231437private fun ReconnectingBanner() {
232438 Surface(
@@ -291,19 +497,56 @@ private fun ChatInputBar(
291497 onStop: () -> Unit,
292498) {
293499 val haptic = LocalHapticFeedback.current
500+ val clipboardManager = LocalClipboardManager.current
294501 Surface(tonalElevation = 3.dp) {
295− Row(
502+ Column(
296503 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504+ ) {
505+ Row(
506+ modifier = Modifier.fillMaxWidth(),
297507 verticalAlignment = Alignment.Bottom,
298508 horizontalArrangement = Arrangement.spacedBy(8.dp),
299509 ) {
300510 OutlinedTextField(
301511 value = draft,
302512 onValueChange = onDraftChange,
303− modifier = Modifier.weight(1f),
513+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
304514 enabled = !loading,
305515 placeholder = { Text("Message opencode…") },
306516 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+ },
307550 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
308551 keyboardActions = KeyboardActions(onSend = {
309552 if (!generating && !loading && draft.isNotBlank()) onSend()
@@ -331,5 +574,17 @@ private fun ChatInputBar(
331574 }
332575 }
333576 }
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+ }
334589 }
335590}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+49−2
@@ -101,6 +101,30 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
101101 enabled = !state.loading,
102102 )
103103
104+ // Point first-time users at the expected address format. Hidden once they
105+ // start typing so it doesn't compete with the field's own contents.
106+ if (state.serverUrl.isEmpty()) {
107+ Spacer(Modifier.height(6.dp))
108+ Text(
109+ text = "Enter the URL of your opencode server (e.g. http://192.168.1.10:4096)",
110+ style = MaterialTheme.typography.bodySmall,
111+ color = MaterialTheme.colorScheme.onSurfaceVariant,
112+ textAlign = TextAlign.Center,
113+ )
114+ }
115+
116+ // Nudge the user if the URL looks like it's missing a scheme — a bare host:port
117+ // won't connect. Informational (tertiary), not an error, since it's a heuristic.
118+ if (state.serverUrl.isNotBlank() && "://" !in state.serverUrl && !state.serverUrl.startsWith("http")) {
119+ Spacer(Modifier.height(6.dp))
120+ Text(
121+ text = "Tip: Add http:// if connecting to a local server",
122+ style = MaterialTheme.typography.bodySmall,
123+ color = MaterialTheme.colorScheme.tertiary,
124+ textAlign = TextAlign.Center,
125+ )
126+ }
127+
104128 if (state.authRequired) {
105129 Spacer(Modifier.height(12.dp))
106130 OutlinedTextField(
@@ -131,7 +155,15 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
131155 },
132156 modifier = Modifier.fillMaxWidth(),
133157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
134− keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
158+ keyboardActions = KeyboardActions(onGo = {
159+ // Mirror the connect button's enabled condition so the keyboard's
160+ // Go action can't fire a request the form isn't ready for.
161+ if (!state.loading && state.serverUrl.isNotBlank() &&
162+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank())
163+ ) {
164+ dispatch(Event.Connect)
165+ }
166+ }),
135167 enabled = !state.loading,
136168 )
137169 Spacer(Modifier.height(4.dp))
@@ -146,7 +178,10 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
146178
147179 Button(
148180 onClick = { dispatch(Event.Connect) },
149− enabled = !state.loading && state.serverUrl.isNotBlank(),
181+ // When auth is required, keep the button disabled until at least one
182+ // credential is entered — otherwise it just triggers a validation error.
183+ enabled = !state.loading && state.serverUrl.isNotBlank() &&
184+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
150185 modifier = Modifier.fillMaxWidth(),
151186 ) {
152187 if (state.loading) {
@@ -160,6 +195,18 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
160195 }
161196 }
162197
198+ // While connecting (including auto-connect on launch), echo the target URL
199+ // so the user knows what the spinner is waiting on.
200+ if (state.loading) {
201+ Spacer(Modifier.height(8.dp))
202+ Text(
203+ text = "Connecting to ${state.serverUrl}...",
204+ style = MaterialTheme.typography.bodySmall,
205+ color = MaterialTheme.colorScheme.onSurfaceVariant,
206+ textAlign = TextAlign.Center,
207+ )
208+ }
209+
163210 // Surface the error inline as well, so it stays visible while the user
164211 // corrects the form (the snackbar is transient).
165212 if (state.error != null && !state.loading) {
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+84−14
@@ -1,7 +1,13 @@
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.foundation.ExperimentalFoundationApi
38import androidx.compose.foundation.background
49import androidx.compose.foundation.clickable
10+import androidx.compose.foundation.combinedClickable
511import androidx.compose.foundation.layout.Arrangement
612import androidx.compose.foundation.layout.Box
713import androidx.compose.foundation.layout.Column
@@ -15,6 +21,8 @@ import androidx.compose.foundation.layout.padding
1521import androidx.compose.foundation.layout.size
1622import androidx.compose.foundation.lazy.LazyColumn
1723import androidx.compose.foundation.lazy.items
24+import androidx.compose.foundation.lazy.rememberLazyListState
25+import androidx.compose.foundation.shape.CircleShape
1826import androidx.compose.material.icons.Icons
1927import androidx.compose.material.icons.automirrored.filled.ArrowBack
2028import androidx.compose.material.icons.filled.Add
@@ -50,8 +58,12 @@ import androidx.compose.runtime.remember
5058import androidx.compose.runtime.setValue
5159import androidx.compose.ui.Alignment
5260import androidx.compose.ui.Modifier
61+import androidx.compose.ui.draw.clip
62+import androidx.compose.ui.graphics.Color
5363import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64+import androidx.compose.ui.platform.LocalContext
5465import androidx.compose.ui.platform.LocalHapticFeedback
66+import androidx.compose.ui.text.style.TextAlign
5567import androidx.compose.ui.text.style.TextOverflow
5668import androidx.compose.ui.unit.dp
5769import soy.iko.opencode.core.Event
@@ -65,6 +77,15 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
6577 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
6678 var isPullRefreshing by remember { mutableStateOf(false) }
6779 var searchQuery by remember { mutableStateOf("") }
80+ val sessionsListState = rememberLazyListState()
81+
82+ // Bring a newly created session (which lands at the top of the list) into view.
83+ // Only scroll when the list actually grows, not on every reload of the same sessions.
84+ var prevSize by remember { mutableStateOf(state.sessions.size) }
85+ LaunchedEffect(state.sessions.size) {
86+ if (state.sessions.size > prevSize) sessionsListState.animateScrollToItem(0)
87+ prevSize = state.sessions.size
88+ }
6889
6990 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
7091 // every loading operation. Clear it once the underlying load completes.
@@ -98,7 +119,23 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
98119 Scaffold(
99120 topBar = {
100121 TopAppBar(
101− title = { Text("Sessions") },
122+ title = {
123+ Row(verticalAlignment = Alignment.CenterVertically) {
124+ // A quick at-a-glance health dot for the SSE stream: green when
125+ // connected, error-tinted when the stream is down (updates stall).
126+ Box(
127+ modifier = Modifier
128+ .size(8.dp)
129+ .clip(CircleShape)
130+ .background(
131+ if (state.sseConnected) Color(0xFF4CAF50)
132+ else MaterialTheme.colorScheme.error,
133+ ),
134+ )
135+ Spacer(Modifier.size(8.dp))
136+ Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "Sessions")
137+ }
138+ },
102139 navigationIcon = {
103140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
104141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -112,11 +149,15 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
112149 )
113150 },
114151 floatingActionButton = {
115− ExtendedFloatingActionButton(
116− onClick = { dispatch(Event.CreateSession) },
117− icon = { Icon(Icons.Filled.Add, contentDescription = null) },
118− text = { Text("New session") },
119− )
152+ // Give the search results the full width while searching — the FAB would
153+ // otherwise cover the bottom rows and isn't relevant mid-search anyway.
154+ if (searchQuery.isEmpty()) {
155+ ExtendedFloatingActionButton(
156+ onClick = { dispatch(Event.CreateSession) },
157+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
158+ text = { Text("New session") },
159+ )
160+ }
120161 },
121162 ) { padding ->
122163 Column(Modifier.fillMaxSize().padding(padding)) {
@@ -158,6 +199,7 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
158199 state = rememberPullToRefreshState(),
159200 ) {
160201 LazyColumn(
202+ state = sessionsListState,
161203 modifier = Modifier.fillMaxSize(),
162204 contentPadding = PaddingValues(bottom = 88.dp),
163205 ) {
@@ -196,13 +238,21 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
196238 }
197239}
198240
241+@OptIn(ExperimentalFoundationApi::class)
199242@Composable
200243private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
244+ val context = LocalContext.current
201245 Row(
202246 modifier = Modifier
203247 .fillMaxWidth()
204248 .background(MaterialTheme.colorScheme.surface)
205− .clickable(onClick = onOpen)
249+ .combinedClickable(
250+ onClick = onOpen,
251+ onLongClick = {
252+ copyToClipboard(context, session.id)
253+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
254+ },
255+ )
206256 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
207257 verticalAlignment = Alignment.CenterVertically,
208258 ) {
@@ -237,13 +287,13 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
237287 Icon(
238288 Icons.Filled.DeleteOutline,
239289 contentDescription = "Delete session",
240− tint = MaterialTheme.colorScheme.onSurfaceVariant,
290+ tint = MaterialTheme.colorScheme.error,
241291 )
242292 }
243293 }
244294}
245295
246−/** Red background with a trailing delete icon, revealed while swiping a session row away. */
296+/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
247297@Composable
248298private fun SwipeDeleteBackground() {
249299 Box(
@@ -253,11 +303,19 @@ private fun SwipeDeleteBackground() {
253303 .padding(horizontal = 24.dp),
254304 contentAlignment = Alignment.CenterEnd,
255305 ) {
256− Icon(
257− Icons.Filled.DeleteOutline,
258− contentDescription = null,
259− tint = MaterialTheme.colorScheme.onError,
260− )
306+ Row(verticalAlignment = Alignment.CenterVertically) {
307+ Icon(
308+ Icons.Filled.DeleteOutline,
309+ contentDescription = null,
310+ tint = MaterialTheme.colorScheme.onError,
311+ )
312+ Text(
313+ text = "Delete",
314+ style = MaterialTheme.typography.labelLarge,
315+ color = MaterialTheme.colorScheme.onError,
316+ modifier = Modifier.padding(start = 4.dp),
317+ )
318+ }
261319 }
262320}
263321
@@ -287,6 +345,11 @@ private fun ReconnectingBanner() {
287345 }
288346}
289347
348+private fun copyToClipboard(context: Context, text: String) {
349+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
350+ clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
351+}
352+
290353/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
291354private fun shortSessionId(id: String): String =
292355 if (id.length > 12) id.take(8) + "…" else id
@@ -328,5 +391,12 @@ private fun EmptySessions() {
328391 style = MaterialTheme.typography.bodyMedium,
329392 color = MaterialTheme.colorScheme.onSurfaceVariant,
330393 )
394+ Spacer(Modifier.height(8.dp))
395+ Text(
396+ text = "Sessions you create on this server will appear here.",
397+ style = MaterialTheme.typography.bodySmall,
398+ color = MaterialTheme.colorScheme.onSurfaceVariant,
399+ textAlign = TextAlign.Center,
400+ )
331401 }
332402}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+22
@@ -14,7 +14,18 @@ import androidx.compose.ui.platform.LocalContext
1414private val DarkColors = darkColorScheme(
1515 primary = Emerald,
1616 onPrimary = Color(0xFF0F1115),
17+ primaryContainer = Color(0xFF1A3D2A),
18+ onPrimaryContainer = Color(0xFFA8E6C1),
1719 secondary = EmeraldDark,
20+ onSecondary = Color(0xFFE6E9EF),
21+ secondaryContainer = Color(0xFF1A2A3D),
22+ onSecondaryContainer = Color(0xFFA8C5E6),
23+ tertiary = Color(0xFF6B7280),
24+ onTertiary = Color(0xFFE6E9EF),
25+ tertiaryContainer = Color(0xFF2A2A3D),
26+ onTertiaryContainer = Color(0xFFC5C5E6),
27+ errorContainer = Color(0xFF4D2626),
28+ onErrorContainer = Color(0xFFFFB4B4),
1829 background = DarkBackground,
1930 surface = DarkSurface,
2031 surfaceVariant = DarkSurfaceVariant,
@@ -24,7 +35,18 @@ private val DarkColors = darkColorScheme(
2435
2536private val LightColors = lightColorScheme(
2637 primary = EmeraldDark,
38+ primaryContainer = Color(0xFFD7F5E3),
39+ onPrimaryContainer = Color(0xFF0A3D22),
2740 secondary = Emerald,
41+ onSecondary = Color(0xFF1A1C1F),
42+ secondaryContainer = Color(0xFFD7E8F5),
43+ onSecondaryContainer = Color(0xFF0A2A4D),
44+ tertiary = Color(0xFF6B7280),
45+ onTertiary = Color(0xFFFFFFFF),
46+ tertiaryContainer = Color(0xFFE8E8F5),
47+ onTertiaryContainer = Color(0xFF2A2A4D),
48+ errorContainer = Color(0xFFFFE0E0),
49+ onErrorContainer = Color(0xFF660000),
2850 background = LightBackground,
2951 surface = LightSurface,
3052 surfaceVariant = LightSurfaceVariant,
shared/src/app.rs+3
@@ -352,6 +352,9 @@ impl App for OpencodeApp {
352352 title: display_title(&s.title),
353353 })
354354 .collect();
355+ // Impose a stable alphabetical order so the list doesn't shuffle
356+ // with whatever order the server happens to return sessions in.
357+ model.sessions.sort_by_key(|s| s.title.to_lowercase());
355358 }
356359 Err(e) => model.error = Some(e),
357360 }