git.iko.soy/opencode-android
on master help sign in
9 files changed+273−13
since splitsnapshots
unifiedsplit
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+5 app/src/main/java/soy/iko/opencode/core/HttpClient.kt+1 app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+12−1 app/src/main/java/soy/iko/opencode/core/SseClient.kt+1 app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+98−2 app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+96−7 app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+21−1 app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+29−2 app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+10
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+5
@@ -23,6 +23,9 @@ 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`).
@@ -44,6 +47,7 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
4447 prefs.edit {
4548 putString(KEY_URL, state.serverUrl)
4649 putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
4751 }
4852 }
4953 }
@@ -57,5 +61,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
5761 private companion object {
5862 const val KEY_URL = "serverUrl"
5963 const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
6065 }
6166}
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+12−1
@@ -236,7 +236,18 @@ class OpencodeCore(
236236 if (connected && sse == null) startSse()
237237 }
238238
239− 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+ }
240251
241252 // ── Effects ────────────────────────────────────────────────────────────────
242253 private fun sendMessage(raw: String) {
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/components/MessageBubble.kt+98−2
@@ -49,6 +49,7 @@ import androidx.compose.ui.text.TextLinkStyles
4949import androidx.compose.ui.text.buildAnnotatedString
5050import androidx.compose.ui.text.font.FontFamily
5151import androidx.compose.ui.text.font.FontStyle
52+import androidx.compose.ui.text.font.FontWeight
5253import androidx.compose.ui.text.withLink
5354import androidx.compose.ui.text.withStyle
5455import androidx.compose.ui.text.style.TextDecoration
@@ -209,14 +210,109 @@ private fun buildLinkedText(
209210 append(segment)
210211 }
211212 } else {
212− appendLinkedText(segment, linkColor, context)
213+ appendLinkedText(segment, linkColor, codeBackground, context)
213214 }
214215 }
215216 if (streaming) append(" ▌")
216217}
217218
218−/** Append [text] to the builder, turning each http(s) URL into a clickable link. */
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+ */
219226private 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(
220316 text: String,
221317 linkColor: Color,
222318 context: Context,
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+96−7
@@ -26,6 +26,7 @@ import androidx.compose.foundation.layout.Row
2626import androidx.compose.foundation.layout.Spacer
2727import androidx.compose.foundation.layout.fillMaxSize
2828import androidx.compose.foundation.layout.fillMaxWidth
29+import androidx.compose.foundation.layout.heightIn
2930import androidx.compose.foundation.layout.PaddingValues
3031import androidx.compose.foundation.layout.WindowInsets
3132import androidx.compose.foundation.layout.ime
@@ -42,8 +43,10 @@ import androidx.compose.foundation.text.KeyboardOptions
4243import androidx.compose.material.icons.Icons
4344import androidx.compose.material.icons.automirrored.filled.ArrowBack
4445import androidx.compose.material.icons.automirrored.filled.Send
46+import androidx.compose.material.icons.filled.ChatBubbleOutline
4547import androidx.compose.material.icons.filled.Close
4648import androidx.compose.material.icons.filled.KeyboardArrowDown
49+import androidx.compose.material.icons.filled.KeyboardArrowUp
4750import androidx.compose.material.icons.filled.Stop
4851import androidx.compose.material3.CircularProgressIndicator
4952import androidx.compose.material3.ExperimentalMaterial3Api
@@ -58,6 +61,7 @@ import androidx.compose.material3.OutlinedTextField
5861import androidx.compose.material3.Scaffold
5962import androidx.compose.material3.Surface
6063import androidx.compose.material3.Text
64+import androidx.compose.material3.TextButton
6165import androidx.compose.material3.TopAppBar
6266import androidx.compose.runtime.Composable
6367import androidx.compose.runtime.LaunchedEffect
@@ -71,6 +75,7 @@ import androidx.compose.ui.Alignment
7175import androidx.compose.ui.Modifier
7276import androidx.compose.ui.draw.clip
7377import androidx.compose.ui.hapticfeedback.HapticFeedbackType
78+import androidx.compose.ui.platform.LocalClipboardManager
7479import androidx.compose.ui.platform.LocalContext
7580import androidx.compose.ui.platform.LocalDensity
7681import androidx.compose.ui.platform.LocalHapticFeedback
@@ -108,6 +113,12 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
108113 }
109114 }
110115
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+
111122 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
112123 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
113124 var lastSeenCount by remember { mutableStateOf(0) }
@@ -194,12 +205,24 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
194205 }
195206 Box(Modifier.fillMaxWidth().weight(1f)) {
196207 if (state.messages.isEmpty() && !state.loading) {
197− Text(
198− text = "Send a message to start the conversation.",
199− style = MaterialTheme.typography.bodyMedium,
200− color = MaterialTheme.colorScheme.onSurfaceVariant,
208+ Column(
201209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
202− )
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+ }
203226 }
204227 LazyColumn(
205228 state = listState,
@@ -246,6 +269,14 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
246269 }
247270 },
248271 )
272+ ScrollToTopButton(
273+ visible = showScrollTop,
274+ onClick = {
275+ coroutineScope.launch {
276+ listState.animateScrollToItem(0)
277+ }
278+ },
279+ )
249280 }
250281 }
251282 }
@@ -285,6 +316,30 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
285316 }
286317}
287318
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+
288343private fun copyToClipboard(context: Context, text: String) {
289344 val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
290345 clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
@@ -442,19 +497,41 @@ private fun ChatInputBar(
442497 onStop: () -> Unit,
443498) {
444499 val haptic = LocalHapticFeedback.current
500+ val clipboardManager = LocalClipboardManager.current
445501 Surface(tonalElevation = 3.dp) {
446− Row(
502+ Column(
447503 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504+ ) {
505+ Row(
506+ modifier = Modifier.fillMaxWidth(),
448507 verticalAlignment = Alignment.Bottom,
449508 horizontalArrangement = Arrangement.spacedBy(8.dp),
450509 ) {
451510 OutlinedTextField(
452511 value = draft,
453512 onValueChange = onDraftChange,
454− modifier = Modifier.weight(1f),
513+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
455514 enabled = !loading,
456515 placeholder = { Text("Message opencode…") },
457516 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+ },
458535 // Surface a running count once the draft gets long, so the user has a
459536 // sense of scale before sending a wall of text.
460537 supportingText = if (draft.length > 500) {
@@ -497,5 +574,17 @@ private fun ChatInputBar(
497574 }
498575 }
499576 }
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+ }
500589 }
501590}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+21−1
@@ -155,7 +155,15 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
155155 },
156156 modifier = Modifier.fillMaxWidth(),
157157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
158− 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+ }),
159167 enabled = !state.loading,
160168 )
161169 Spacer(Modifier.height(4.dp))
@@ -187,6 +195,18 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
187195 }
188196 }
189197
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+
190210 // Surface the error inline as well, so it stays visible while the user
191211 // corrects the form (the snackbar is transient).
192212 if (state.error != null && !state.loading) {
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+29−2
@@ -22,6 +22,7 @@ import androidx.compose.foundation.layout.size
2222import androidx.compose.foundation.lazy.LazyColumn
2323import androidx.compose.foundation.lazy.items
2424import androidx.compose.foundation.lazy.rememberLazyListState
25+import androidx.compose.foundation.shape.CircleShape
2526import androidx.compose.material.icons.Icons
2627import androidx.compose.material.icons.automirrored.filled.ArrowBack
2728import androidx.compose.material.icons.filled.Add
@@ -57,9 +58,12 @@ import androidx.compose.runtime.remember
5758import androidx.compose.runtime.setValue
5859import androidx.compose.ui.Alignment
5960import androidx.compose.ui.Modifier
61+import androidx.compose.ui.draw.clip
62+import androidx.compose.ui.graphics.Color
6063import androidx.compose.ui.hapticfeedback.HapticFeedbackType
6164import androidx.compose.ui.platform.LocalContext
6265import androidx.compose.ui.platform.LocalHapticFeedback
66+import androidx.compose.ui.text.style.TextAlign
6367import androidx.compose.ui.text.style.TextOverflow
6468import androidx.compose.ui.unit.dp
6569import soy.iko.opencode.core.Event
@@ -115,7 +119,23 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
115119 Scaffold(
116120 topBar = {
117121 TopAppBar(
118− title = { Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "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+ },
119139 navigationIcon = {
120140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
121141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -267,7 +287,7 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
267287 Icon(
268288 Icons.Filled.DeleteOutline,
269289 contentDescription = "Delete session",
270− tint = MaterialTheme.colorScheme.onSurfaceVariant,
290+ tint = MaterialTheme.colorScheme.error,
271291 )
272292 }
273293 }
@@ -371,5 +391,12 @@ private fun EmptySessions() {
371391 style = MaterialTheme.typography.bodyMedium,
372392 color = MaterialTheme.colorScheme.onSurfaceVariant,
373393 )
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+ )
374401 }
375402}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+10
@@ -17,6 +17,11 @@ private val DarkColors = darkColorScheme(
1717 primaryContainer = Color(0xFF1A3D2A),
1818 onPrimaryContainer = Color(0xFFA8E6C1),
1919 secondary = EmeraldDark,
20+ onSecondary = Color(0xFFE6E9EF),
21+ secondaryContainer = Color(0xFF1A2A3D),
22+ onSecondaryContainer = Color(0xFFA8C5E6),
23+ tertiary = Color(0xFF6B7280),
24+ onTertiary = Color(0xFFE6E9EF),
2025 tertiaryContainer = Color(0xFF2A2A3D),
2126 onTertiaryContainer = Color(0xFFC5C5E6),
2227 errorContainer = Color(0xFF4D2626),
@@ -33,6 +38,11 @@ private val LightColors = lightColorScheme(
3338 primaryContainer = Color(0xFFD7F5E3),
3439 onPrimaryContainer = Color(0xFF0A3D22),
3540 secondary = Emerald,
41+ onSecondary = Color(0xFF1A1C1F),
42+ secondaryContainer = Color(0xFFD7E8F5),
43+ onSecondaryContainer = Color(0xFF0A2A4D),
44+ tertiary = Color(0xFF6B7280),
45+ onTertiary = Color(0xFFFFFFFF),
3646 tertiaryContainer = Color(0xFFE8E8F5),
3747 onTertiaryContainer = Color(0xFF2A2A4D),
3848 errorContainer = Color(0xFFFFE0E0),