git.iko.soy/opencode-android
on 3716ac2 help sign in
app/src/main/java/soy/iko/opencode/CoreViewModel.kt−5
since splitsnapshots
unifiedsplit
@@ -23,9 +23,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
23 init {
23 init {
24 prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
24 prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
25 prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
25 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)) }
29
26
30 // On a fresh process after a configuration change, resume the SSE stream if
27 // On a fresh process after a configuration change, resume the SSE stream if
31 // the core is already connected (no-op otherwise — it guards on `connected`).
28 // the core is already connected (no-op otherwise — it guards on `connected`).
@@ -47,7 +44,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
47 prefs.edit {
44 prefs.edit {
48 putString(KEY_URL, state.serverUrl)
45 putString(KEY_URL, state.serverUrl)
49 putString(KEY_USER, state.username)
46 putString(KEY_USER, state.username)
50− putString(KEY_PASSWORD, state.password)
51 }
47 }
52 }
48 }
53 }
49 }
@@ -61,6 +57,5 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
61 private companion object {
57 private companion object {
62 const val KEY_URL = "serverUrl"
58 const val KEY_URL = "serverUrl"
63 const val KEY_USER = "username"
59 const val KEY_USER = "username"
64− const val KEY_PASSWORD = "password"
65 }
60 }
66}
61}
app/src/main/java/soy/iko/opencode/core/HttpClient.kt−1
@@ -51,7 +51,6 @@ class HttpClient(
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
52 runCatching {
52 runCatching {
53 val builder = Request.Builder().url(url).method()
53 val builder = Request.Builder().url(url).method()
54− builder.header("User-Agent", "opencode-android/1.0")
55 if (auth != null) builder.header("Authorization", auth)
54 if (auth != null) builder.header("Authorization", auth)
56 await(okhttp.newCall(builder.build()))
55 await(okhttp.newCall(builder.build()))
57 }
56 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+1−24
@@ -124,7 +124,6 @@ class OpencodeCore(
124 connectJob?.cancel()
124 connectJob?.cancel()
125 abortJob?.cancel()
125 abortJob?.cancel()
126 sendMessageJob?.cancel()
126 sendMessageJob?.cancel()
127− deleteSessionJob?.cancel()
128 loadMessagesJob?.cancel()
127 loadMessagesJob?.cancel()
129 loadMessagesJob = scope.launch { loadMessages(event.id) }
128 loadMessagesJob = scope.launch { loadMessages(event.id) }
130 }
129 }
@@ -189,9 +188,6 @@ class OpencodeCore(
189 removedMessageIds.clear()
188 removedMessageIds.clear()
190 draft = ""
189 draft = ""
191 generating = false
190 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
195 loading = true
191 loading = true
196 emit()
192 emit()
197 connectJob?.cancel()
193 connectJob?.cancel()
@@ -236,18 +232,7 @@ class OpencodeCore(
236 if (connected && sse == null) startSse()
232 if (connected && sse == null) startSse()
237 }
233 }
238
234
239− fun shutdown() {
235+ fun shutdown() = closeSse()
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− }
251
236
252 // ── Effects ────────────────────────────────────────────────────────────────
237 // ── Effects ────────────────────────────────────────────────────────────────
253 private fun sendMessage(raw: String) {
238 private fun sendMessage(raw: String) {
@@ -306,10 +291,6 @@ class OpencodeCore(
306 when {
291 when {
307 resp.code == 401 -> {
292 resp.code == 401 -> {
308 loading = false
293 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
313 // Always reveal the auth fields so the user can see/edit
294 // Always reveal the auth fields so the user can see/edit
314 // their credentials — even when the ones supplied were wrong.
295 // their credentials — even when the ones supplied were wrong.
315 authRequired = true
296 authRequired = true
@@ -372,10 +353,6 @@ class OpencodeCore(
372 if (session != null) {
353 if (session != null) {
373 if (sessions.none { it.id == session.id }) {
354 if (sessions.none { it.id == session.id }) {
374 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
355 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() }
379 }
356 }
380 emit()
357 emit()
381 // SelectSession takes over the loading state (loads messages).
358 // SelectSession takes over the loading state (loads messages).
app/src/main/java/soy/iko/opencode/core/SseClient.kt−1
@@ -33,7 +33,6 @@ class SseClient(
33
33
34 fun connect() {
34 fun connect() {
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36− builder.header("User-Agent", "opencode-android/1.0")
37 if (auth != null) builder.header("Authorization", auth)
36 if (auth != null) builder.header("Authorization", auth)
38 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
37 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
39 }
38 }
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+2−55
@@ -7,19 +7,13 @@ import androidx.compose.animation.slideOutHorizontally
7import androidx.compose.animation.togetherWith
7import androidx.compose.animation.togetherWith
8import androidx.compose.foundation.layout.fillMaxSize
8import androidx.compose.foundation.layout.fillMaxSize
9import androidx.compose.foundation.layout.padding
9import androidx.compose.foundation.layout.padding
10−import androidx.compose.material3.AlertDialog
11import androidx.compose.material3.Scaffold
10import androidx.compose.material3.Scaffold
12import androidx.compose.material3.SnackbarDuration
11import androidx.compose.material3.SnackbarDuration
13import androidx.compose.material3.SnackbarHost
12import androidx.compose.material3.SnackbarHost
14import androidx.compose.material3.SnackbarHostState
13import androidx.compose.material3.SnackbarHostState
15−import androidx.compose.material3.Text
16−import androidx.compose.material3.TextButton
17import androidx.compose.runtime.Composable
14import androidx.compose.runtime.Composable
18import androidx.compose.runtime.LaunchedEffect
15import androidx.compose.runtime.LaunchedEffect
19−import androidx.compose.runtime.getValue
20−import androidx.compose.runtime.mutableStateOf
21import androidx.compose.runtime.remember
16import androidx.compose.runtime.remember
22−import androidx.compose.runtime.setValue
23import androidx.compose.ui.Modifier
17import androidx.compose.ui.Modifier
24import soy.iko.opencode.core.Event
18import soy.iko.opencode.core.Event
25import soy.iko.opencode.core.Screen
19import soy.iko.opencode.core.Screen
@@ -31,8 +25,6 @@ import soy.iko.opencode.ui.screens.SessionsScreen
31@Composable
25@Composable
32fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
26fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
33 val snackbar = remember { SnackbarHostState() }
27 val snackbar = remember { SnackbarHostState() }
34− var showStopConfirm by remember { mutableStateOf(false) }
35− var showDisconnectConfirm by remember { mutableStateOf(false) }
36
28
37 LaunchedEffect(state.error) {
29 LaunchedEffect(state.error) {
38 state.error?.let {
30 state.error?.let {
@@ -48,57 +40,12 @@ fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
48
40
49 BackHandler(enabled = state.screen != Screen.Connect) {
41 BackHandler(enabled = state.screen != Screen.Connect) {
50 when (state.screen) {
42 when (state.screen) {
51− // Leaving mid-generation would silently drop the reply, so confirm first.
52− Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
43+ Screen.Chat -> dispatch(Event.NavigateToSessions)
53− // Disconnecting drops the server session, so guard the back button.
44+ Screen.Sessions -> dispatch(Event.NavigateToConnect)
54− Screen.Sessions -> showDisconnectConfirm = true
55 Screen.Connect -> Unit
45 Screen.Connect -> Unit
56 }
46 }
57 }
47 }
58
48
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−
102 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
49 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
103 AnimatedContent(
50 AnimatedContent(
104 targetState = state.screen,
51 targetState = state.screen,
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+6−138
@@ -47,9 +47,7 @@ import androidx.compose.ui.text.LinkAnnotation
47import androidx.compose.ui.text.SpanStyle
47import androidx.compose.ui.text.SpanStyle
48import androidx.compose.ui.text.TextLinkStyles
48import androidx.compose.ui.text.TextLinkStyles
49import androidx.compose.ui.text.buildAnnotatedString
49import androidx.compose.ui.text.buildAnnotatedString
50−import androidx.compose.ui.text.font.FontFamily
51import androidx.compose.ui.text.font.FontStyle
50import androidx.compose.ui.text.font.FontStyle
52−import androidx.compose.ui.text.font.FontWeight
53import androidx.compose.ui.text.withLink
51import androidx.compose.ui.text.withLink
54import androidx.compose.ui.text.withStyle
52import androidx.compose.ui.text.withStyle
55import androidx.compose.ui.text.style.TextDecoration
53import androidx.compose.ui.text.style.TextDecoration
@@ -128,26 +126,13 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
128
126
129 message.reasoning?.let { ReasoningBlock(it, context) }
127 message.reasoning?.let { ReasoningBlock(it, context) }
130
128
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−
141 message.tools.forEach { ToolRow(it) }
129 message.tools.forEach { ToolRow(it) }
142
130
143 SelectionContainer {
131 SelectionContainer {
144 if (message.text.isNotEmpty()) {
132 if (message.text.isNotEmpty()) {
145 val linkColor = MaterialTheme.colorScheme.primary
133 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) {
134+ val annotatedText = remember(message.text, message.streaming, linkColor) {
150− buildLinkedText(message.text, message.streaming, linkColor, codeBackground, context)
135+ buildLinkedText(message.text, message.streaming, linkColor, context)
151 }
136 }
152 Text(
137 Text(
153 text = annotatedText,
138 text = annotatedText,
@@ -189,134 +174,16 @@ private fun copyToClipboard(context: Context, text: String) {
189private val urlRegex = Regex("""https?://[^\s]+""")
174private val urlRegex = Regex("""https?://[^\s]+""")
190
175
191/**
176/**
192− * Render [text] as an AnnotatedString. Triple-backtick fences split the text into
177+ * Render [text] as an AnnotatedString where each http(s) URL becomes a clickable link
193− * prose and code segments: code segments are rendered monospace on a tinted
178+ * that opens in the browser. Falls back to plain text when no URLs are present. The
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.
179+ * streaming cursor (" ▌") is appended outside any link annotation.
196 */
180 */
197private fun buildLinkedText(
181private fun buildLinkedText(
198 text: String,
182 text: String,
199 streaming: Boolean,
183 streaming: Boolean,
200 linkColor: Color,
184 linkColor: Color,
201− codeBackground: Color,
202 context: Context,
185 context: Context,
203): AnnotatedString = buildAnnotatedString {
186): 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()
187 val matches = urlRegex.findAll(text).toList()
321 var cursor = 0
188 var cursor = 0
322 for (match in matches) {
189 for (match in matches) {
@@ -340,6 +207,7 @@ private fun AnnotatedString.Builder.appendUrls(
340 cursor = match.range.last + 1
207 cursor = match.range.last + 1
341 }
208 }
342 append(text.substring(cursor))
209 append(text.substring(cursor))
210+ if (streaming) append(" ▌")
343}
211}
344
212
345private fun shareText(context: Context, text: String) {
213private fun shareText(context: Context, text: String) {
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+7−111
@@ -26,7 +26,6 @@ import androidx.compose.foundation.layout.Row
26import androidx.compose.foundation.layout.Spacer
26import androidx.compose.foundation.layout.Spacer
27import androidx.compose.foundation.layout.fillMaxSize
27import androidx.compose.foundation.layout.fillMaxSize
28import androidx.compose.foundation.layout.fillMaxWidth
28import androidx.compose.foundation.layout.fillMaxWidth
29−import androidx.compose.foundation.layout.heightIn
30import androidx.compose.foundation.layout.PaddingValues
29import androidx.compose.foundation.layout.PaddingValues
31import androidx.compose.foundation.layout.WindowInsets
30import androidx.compose.foundation.layout.WindowInsets
32import androidx.compose.foundation.layout.ime
31import androidx.compose.foundation.layout.ime
@@ -43,10 +42,8 @@ import androidx.compose.foundation.text.KeyboardOptions
43import androidx.compose.material.icons.Icons
42import androidx.compose.material.icons.Icons
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
43import androidx.compose.material.icons.automirrored.filled.ArrowBack
45import androidx.compose.material.icons.automirrored.filled.Send
44import androidx.compose.material.icons.automirrored.filled.Send
46−import androidx.compose.material.icons.filled.ChatBubbleOutline
47import androidx.compose.material.icons.filled.Close
45import androidx.compose.material.icons.filled.Close
48import androidx.compose.material.icons.filled.KeyboardArrowDown
46import androidx.compose.material.icons.filled.KeyboardArrowDown
49−import androidx.compose.material.icons.filled.KeyboardArrowUp
50import androidx.compose.material.icons.filled.Stop
47import androidx.compose.material.icons.filled.Stop
51import androidx.compose.material3.CircularProgressIndicator
48import androidx.compose.material3.CircularProgressIndicator
52import androidx.compose.material3.ExperimentalMaterial3Api
49import androidx.compose.material3.ExperimentalMaterial3Api
@@ -61,7 +58,6 @@ import androidx.compose.material3.OutlinedTextField
61import androidx.compose.material3.Scaffold
58import androidx.compose.material3.Scaffold
62import androidx.compose.material3.Surface
59import androidx.compose.material3.Surface
63import androidx.compose.material3.Text
60import androidx.compose.material3.Text
64−import androidx.compose.material3.TextButton
65import androidx.compose.material3.TopAppBar
61import androidx.compose.material3.TopAppBar
66import androidx.compose.runtime.Composable
62import androidx.compose.runtime.Composable
67import androidx.compose.runtime.LaunchedEffect
63import androidx.compose.runtime.LaunchedEffect
@@ -75,7 +71,6 @@ import androidx.compose.ui.Alignment
75import androidx.compose.ui.Modifier
71import androidx.compose.ui.Modifier
76import androidx.compose.ui.draw.clip
72import androidx.compose.ui.draw.clip
77import androidx.compose.ui.hapticfeedback.HapticFeedbackType
73import androidx.compose.ui.hapticfeedback.HapticFeedbackType
78−import androidx.compose.ui.platform.LocalClipboardManager
79import androidx.compose.ui.platform.LocalContext
74import androidx.compose.ui.platform.LocalContext
80import androidx.compose.ui.platform.LocalDensity
75import androidx.compose.ui.platform.LocalDensity
81import androidx.compose.ui.platform.LocalHapticFeedback
76import androidx.compose.ui.platform.LocalHapticFeedback
@@ -113,12 +108,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
113 }
108 }
114 }
109 }
115
110
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
111 // 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.
112 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
124 var lastSeenCount by remember { mutableStateOf(0) }
113 var lastSeenCount by remember { mutableStateOf(0) }
@@ -205,24 +194,12 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
205 }
194 }
206 Box(Modifier.fillMaxWidth().weight(1f)) {
195 Box(Modifier.fillMaxWidth().weight(1f)) {
207 if (state.messages.isEmpty() && !state.loading) {
196 if (state.messages.isEmpty() && !state.loading) {
208− Column(
197+ Text(
198+ text = "Send a message to start the conversation.",
199+ style = MaterialTheme.typography.bodyMedium,
200+ color = MaterialTheme.colorScheme.onSurfaceVariant,
209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
201 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210− horizontalAlignment = Alignment.CenterHorizontally,
211− ) {
202+ )
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− }
226 }
203 }
227 LazyColumn(
204 LazyColumn(
228 state = listState,
205 state = listState,
@@ -269,14 +246,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
269 }
246 }
270 },
247 },
271 )
248 )
272− ScrollToTopButton(
273− visible = showScrollTop,
274− onClick = {
275− coroutineScope.launch {
276− listState.animateScrollToItem(0)
277− }
278− },
279− )
280 }
249 }
281 }
250 }
282 }
251 }
@@ -316,30 +285,6 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
316 }
285 }
317}
286}
318
287
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−
343private fun copyToClipboard(context: Context, text: String) {
288private fun copyToClipboard(context: Context, text: String) {
344 val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
289 val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
345 clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
290 clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
@@ -497,56 +442,19 @@ private fun ChatInputBar(
497 onStop: () -> Unit,
442 onStop: () -> Unit,
498) {
443) {
499 val haptic = LocalHapticFeedback.current
444 val haptic = LocalHapticFeedback.current
500− val clipboardManager = LocalClipboardManager.current
501 Surface(tonalElevation = 3.dp) {
445 Surface(tonalElevation = 3.dp) {
502− Column(
503− modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504− ) {
505 Row(
446 Row(
506− modifier = Modifier.fillMaxWidth(),
447+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
507 verticalAlignment = Alignment.Bottom,
448 verticalAlignment = Alignment.Bottom,
508 horizontalArrangement = Arrangement.spacedBy(8.dp),
449 horizontalArrangement = Arrangement.spacedBy(8.dp),
509 ) {
450 ) {
510 OutlinedTextField(
451 OutlinedTextField(
511 value = draft,
452 value = draft,
512 onValueChange = onDraftChange,
453 onValueChange = onDraftChange,
513− modifier = Modifier.weight(1f).heightIn(min = 48.dp),
454+ modifier = Modifier.weight(1f),
514 enabled = !loading,
455 enabled = !loading,
515 placeholder = { Text("Message opencode…") },
456 placeholder = { Text("Message opencode…") },
516 maxLines = 5,
457 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),
458 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551 keyboardActions = KeyboardActions(onSend = {
459 keyboardActions = KeyboardActions(onSend = {
552 if (!generating && !loading && draft.isNotBlank()) onSend()
460 if (!generating && !loading && draft.isNotBlank()) onSend()
@@ -574,17 +482,5 @@ private fun ChatInputBar(
574 }
482 }
575 }
483 }
576 }
484 }
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− }
589 }
485 }
590}
486}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+2−25
@@ -155,15 +155,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
155 },
155 },
156 modifier = Modifier.fillMaxWidth(),
156 modifier = Modifier.fillMaxWidth(),
157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
158− keyboardActions = KeyboardActions(onGo = {
158+ keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
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− }),
167 enabled = !state.loading,
159 enabled = !state.loading,
168 )
160 )
169 Spacer(Modifier.height(4.dp))
161 Spacer(Modifier.height(4.dp))
@@ -178,10 +170,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
178
170
179 Button(
171 Button(
180 onClick = { dispatch(Event.Connect) },
172 onClick = { dispatch(Event.Connect) },
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() &&
173+ enabled = !state.loading && state.serverUrl.isNotBlank(),
184− (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
185 modifier = Modifier.fillMaxWidth(),
174 modifier = Modifier.fillMaxWidth(),
186 ) {
175 ) {
187 if (state.loading) {
176 if (state.loading) {
@@ -195,18 +184,6 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
195 }
184 }
196 }
185 }
197
186
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−
210 // Surface the error inline as well, so it stays visible while the user
187 // Surface the error inline as well, so it stays visible while the user
211 // corrects the form (the snackbar is transient).
188 // corrects the form (the snackbar is transient).
212 if (state.error != null && !state.loading) {
189 if (state.error != null && !state.loading) {
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+2−40
@@ -21,8 +21,6 @@ import androidx.compose.foundation.layout.padding
21import androidx.compose.foundation.layout.size
21import androidx.compose.foundation.layout.size
22import androidx.compose.foundation.lazy.LazyColumn
22import androidx.compose.foundation.lazy.LazyColumn
23import androidx.compose.foundation.lazy.items
23import androidx.compose.foundation.lazy.items
24−import androidx.compose.foundation.lazy.rememberLazyListState
25−import androidx.compose.foundation.shape.CircleShape
26import androidx.compose.material.icons.Icons
24import androidx.compose.material.icons.Icons
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
25import androidx.compose.material.icons.automirrored.filled.ArrowBack
28import androidx.compose.material.icons.filled.Add
26import androidx.compose.material.icons.filled.Add
@@ -58,12 +56,9 @@ import androidx.compose.runtime.remember
58import androidx.compose.runtime.setValue
56import androidx.compose.runtime.setValue
59import androidx.compose.ui.Alignment
57import androidx.compose.ui.Alignment
60import androidx.compose.ui.Modifier
58import androidx.compose.ui.Modifier
61−import androidx.compose.ui.draw.clip
62−import androidx.compose.ui.graphics.Color
63import androidx.compose.ui.hapticfeedback.HapticFeedbackType
59import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64import androidx.compose.ui.platform.LocalContext
60import androidx.compose.ui.platform.LocalContext
65import androidx.compose.ui.platform.LocalHapticFeedback
61import androidx.compose.ui.platform.LocalHapticFeedback
66−import androidx.compose.ui.text.style.TextAlign
67import androidx.compose.ui.text.style.TextOverflow
62import androidx.compose.ui.text.style.TextOverflow
68import androidx.compose.ui.unit.dp
63import androidx.compose.ui.unit.dp
69import soy.iko.opencode.core.Event
64import soy.iko.opencode.core.Event
@@ -77,15 +72,6 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
77 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
72 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
78 var isPullRefreshing by remember { mutableStateOf(false) }
73 var isPullRefreshing by remember { mutableStateOf(false) }
79 var searchQuery by remember { mutableStateOf("") }
74 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− }
89
75
90 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
76 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
91 // every loading operation. Clear it once the underlying load completes.
77 // every loading operation. Clear it once the underlying load completes.
@@ -119,23 +105,7 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
119 Scaffold(
105 Scaffold(
120 topBar = {
106 topBar = {
121 TopAppBar(
107 TopAppBar(
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")
108+ title = { Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "Sessions") },
137− }
138− },
139 navigationIcon = {
109 navigationIcon = {
140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
110 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
111 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -199,7 +169,6 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
199 state = rememberPullToRefreshState(),
169 state = rememberPullToRefreshState(),
200 ) {
170 ) {
201 LazyColumn(
171 LazyColumn(
202− state = sessionsListState,
203 modifier = Modifier.fillMaxSize(),
172 modifier = Modifier.fillMaxSize(),
204 contentPadding = PaddingValues(bottom = 88.dp),
173 contentPadding = PaddingValues(bottom = 88.dp),
205 ) {
174 ) {
@@ -287,7 +256,7 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
287 Icon(
256 Icon(
288 Icons.Filled.DeleteOutline,
257 Icons.Filled.DeleteOutline,
289 contentDescription = "Delete session",
258 contentDescription = "Delete session",
290− tint = MaterialTheme.colorScheme.error,
259+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
291 )
260 )
292 }
261 }
293 }
262 }
@@ -391,12 +360,5 @@ private fun EmptySessions() {
391 style = MaterialTheme.typography.bodyMedium,
360 style = MaterialTheme.typography.bodyMedium,
392 color = MaterialTheme.colorScheme.onSurfaceVariant,
361 color = MaterialTheme.colorScheme.onSurfaceVariant,
393 )
362 )
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− )
401 }
363 }
402}
364}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt−10
@@ -17,11 +17,6 @@ private val DarkColors = darkColorScheme(
17 primaryContainer = Color(0xFF1A3D2A),
17 primaryContainer = Color(0xFF1A3D2A),
18 onPrimaryContainer = Color(0xFFA8E6C1),
18 onPrimaryContainer = Color(0xFFA8E6C1),
19 secondary = EmeraldDark,
19 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),
20 tertiaryContainer = Color(0xFF2A2A3D),
26 onTertiaryContainer = Color(0xFFC5C5E6),
21 onTertiaryContainer = Color(0xFFC5C5E6),
27 errorContainer = Color(0xFF4D2626),
22 errorContainer = Color(0xFF4D2626),
@@ -38,11 +33,6 @@ private val LightColors = lightColorScheme(
38 primaryContainer = Color(0xFFD7F5E3),
33 primaryContainer = Color(0xFFD7F5E3),
39 onPrimaryContainer = Color(0xFF0A3D22),
34 onPrimaryContainer = Color(0xFF0A3D22),
40 secondary = Emerald,
35 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),
36 tertiaryContainer = Color(0xFFE8E8F5),
47 onTertiaryContainer = Color(0xFF2A2A4D),
37 onTertiaryContainer = Color(0xFF2A2A4D),
48 errorContainer = Color(0xFFFFE0E0),
38 errorContainer = Color(0xFFFFE0E0),