git.iko.soy/opencode-android
on 9ffe468 help sign in
12 files changed+130−1209
since splitsnapshots
unifiedsplit
app/src/main/java/soy/iko/opencode/CoreViewModel.kt−14 app/src/main/java/soy/iko/opencode/MainActivity.kt+1−7 app/src/main/java/soy/iko/opencode/core/HttpClient.kt−1 app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+38−195 app/src/main/java/soy/iko/opencode/core/SseClient.kt−1 app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+11−65 app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+22−293 app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+18−322 app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+4−91 app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+35−183 app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+1−23 shared/src/app.rs−14
app/src/main/java/soy/iko/opencode/CoreViewModel.kt−14
@@ -23,23 +23,11 @@ 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)) }
2926
3027 // On a fresh process after a configuration change, resume the SSE stream if
3128 // the core is already connected (no-op otherwise — it guards on `connected`).
3229 core.resumeStreamingIfConnected()
3330
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−
4331 // Persist connection details once a connection succeeds.
4432 viewModelScope.launch {
4533 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
@@ -47,7 +35,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
4735 prefs.edit {
4836 putString(KEY_URL, state.serverUrl)
4937 putString(KEY_USER, state.username)
50− putString(KEY_PASSWORD, state.password)
5138 }
5239 }
5340 }
@@ -61,6 +48,5 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
6148 private companion object {
6249 const val KEY_URL = "serverUrl"
6350 const val KEY_USER = "username"
64− const val KEY_PASSWORD = "password"
6551 }
6652}
app/src/main/java/soy/iko/opencode/MainActivity.kt+1−7
@@ -2,7 +2,6 @@ package soy.iko.opencode
22
33import android.os.Bundle
44import androidx.activity.ComponentActivity
5−import androidx.activity.SystemBarStyle
65import androidx.activity.compose.setContent
76import androidx.activity.enableEdgeToEdge
87import androidx.compose.runtime.getValue
@@ -13,12 +12,7 @@ import soy.iko.opencode.ui.theme.OpencodeTheme
1312
1413class MainActivity : ComponentActivity() {
1514 override fun onCreate(savedInstanceState: Bundle?) {
16− enableEdgeToEdge(
17− statusBarStyle = SystemBarStyle.auto(
18− lightScrim = 0xFF0F1115.toInt(),
19− darkScrim = 0xFF0F1115.toInt(),
20− ),
21− )
15+ enableEdgeToEdge()
2216 super.onCreate(savedInstanceState)
2317 setContent {
2418 OpencodeTheme {
app/src/main/java/soy/iko/opencode/core/HttpClient.kt−1
@@ -51,7 +51,6 @@ 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")
5554 if (auth != null) builder.header("Authorization", auth)
5655 await(okhttp.newCall(builder.build()))
5756 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+38−195
@@ -1,7 +1,6 @@
11package soy.iko.opencode.core
22
33import kotlinx.coroutines.CoroutineScope
4−import kotlinx.coroutines.Job
54import kotlinx.coroutines.delay
65import kotlinx.coroutines.flow.MutableStateFlow
76import kotlinx.coroutines.flow.StateFlow
@@ -49,31 +48,6 @@ class OpencodeCore(
4948 private var sse: SseClient? = null
5049 private var sseClosedIntentionally = false
5150 private var reconnectAttempts = 0
52− private var reconnectJob: Job? = null
53−
54− // Guards against overlapping session refreshes: rapid taps launch multiple
55− // loadSessions coroutines and the slowest-to-return would otherwise win.
56− 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
75− // Message IDs removed via SSE; a late MessageUpdated for one must not resurrect it.
76− private val removedMessageIds = mutableSetOf<String>()
7751
7852 // ── Event entry point ──────────────────────────────────────────────────────
7953 fun dispatch(event: Event) {
@@ -81,11 +55,9 @@ class OpencodeCore(
8155 // Store the field verbatim while typing; normalizing here would fight
8256 // the user's edits (e.g. eat the "://" as they type it). The URL is
8357 // normalized once, on Connect.
84− // Clear any prior error as soon as the user edits a field, so a stale
85− // message (e.g. "Invalid credentials") doesn't linger while they correct it.
86− is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
87− is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
88− is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
58+ is Event.ServerUrlChanged -> { serverUrl = event.url; emit() }
59+ is Event.UsernameChanged -> { username = event.value; emit() }
60+ is Event.PasswordChanged -> { password = event.value; emit() }
8961
9062 Event.Connect -> {
9163 serverUrl = normalizeUrl(serverUrl)
@@ -93,57 +65,31 @@ class OpencodeCore(
9365 // The auth fields are showing but empty — sending the request now
9466 // would just 401 again in a loop. Prompt for credentials instead.
9567 if (authRequired && !hasCredentials()) { error = "Enter username and password"; emit(); return }
96− // Leave authRequired as-is; probeHealth sets it from the response (true on
97− // 401, false on success). Resetting it here just flickers the auth fields.
98− loading = true; error = null; emit()
99− connectJob?.cancel()
100− connectJob = scope.launch { probeHealth() }
68+ loading = true; error = null; authRequired = false; emit()
69+ scope.launch { probeHealth() }
10170 }
10271
103− Event.LoadSessions -> {
104− if (!connected) { error = "Not connected"; emit(); return }
105− loading = true; emit()
106− loadSessionsJob?.cancel()
107− loadSessionsJob = scope.launch { loadSessions() }
108− }
72+ Event.LoadSessions -> { loading = true; emit(); scope.launch { loadSessions() } }
10973
11074 is Event.SelectSession -> {
111− // The session may have been deleted (e.g. via SSE) while the list was on
112− // screen; opening it would only 404 on loadMessages. Bail with an error.
113− val session = sessions.firstOrNull { it.id == event.id }
114− if (session == null) { error = "Session no longer exists"; emit(); return }
115− currentSessionTitle = session.title
75+ currentSessionTitle = sessions.firstOrNull { it.id == event.id }?.title.orEmpty()
11676 currentSessionId = event.id
11777 messages.clear()
118− removedMessageIds.clear()
11978 screen = Screen.Chat
12079 loading = true
121− generating = false
12280 error = null
12381 emit()
124− connectJob?.cancel()
125− abortJob?.cancel()
126− sendMessageJob?.cancel()
127− deleteSessionJob?.cancel()
128− loadMessagesJob?.cancel()
129− loadMessagesJob = scope.launch { loadMessages(event.id) }
82+ scope.launch { loadMessages(event.id) }
13083 }
13184
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− }
85+ Event.CreateSession -> { loading = true; emit(); scope.launch { createSession() } }
13886
13987 is Event.DeleteSession -> {
140− if (!connected) { error = "Not connected"; emit(); return }
14188 val id = event.id
14289 // Delete on the server first; only drop it from the UI once that
14390 // succeeds, so a failed request leaves the session recoverable.
144− loading = true; error = null; emit()
145− deleteSessionJob?.cancel()
146− deleteSessionJob = scope.launch {
91+ loading = true; emit()
92+ scope.launch {
14793 http.delete("$serverUrl/session/$id", authHeader()).fold(
14894 onSuccess = { resp ->
14995 if (resp.code in 200..299) {
@@ -176,32 +122,17 @@ class OpencodeCore(
176122 messages.forEach { it.streaming = false }
177123 emit()
178124 val id = currentSessionId ?: return
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()) }
125+ scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
183126 }
184127
185128 Event.NavigateToSessions -> {
186129 screen = Screen.Sessions
187130 currentSessionId = null
188131 messages.clear()
189− removedMessageIds.clear()
190− draft = ""
191132 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
195133 loading = true
196134 emit()
197− connectJob?.cancel()
198− abortJob?.cancel()
199− createSessionJob?.cancel()
200− deleteSessionJob?.cancel()
201− sendMessageJob?.cancel()
202− loadMessagesJob?.cancel()
203− loadSessionsJob?.cancel()
204− loadSessionsJob = scope.launch { loadSessions() }
135+ scope.launch { loadSessions() }
205136 }
206137
207138 Event.NavigateToConnect -> {
@@ -211,18 +142,7 @@ class OpencodeCore(
211142 generating = false
212143 sessions.clear()
213144 messages.clear()
214− removedMessageIds.clear()
215145 currentSessionId = null
216− draft = ""
217− // Reset to the default so a late-firing close callback from the old
218− // SSE connection can't flash the reconnecting banner on the next connect.
219− sseConnected = true
220− connectJob?.cancel()
221− abortJob?.cancel()
222− createSessionJob?.cancel()
223− deleteSessionJob?.cancel()
224− sendMessageJob?.cancel()
225− loadMessagesJob?.cancel()
226146 closeSse()
227147 emit()
228148 }
@@ -236,44 +156,26 @@ class OpencodeCore(
236156 if (connected && sse == null) startSse()
237157 }
238158
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− }
159+ fun shutdown() = closeSse()
251160
252161 // ── Effects ────────────────────────────────────────────────────────────────
253162 private fun sendMessage(raw: String) {
254163 val text = raw.trim()
255164 val session = currentSessionId ?: return
256165 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
260166 localSeq += 1
261167 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
262168 status = MessageStatus.Pending
263169 textParts["local"] = text
264170 }
265171 messages.add(user)
266− // Keep the draft text so we can restore it if the send fails; otherwise the
267− // user's message is lost and they'd have to retype it.
268− val savedDraft = draft
269172 draft = ""
270173 generating = true
271174 error = null
272175 emit()
273176
274177 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275− sendMessageJob?.cancel()
276− sendMessageJob = scope.launch {
178+ scope.launch {
277179 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
278180 result.fold(
279181 onSuccess = { resp ->
@@ -282,16 +184,12 @@ class OpencodeCore(
282184 } else {
283185 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
284186 generating = false
285− messages.forEach { it.streaming = false }
286− draft = savedDraft
287187 error = "Server returned status ${resp.code}"
288188 }
289189 },
290190 onFailure = { e ->
291191 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
292192 generating = false
293− messages.forEach { it.streaming = false }
294− draft = savedDraft
295193 error = "Request failed: ${e.message}"
296194 },
297195 )
@@ -306,10 +204,6 @@ class OpencodeCore(
306204 when {
307205 resp.code == 401 -> {
308206 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
313207 // Always reveal the auth fields so the user can see/edit
314208 // their credentials — even when the ones supplied were wrong.
315209 authRequired = true
@@ -324,14 +218,10 @@ class OpencodeCore(
324218 loading = true
325219 emit()
326220 startSse()
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() }
221+ loadSessions()
331222 }
332223 else -> {
333224 loading = false
334− connected = false
335225 error = "Server returned status ${resp.code}"
336226 emit()
337227 }
@@ -339,7 +229,6 @@ class OpencodeCore(
339229 },
340230 onFailure = { e ->
341231 loading = false
342− connected = false
343232 error = "Connection failed: ${e.message}"
344233 emit()
345234 },
@@ -352,9 +241,6 @@ class OpencodeCore(
352241 if (resp.code in 200..299) {
353242 sessions.clear()
354243 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() }
358244 } else {
359245 error = "Server returned status ${resp.code}"
360246 }
@@ -372,10 +258,6 @@ class OpencodeCore(
372258 if (session != null) {
373259 if (sessions.none { it.id == session.id }) {
374260 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() }
379261 }
380262 emit()
381263 // SelectSession takes over the loading state (loads messages).
@@ -397,7 +279,6 @@ class OpencodeCore(
397279 loading = false
398280 if (resp.code in 200..299) {
399281 messages.clear()
400− removedMessageIds.clear()
401282 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
402283 generating = messages.any { it.streaming }
403284 } else {
@@ -408,7 +289,6 @@ class OpencodeCore(
408289 onFailure = { e ->
409290 if (!isCurrent(sessionId)) { loading = false; return }
410291 loading = false
411− generating = false
412292 error = "Request failed: ${e.message}"
413293 emit()
414294 },
@@ -437,8 +317,6 @@ class OpencodeCore(
437317
438318 private fun closeSse() {
439319 sseClosedIntentionally = true
440− reconnectJob?.cancel()
441− reconnectJob = null
442320 sse?.close()
443321 sse = null
444322 }
@@ -449,10 +327,7 @@ class OpencodeCore(
449327 // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
450328 val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
451329 if (delayMs < 30_000L) reconnectAttempts += 1
452− // Cancel any pending reconnect so rapid network flapping can't stack multiple
453− // coroutines that each open a new SSE connection.
454− reconnectJob?.cancel()
455− reconnectJob = scope.launch {
330+ scope.launch {
456331 delay(delayMs)
457332 if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
458333 }
@@ -460,20 +335,15 @@ class OpencodeCore(
460335
461336 private fun handleServerEvent(json: String) {
462337 val event = Protocol.parseEvent(json) ?: return
463− // Only re-render if the event actually changed our state; applyEvent returns
464− // false for events that don't apply (other session, unknown message, …).
465− if (applyEvent(event)) emit()
338+ applyEvent(event)
339+ emit()
466340 }
467341
468− /** Apply a server event to the model. Returns true iff any state actually changed. */
469− private fun applyEvent(event: Protocol.Event): Boolean {
342+ private fun applyEvent(event: Protocol.Event) {
470343 when (event) {
471344 is Protocol.Event.MessageUpdated -> {
472345 val info = event.info
473− if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
474− // A MessageRemoved may have arrived before this (late/out-of-order) update;
475− // don't re-create a message the server has already deleted.
476− if (info.id in removedMessageIds) return false
346+ if (info.role != "assistant" || !isCurrent(info.sessionId)) return
477347 val streaming = info.time.completed == null && info.error == null
478348 val existing = messages.firstOrNull { it.id == info.id }
479349 if (existing != null) {
@@ -482,59 +352,39 @@ class OpencodeCore(
482352 } else {
483353 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
484354 }
485− info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
486− return true
355+ info.error?.let { error = it.message(); generating = false }
487356 }
488357
489358 is Protocol.Event.PartUpdated -> {
490359 val part = event.part
491− val msg = messages.firstOrNull { it.id == part.messageId } ?: return false
492− // Synthetic text parts are intentionally skipped; report no change so we
493− // don't trigger a needless re-render/emit for them.
494− return when (part) {
495− is Protocol.Part.Text -> if (part.synthetic) {
496− false
497− } else {
360+ val msg = messages.firstOrNull { it.id == part.messageId } ?: return
361+ when (part) {
362+ is Protocol.Part.Text -> if (!part.synthetic) {
498363 msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
499− true
500364 }
501− is Protocol.Part.Reasoning -> {
365+ is Protocol.Part.Reasoning ->
502366 msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
503− true
504− }
505− is Protocol.Part.Tool -> {
367+ is Protocol.Part.Tool ->
506368 msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
507− true
508− }
509369 }
510370 }
511371
512− is Protocol.Event.PartRemoved -> {
513− val msg = messages.firstOrNull { it.id == event.messageId } ?: return false
514− msg.remove(event.partId)
515− return true
516− }
372+ is Protocol.Event.PartRemoved -> messages.firstOrNull { it.id == event.messageId }?.remove(event.partId)
517373
518− is Protocol.Event.MessageRemoved -> {
519− // Remember the ID so a late MessageUpdated can't resurrect the message.
520− removedMessageIds.add(event.messageId)
521− return messages.removeAll { it.id == event.messageId }
522− }
374+ is Protocol.Event.MessageRemoved -> messages.removeAll { it.id == event.messageId }
523375
524− is Protocol.Event.SessionIdle -> {
525− if (!isCurrent(event.sessionId)) return false
376+ is Protocol.Event.SessionIdle -> if (isCurrent(event.sessionId)) {
526377 generating = false
527378 messages.forEach { it.streaming = false }
528− return true
529379 }
530380
531381 is Protocol.Event.SessionError -> {
532382 val scoped = event.sessionId == null || isCurrent(event.sessionId)
533− if (!scoped) return false
534− event.error?.let { error = it.message() }
535− generating = false
536− messages.forEach { it.streaming = false }
537− return true
383+ if (scoped) {
384+ event.error?.let { error = it.message() }
385+ generating = false
386+ messages.forEach { it.streaming = false }
387+ }
538388 }
539389
540390 is Protocol.Event.SessionUpserted -> {
@@ -545,26 +395,19 @@ class OpencodeCore(
545395 } else {
546396 sessions.add(0, SessionView(event.info.id, title))
547397 }
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() }
551398 if (isCurrent(event.info.id)) currentSessionTitle = title
552− return true
553399 }
554400
555− is Protocol.Event.SessionDeleted -> {
556− val id = event.sessionId ?: return false
557− val removed = sessions.removeAll { it.id == id }
401+ is Protocol.Event.SessionDeleted -> event.sessionId?.let { id ->
402+ sessions.removeAll { it.id == id }
558403 if (isCurrent(id)) {
559404 currentSessionId = null
560405 messages.clear()
561406 screen = Screen.Sessions
562− return true
563407 }
564− return removed
565408 }
566409
567− Protocol.Event.Other -> return false
410+ Protocol.Event.Other -> Unit
568411 }
569412 }
570413
app/src/main/java/soy/iko/opencode/core/SseClient.kt−1
@@ -33,7 +33,6 @@ 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")
3736 if (auth != null) builder.header("Authorization", auth)
3837 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
3938 }
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+11−65
@@ -2,24 +2,20 @@ package soy.iko.opencode.ui
22
33import androidx.activity.compose.BackHandler
44import androidx.compose.animation.AnimatedContent
5−import androidx.compose.animation.slideInHorizontally
6−import androidx.compose.animation.slideOutHorizontally
5+import androidx.compose.animation.SizeTransform
6+import androidx.compose.animation.fadeIn
7+import androidx.compose.animation.fadeOut
78import androidx.compose.animation.togetherWith
89import androidx.compose.foundation.layout.fillMaxSize
910import androidx.compose.foundation.layout.padding
10−import androidx.compose.material3.AlertDialog
1111import androidx.compose.material3.Scaffold
1212import androidx.compose.material3.SnackbarDuration
1313import androidx.compose.material3.SnackbarHost
1414import androidx.compose.material3.SnackbarHostState
15−import androidx.compose.material3.Text
16−import androidx.compose.material3.TextButton
15+import androidx.compose.material3.SnackbarResult
1716import androidx.compose.runtime.Composable
1817import androidx.compose.runtime.LaunchedEffect
19−import androidx.compose.runtime.getValue
20−import androidx.compose.runtime.mutableStateOf
2118import androidx.compose.runtime.remember
22−import androidx.compose.runtime.setValue
2319import androidx.compose.ui.Modifier
2420import soy.iko.opencode.core.Event
2521import soy.iko.opencode.core.Screen
@@ -31,16 +27,17 @@ import soy.iko.opencode.ui.screens.SessionsScreen
3127@Composable
3228fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
3329 val snackbar = remember { SnackbarHostState() }
34− var showStopConfirm by remember { mutableStateOf(false) }
35− var showDisconnectConfirm by remember { mutableStateOf(false) }
3630
3731 LaunchedEffect(state.error) {
3832 state.error?.let {
39− snackbar.showSnackbar(
33+ val result = snackbar.showSnackbar(
4034 message = it,
4135 actionLabel = "Dismiss",
4236 duration = SnackbarDuration.Short,
4337 )
38+ if (result == SnackbarResult.ActionPerformed) {
39+ dispatch(Event.DismissError)
40+ }
4441 // Always clear the error from state after showing.
4542 dispatch(Event.DismissError)
4643 }
@@ -48,69 +45,18 @@ fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
4845
4946 BackHandler(enabled = state.screen != Screen.Connect) {
5047 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)
53− // Disconnecting drops the server session, so guard the back button.
54− Screen.Sessions -> showDisconnectConfirm = true
48+ Screen.Chat -> dispatch(Event.NavigateToSessions)
49+ Screen.Sessions -> dispatch(Event.NavigateToConnect)
5550 Screen.Connect -> Unit
5651 }
5752 }
5853
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−
10254 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
10355 AnimatedContent(
10456 targetState = state.screen,
10557 modifier = Modifier.fillMaxSize().padding(padding),
10658 transitionSpec = {
107− // Compare screen ordinals to decide slide direction: forward navigation
108− // (Connect → Sessions → Chat) slides in from the right, back slides from the left.
109− if (targetState.ordinal > initialState.ordinal) {
110− slideInHorizontally { it } togetherWith slideOutHorizontally { -it }
111− } else {
112− slideInHorizontally { -it } togetherWith slideOutHorizontally { it }
113− }
59+ (fadeIn() togetherWith fadeOut()).using(SizeTransform(clip = false))
11460 },
11561 label = "screen",
11662 ) { screen ->
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+22−293
@@ -3,8 +3,6 @@ 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
86import android.widget.Toast
97import androidx.compose.foundation.ExperimentalFoundationApi
108import androidx.compose.foundation.background
@@ -15,20 +13,14 @@ import androidx.compose.foundation.layout.Column
1513import androidx.compose.foundation.layout.Row
1614import androidx.compose.foundation.layout.fillMaxWidth
1715import androidx.compose.foundation.layout.padding
18−import androidx.compose.foundation.layout.size
1916import androidx.compose.foundation.layout.widthIn
2017import androidx.compose.foundation.shape.RoundedCornerShape
21−import androidx.compose.foundation.text.selection.SelectionContainer
2218import androidx.compose.material.icons.Icons
2319import androidx.compose.material.icons.filled.Build
24−import androidx.compose.material.icons.filled.Check
2520import androidx.compose.material.icons.filled.ErrorOutline
2621import androidx.compose.material.icons.filled.ExpandLess
2722import androidx.compose.material.icons.filled.ExpandMore
2823import 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
3224import androidx.compose.material3.Icon
3325import androidx.compose.material3.MaterialTheme
3426import androidx.compose.material3.Text
@@ -42,20 +34,9 @@ import androidx.compose.ui.Modifier
4234import androidx.compose.ui.draw.clip
4335import androidx.compose.ui.graphics.Color
4436import androidx.compose.ui.platform.LocalContext
45−import androidx.compose.ui.text.AnnotatedString
46−import androidx.compose.ui.text.LinkAnnotation
47−import androidx.compose.ui.text.SpanStyle
48−import androidx.compose.ui.text.TextLinkStyles
49−import androidx.compose.ui.text.buildAnnotatedString
50−import androidx.compose.ui.text.font.FontFamily
5137import androidx.compose.ui.text.font.FontStyle
52−import androidx.compose.ui.text.font.FontWeight
53−import androidx.compose.ui.text.withLink
54−import androidx.compose.ui.text.withStyle
55−import androidx.compose.ui.text.style.TextDecoration
5638import androidx.compose.ui.text.style.TextOverflow
5739import androidx.compose.ui.unit.dp
58−import androidx.compose.ui.unit.sp
5940import soy.iko.opencode.core.MessageStatus
6041import soy.iko.opencode.core.MessageView
6142import soy.iko.opencode.core.ToolView
@@ -65,7 +46,7 @@ private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
6546
6647@OptIn(ExperimentalFoundationApi::class)
6748@Composable
68−fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
49+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
6950 val isUser = message.isUser
7051 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
7152 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
@@ -78,20 +59,11 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
7859 )
7960
8061 val context = LocalContext.current
81− var showMenu by remember { mutableStateOf(false) }
8262
8363 Row(
84− modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
64+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
8565 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
8666 ) {
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− }
9567 Column(
9668 modifier = Modifier
9769 .fillMaxWidth(0.85f)
@@ -102,67 +74,25 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
10274 onClick = {},
10375 onLongClick = {
10476 if (message.text.isNotEmpty()) {
105− showMenu = true
77+ copyToClipboard(context, message.text)
78+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
10679 }
10780 },
10881 )
10982 .padding(horizontal = 14.dp, vertical = 10.dp),
11083 ) {
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− }
84+ message.reasoning?.let { ReasoningBlock(it) }
12885
129− message.reasoning?.let { ReasoningBlock(it, context) }
86+ message.tools.forEach { ToolRow(it) }
13087
131− // Give a quick overview of how many tools ran before listing them.
132− if (message.tools.size > 1) {
88+ if (message.text.isNotEmpty()) {
13389 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),
90+ text = message.text + if (message.streaming) " ▌" else "",
91+ color = textColor,
92+ style = MaterialTheme.typography.bodyLarge,
13893 )
139− }
140−
141− message.tools.forEach { ToolRow(it) }
142−
143− SelectionContainer {
144− 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− }
152− Text(
153− text = annotatedText,
154− color = textColor,
155− // Give assistant replies (often long, code-heavy) extra line
156− // spacing for readability; user bubbles keep the default.
157− style = if (isUser) {
158− MaterialTheme.typography.bodyLarge
159− } else {
160− MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp)
161− },
162− )
163− } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
164− Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
165− }
94+ } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
95+ Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
16696 }
16797
16898 if (message.time > 0) {
@@ -175,7 +105,7 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
175105 }
176106
177107 if (isUser && message.status != MessageStatus.Sent) {
178− StatusLine(message.status, onRetry = onRetry)
108+ StatusLine(message.status)
179109 }
180110 }
181111 }
@@ -186,172 +116,8 @@ private fun copyToClipboard(context: Context, text: String) {
186116 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
187117}
188118
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−
353119@Composable
354−private fun ReasoningBlock(text: String, context: Context) {
120+private fun ReasoningBlock(text: String) {
355121 var expanded by remember { mutableStateOf(false) }
356122 Column(modifier = Modifier.padding(bottom = 6.dp)) {
357123 Row(
@@ -377,17 +143,6 @@ private fun ReasoningBlock(text: String, context: Context) {
377143 color = MaterialTheme.colorScheme.onSurfaceVariant,
378144 modifier = Modifier.padding(top = 4.dp),
379145 )
380− Text(
381− text = "Copy",
382− style = MaterialTheme.typography.labelSmall,
383− color = MaterialTheme.colorScheme.primary,
384− modifier = Modifier
385− .padding(top = 4.dp)
386− .clickable {
387− copyToClipboard(context, text)
388− Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
389− },
390− )
391146 }
392147 }
393148}
@@ -395,13 +150,6 @@ private fun ReasoningBlock(text: String, context: Context) {
395150@Composable
396151private fun ToolRow(tool: ToolView) {
397152 var expanded by remember { mutableStateOf(false) }
398− val baseColor = MaterialTheme.colorScheme.onSurfaceVariant
399− val statusColor = when (tool.status) {
400− "completed", "success" -> MaterialTheme.colorScheme.primary
401− "error", "failed" -> MaterialTheme.colorScheme.error
402− "pending", "running", "in_progress" -> MaterialTheme.colorScheme.onSurfaceVariant
403− else -> MaterialTheme.colorScheme.onSurfaceVariant
404− }
405153 Row(
406154 verticalAlignment = Alignment.CenterVertically,
407155 modifier = Modifier
@@ -416,23 +164,14 @@ private fun ToolRow(tool: ToolView) {
416164 modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
417165 )
418166 Text(
419− text = buildAnnotatedString {
420− withStyle(SpanStyle(color = baseColor)) {
421− append(tool.name)
422− append(" · ")
423− }
424− withStyle(SpanStyle(color = statusColor)) {
425− append(tool.status)
426− }
427− if (expanded) tool.title?.let {
428− withStyle(SpanStyle(color = baseColor)) {
429− append(" — ")
430− append(it)
431− }
432− }
167+ text = buildString {
168+ append(tool.name)
169+ append(" · ")
170+ append(tool.status)
171+ if (expanded) tool.title?.let { append(" — "); append(it) }
433172 },
434173 style = MonoStyle,
435− color = baseColor,
174+ color = MaterialTheme.colorScheme.onSurfaceVariant,
436175 maxLines = if (expanded) Int.MAX_VALUE else 1,
437176 overflow = TextOverflow.Ellipsis,
438177 modifier = Modifier.weight(1f),
@@ -447,11 +186,11 @@ private fun ToolRow(tool: ToolView) {
447186}
448187
449188@Composable
450−private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
189+private fun StatusLine(status: MessageStatus) {
451190 val (icon, label, tint) = when (status) {
452191 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
453192 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
454− MessageStatus.Sent -> Triple(Icons.Filled.Check, "", Color.Unspecified)
193+ MessageStatus.Sent -> Triple(Icons.Filled.Schedule, "", Color.Unspecified)
455194 }
456195 Row(
457196 verticalAlignment = Alignment.CenterVertically,
@@ -465,15 +204,5 @@ private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
465204 color = tint,
466205 modifier = Modifier.padding(start = 4.dp),
467206 )
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− }
478207 }
479208}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+18−322
@@ -1,57 +1,36 @@
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
73import 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
134import androidx.compose.animation.fadeIn
145import androidx.compose.animation.fadeOut
156import androidx.compose.animation.scaleIn
167import androidx.compose.animation.scaleOut
17−import androidx.compose.foundation.ExperimentalFoundationApi
188import androidx.compose.foundation.background
19−import androidx.compose.foundation.clickable
20−import androidx.compose.foundation.combinedClickable
219import androidx.compose.foundation.layout.Arrangement
2210import androidx.compose.foundation.layout.Box
2311import androidx.compose.foundation.layout.BoxScope
2412import androidx.compose.foundation.layout.Column
2513import androidx.compose.foundation.layout.Row
26−import androidx.compose.foundation.layout.Spacer
2714import androidx.compose.foundation.layout.fillMaxSize
2815import androidx.compose.foundation.layout.fillMaxWidth
29−import androidx.compose.foundation.layout.heightIn
3016import androidx.compose.foundation.layout.PaddingValues
31−import androidx.compose.foundation.layout.WindowInsets
32−import androidx.compose.foundation.layout.ime
3317import androidx.compose.foundation.layout.imePadding
3418import androidx.compose.foundation.layout.padding
3519import androidx.compose.foundation.layout.size
3620import androidx.compose.foundation.lazy.LazyColumn
37−import androidx.compose.foundation.lazy.itemsIndexed
21+import androidx.compose.foundation.lazy.items
3822import androidx.compose.foundation.lazy.rememberLazyListState
3923import androidx.compose.foundation.shape.CircleShape
40−import androidx.compose.foundation.shape.RoundedCornerShape
4124import androidx.compose.foundation.text.KeyboardActions
4225import androidx.compose.foundation.text.KeyboardOptions
4326import androidx.compose.material.icons.Icons
4427import androidx.compose.material.icons.automirrored.filled.ArrowBack
4528import androidx.compose.material.icons.automirrored.filled.Send
46−import androidx.compose.material.icons.filled.ChatBubbleOutline
47−import androidx.compose.material.icons.filled.Close
4829import androidx.compose.material.icons.filled.KeyboardArrowDown
49−import androidx.compose.material.icons.filled.KeyboardArrowUp
5030import androidx.compose.material.icons.filled.Stop
5131import androidx.compose.material3.CircularProgressIndicator
5232import androidx.compose.material3.ExperimentalMaterial3Api
5333import androidx.compose.material3.FilledIconButton
54−import androidx.compose.material3.FilledTonalButton
5534import androidx.compose.material3.FloatingActionButton
5635import androidx.compose.material3.Icon
5736import androidx.compose.material3.IconButton
@@ -61,7 +40,6 @@ import androidx.compose.material3.OutlinedTextField
6140import androidx.compose.material3.Scaffold
6241import androidx.compose.material3.Surface
6342import androidx.compose.material3.Text
64−import androidx.compose.material3.TextButton
6543import androidx.compose.material3.TopAppBar
6644import androidx.compose.runtime.Composable
6745import androidx.compose.runtime.LaunchedEffect
@@ -75,13 +53,8 @@ import androidx.compose.ui.Alignment
7553import androidx.compose.ui.Modifier
7654import androidx.compose.ui.draw.clip
7755import 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
8156import androidx.compose.ui.platform.LocalHapticFeedback
82−import androidx.compose.ui.text.font.FontStyle
8357import androidx.compose.ui.text.input.ImeAction
84−import androidx.compose.ui.text.style.TextAlign
8558import androidx.compose.ui.text.style.TextOverflow
8659import androidx.compose.ui.unit.dp
8760import kotlinx.coroutines.launch
@@ -89,17 +62,11 @@ import soy.iko.opencode.core.Event
8962import soy.iko.opencode.core.UiState
9063import soy.iko.opencode.ui.components.MessageBubble
9164
92−@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
65+@OptIn(ExperimentalMaterial3Api::class)
9366@Composable
9467fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
9568 val listState = rememberLazyListState()
9669 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
10370
10471 // Show a jump-to-bottom button once the user scrolls up away from the latest
10572 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -113,12 +80,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
11380 }
11481 }
11582
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−
12283 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
12384 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
12485 var lastSeenCount by remember { mutableStateOf(0) }
@@ -148,20 +109,10 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
148109 topBar = {
149110 TopAppBar(
150111 title = {
151− val title = state.currentSessionTitle.ifEmpty { "Chat" }
152112 Text(
153− text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
113+ text = state.currentSessionTitle.ifEmpty { "Chat" },
154114 maxLines = 1,
155115 overflow = TextOverflow.Ellipsis,
156− modifier = Modifier.combinedClickable(
157− onClick = { dispatch(Event.NavigateToSessions) },
158− onLongClick = {
159− state.currentSessionId?.let { id ->
160− copyToClipboard(context, id)
161− Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
162− }
163− },
164− ),
165116 )
166117 },
167118 navigationIcon = {
@@ -183,7 +134,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
183134 ChatInputBar(
184135 draft = state.draft,
185136 generating = state.generating,
186− loading = state.loading && state.messages.isEmpty(),
187137 onDraftChange = { dispatch(Event.DraftChanged(it)) },
188138 onSend = { dispatch(Event.SendMessage(state.draft)) },
189139 onStop = { dispatch(Event.CancelGeneration) },
@@ -197,86 +147,35 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
197147 if (state.loading && state.messages.isEmpty()) {
198148 LinearProgressIndicator(Modifier.fillMaxWidth())
199149 }
200− if (state.error != null && state.messages.isNotEmpty()) {
201− ErrorBanner(
202− message = state.error,
203− onDismiss = { dispatch(Event.DismissError) },
204− )
205− }
206150 Box(Modifier.fillMaxWidth().weight(1f)) {
207151 if (state.messages.isEmpty() && !state.loading) {
208− Column(
152+ Text(
153+ text = "Send a message to start the conversation.",
154+ style = MaterialTheme.typography.bodyMedium,
155+ color = MaterialTheme.colorScheme.onSurfaceVariant,
209156 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210− horizontalAlignment = Alignment.CenterHorizontally,
211− ) {
212− Icon(
213− Icons.Filled.ChatBubbleOutline,
214− contentDescription = null,
215− modifier = Modifier.size(48.dp),
216− tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
217− )
218− Spacer(Modifier.size(16.dp))
219− Text(
220− text = "Send a message to start the conversation.",
221− style = MaterialTheme.typography.bodyMedium,
222− color = MaterialTheme.colorScheme.onSurfaceVariant,
223− textAlign = TextAlign.Center,
224− )
225− }
157+ )
226158 }
227159 LazyColumn(
228160 state = listState,
229161 modifier = Modifier.fillMaxSize(),
230162 contentPadding = PaddingValues(vertical = 8.dp),
231163 ) {
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− }
164+ items(state.messages, key = { it.id }) { message ->
165+ MessageBubble(message)
253166 }
254167 }
255168 ScrollToBottomButton(
256− visible = showScrollButton && !isImeVisible,
169+ visible = showScrollButton,
257170 showBadge = hasUnseenMessages,
258171 onClick = {
259172 coroutineScope.launch {
260173 if (state.messages.isNotEmpty()) {
261− // When the typing indicator is showing it occupies the item
262− // just past the last message, so scroll one further to reach it.
263− val target = if (state.generating && state.messages.none { it.streaming })
264− state.messages.size
265− else
266− state.messages.size - 1
267− listState.animateScrollToItem(target)
174+ listState.animateScrollToItem(state.messages.size - 1)
268175 }
269176 }
270177 },
271178 )
272− ScrollToTopButton(
273− visible = showScrollTop,
274− onClick = {
275− coroutineScope.launch {
276− listState.animateScrollToItem(0)
277− }
278− },
279− )
280179 }
281180 }
282181 }
@@ -316,123 +215,6 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
316215 }
317216}
318217
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−
436218@Composable
437219private fun ReconnectingBanner() {
438220 Surface(
@@ -458,109 +240,35 @@ private fun ReconnectingBanner() {
458240 }
459241}
460242
461−@Composable
462−private fun ErrorBanner(message: String, onDismiss: () -> Unit) {
463− Surface(
464− modifier = Modifier.fillMaxWidth(),
465− color = MaterialTheme.colorScheme.errorContainer,
466− ) {
467− Row(
468− modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 6.dp, bottom = 6.dp, end = 4.dp),
469− verticalAlignment = Alignment.CenterVertically,
470− horizontalArrangement = Arrangement.spacedBy(8.dp),
471− ) {
472− Text(
473− text = message,
474− style = MaterialTheme.typography.bodySmall,
475− color = MaterialTheme.colorScheme.onErrorContainer,
476− modifier = Modifier.weight(1f),
477− )
478− IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
479− Icon(
480− Icons.Filled.Close,
481− contentDescription = "Dismiss error",
482− tint = MaterialTheme.colorScheme.onErrorContainer,
483− modifier = Modifier.size(18.dp),
484− )
485− }
486− }
487− }
488−}
489−
490243@Composable
491244private fun ChatInputBar(
492245 draft: String,
493246 generating: Boolean,
494− loading: Boolean,
495247 onDraftChange: (String) -> Unit,
496248 onSend: () -> Unit,
497249 onStop: () -> Unit,
498250) {
499251 val haptic = LocalHapticFeedback.current
500− val clipboardManager = LocalClipboardManager.current
501252 Surface(tonalElevation = 3.dp) {
502− Column(
503− modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504− ) {
505253 Row(
506− modifier = Modifier.fillMaxWidth(),
254+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
507255 verticalAlignment = Alignment.Bottom,
508256 horizontalArrangement = Arrangement.spacedBy(8.dp),
509257 ) {
510258 OutlinedTextField(
511259 value = draft,
512260 onValueChange = onDraftChange,
513− modifier = Modifier.weight(1f).heightIn(min = 48.dp),
514− enabled = !loading,
261+ modifier = Modifier.weight(1f),
515262 placeholder = { Text("Message opencode…") },
516263 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− },
550264 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551265 keyboardActions = KeyboardActions(onSend = {
552− if (!generating && !loading && draft.isNotBlank()) onSend()
266+ if (!generating && draft.isNotBlank()) onSend()
553267 }),
554268 )
555269 if (generating) {
556− FilledTonalButton(onClick = onStop) {
557− Icon(
558− Icons.Filled.Stop,
559− contentDescription = null,
560− modifier = Modifier.size(18.dp),
561− )
562− Spacer(Modifier.size(6.dp))
563− Text("Stop")
270+ FilledIconButton(onClick = onStop) {
271+ Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
564272 }
565273 } else {
566274 FilledIconButton(
@@ -568,23 +276,11 @@ private fun ChatInputBar(
568276 haptic.performHapticFeedback(HapticFeedbackType.LongPress)
569277 onSend()
570278 },
571− enabled = draft.isNotBlank() && !loading,
279+ enabled = draft.isNotBlank(),
572280 ) {
573281 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
574282 }
575283 }
576284 }
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− }
589285 }
590286}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+4−91
@@ -17,29 +17,18 @@ import androidx.compose.material.icons.Icons
1717import androidx.compose.material.icons.filled.Lock
1818import androidx.compose.material.icons.filled.Person
1919import androidx.compose.material.icons.filled.Terminal
20−import androidx.compose.material.icons.filled.Visibility
21−import androidx.compose.material.icons.filled.VisibilityOff
2220import androidx.compose.material3.Button
2321import androidx.compose.material3.CircularProgressIndicator
2422import androidx.compose.material3.Icon
25−import androidx.compose.material3.IconButton
2623import androidx.compose.material3.MaterialTheme
2724import androidx.compose.material3.OutlinedTextField
2825import androidx.compose.material3.Text
2926import androidx.compose.runtime.Composable
30−import androidx.compose.runtime.LaunchedEffect
31−import androidx.compose.runtime.getValue
32−import androidx.compose.runtime.mutableStateOf
33−import androidx.compose.runtime.remember
34−import androidx.compose.runtime.setValue
3527import androidx.compose.ui.Alignment
3628import androidx.compose.ui.Modifier
37−import androidx.compose.ui.focus.FocusRequester
38−import androidx.compose.ui.focus.focusRequester
3929import androidx.compose.ui.text.input.ImeAction
4030import androidx.compose.ui.text.input.KeyboardType
4131import androidx.compose.ui.text.input.PasswordVisualTransformation
42−import androidx.compose.ui.text.input.VisualTransformation
4332import androidx.compose.ui.text.style.TextAlign
4433import androidx.compose.ui.unit.dp
4534import soy.iko.opencode.core.Event
@@ -47,15 +36,6 @@ import soy.iko.opencode.core.UiState
4736
4837@Composable
4938fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
50− val focusRequester = remember { FocusRequester() }
51− var passwordVisible by remember { mutableStateOf(false) }
52−
53− // Focus the server URL field when the screen opens, but only when it's empty
54− // so we don't steal focus (and pop the keyboard) on a return visit.
55− LaunchedEffect(Unit) {
56− if (state.serverUrl.isEmpty()) focusRequester.requestFocus()
57− }
58−
5939 Column(
6040 modifier = Modifier
6141 .fillMaxSize()
@@ -92,7 +72,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
9272 label = { Text("Server URL") },
9373 placeholder = { Text("http://192.168.1.10:4096") },
9474 singleLine = true,
95− modifier = Modifier.fillMaxWidth().focusRequester(focusRequester),
75+ modifier = Modifier.fillMaxWidth(),
9676 keyboardOptions = KeyboardOptions(
9777 keyboardType = KeyboardType.Uri,
9878 imeAction = if (state.authRequired) ImeAction.Next else ImeAction.Go,
@@ -101,30 +81,6 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
10181 enabled = !state.loading,
10282 )
10383
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−
12884 if (state.authRequired) {
12985 Spacer(Modifier.height(12.dp))
13086 OutlinedTextField(
@@ -143,27 +99,11 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
14399 onValueChange = { dispatch(Event.PasswordChanged(it)) },
144100 label = { Text("Password") },
145101 singleLine = true,
146− visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
102+ visualTransformation = PasswordVisualTransformation(),
147103 leadingIcon = { Icon(Icons.Filled.Lock, contentDescription = null) },
148− trailingIcon = {
149− IconButton(onClick = { passwordVisible = !passwordVisible }) {
150− Icon(
151− imageVector = if (passwordVisible) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
152− contentDescription = if (passwordVisible) "Hide password" else "Show password",
153− )
154− }
155− },
156104 modifier = Modifier.fillMaxWidth(),
157105 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
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− }),
106+ keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
167107 enabled = !state.loading,
168108 )
169109 Spacer(Modifier.height(4.dp))
@@ -178,10 +118,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
178118
179119 Button(
180120 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() &&
184− (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
121+ enabled = !state.loading && state.serverUrl.isNotBlank(),
185122 modifier = Modifier.fillMaxWidth(),
186123 ) {
187124 if (state.loading) {
@@ -194,29 +131,5 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
194131 Text(if (state.authRequired) "Sign in" else "Connect")
195132 }
196133 }
197−
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
211− // corrects the form (the snackbar is transient).
212− if (state.error != null && !state.loading) {
213− Spacer(Modifier.height(8.dp))
214− Text(
215− text = state.error,
216− style = MaterialTheme.typography.bodySmall,
217− color = MaterialTheme.colorScheme.error,
218− textAlign = TextAlign.Center,
219− )
220− }
221134 }
222135}
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+35−183
@@ -1,13 +1,7 @@
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
83import androidx.compose.foundation.background
94import androidx.compose.foundation.clickable
10−import androidx.compose.foundation.combinedClickable
115import androidx.compose.foundation.layout.Arrangement
126import androidx.compose.foundation.layout.Box
137import androidx.compose.foundation.layout.Column
@@ -21,17 +15,13 @@ import androidx.compose.foundation.layout.padding
2115import androidx.compose.foundation.layout.size
2216import androidx.compose.foundation.lazy.LazyColumn
2317import androidx.compose.foundation.lazy.items
24−import androidx.compose.foundation.lazy.rememberLazyListState
25−import androidx.compose.foundation.shape.CircleShape
2618import androidx.compose.material.icons.Icons
2719import androidx.compose.material.icons.automirrored.filled.ArrowBack
2820import androidx.compose.material.icons.filled.Add
2921import androidx.compose.material.icons.filled.ChatBubbleOutline
30−import androidx.compose.material.icons.filled.ChevronRight
3122import androidx.compose.material.icons.filled.DeleteOutline
3223import androidx.compose.material.icons.filled.Refresh
3324import androidx.compose.material3.AlertDialog
34−import androidx.compose.material3.CircularProgressIndicator
3525import androidx.compose.material3.ExperimentalMaterial3Api
3626import androidx.compose.material3.ExtendedFloatingActionButton
3727import androidx.compose.material3.HorizontalDivider
@@ -39,9 +29,7 @@ import androidx.compose.material3.Icon
3929import androidx.compose.material3.IconButton
4030import androidx.compose.material3.LinearProgressIndicator
4131import androidx.compose.material3.MaterialTheme
42−import androidx.compose.material3.OutlinedTextField
4332import androidx.compose.material3.Scaffold
44−import androidx.compose.material3.Surface
4533import androidx.compose.material3.SwipeToDismissBox
4634import androidx.compose.material3.SwipeToDismissBoxValue
4735import androidx.compose.material3.Text
@@ -58,12 +46,8 @@ import androidx.compose.runtime.remember
5846import androidx.compose.runtime.setValue
5947import androidx.compose.ui.Alignment
6048import androidx.compose.ui.Modifier
61−import androidx.compose.ui.draw.clip
62−import androidx.compose.ui.graphics.Color
6349import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64−import androidx.compose.ui.platform.LocalContext
6550import androidx.compose.ui.platform.LocalHapticFeedback
66−import androidx.compose.ui.text.style.TextAlign
6751import androidx.compose.ui.text.style.TextOverflow
6852import androidx.compose.ui.unit.dp
6953import soy.iko.opencode.core.Event
@@ -76,16 +60,6 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
7660 val haptic = LocalHapticFeedback.current
7761 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
7862 var isPullRefreshing by remember { mutableStateOf(false) }
79− 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− }
8963
9064 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
9165 // every loading operation. Clear it once the underlying load completes.
@@ -119,23 +93,7 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
11993 Scaffold(
12094 topBar = {
12195 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")
137− }
138− },
96+ title = { Text("Sessions") },
13997 navigationIcon = {
14098 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
14199 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -149,46 +107,19 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
149107 )
150108 },
151109 floatingActionButton = {
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− }
110+ ExtendedFloatingActionButton(
111+ onClick = { dispatch(Event.CreateSession) },
112+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
113+ text = { Text("New session") },
114+ )
161115 },
162116 ) { padding ->
163117 Column(Modifier.fillMaxSize().padding(padding)) {
164− if (!state.sseConnected) {
165− ReconnectingBanner()
166− }
167118 if (state.loading && !isPullRefreshing) {
168119 LinearProgressIndicator(Modifier.fillMaxWidth())
169120 }
170− if (state.sessions.isNotEmpty()) {
171− OutlinedTextField(
172− value = searchQuery,
173− onValueChange = { searchQuery = it },
174− placeholder = { Text("Search sessions") },
175− singleLine = true,
176− modifier = Modifier
177− .fillMaxWidth()
178− .padding(horizontal = 16.dp, vertical = 8.dp),
179− )
180− }
181− val filteredSessions = if (searchQuery.isEmpty()) {
182− state.sessions
183− } else {
184− state.sessions.filter {
185− it.title.contains(searchQuery, ignoreCase = true) ||
186− it.id.contains(searchQuery, ignoreCase = true)
187− }
188− }
189121 when {
190122 state.sessions.isEmpty() && !state.loading -> EmptySessions()
191− filteredSessions.isEmpty() && searchQuery.isNotEmpty() -> NoSearchResults(searchQuery)
192123 else -> PullToRefreshBox(
193124 isRefreshing = isPullRefreshing,
194125 onRefresh = {
@@ -199,37 +130,32 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
199130 state = rememberPullToRefreshState(),
200131 ) {
201132 LazyColumn(
202− state = sessionsListState,
203133 modifier = Modifier.fillMaxSize(),
204134 contentPadding = PaddingValues(bottom = 88.dp),
205135 ) {
206− items(filteredSessions, key = { it.id }) { session ->
207− // animateItem() slides the remaining rows into place when one is
208− // deleted (and fades new rows in) instead of snapping instantly.
209− Column(modifier = Modifier.animateItem()) {
210− val dismissState = rememberSwipeToDismissBoxState(
211− // Only a swipe from the end (right-to-left) triggers deletion;
212− // return false so the row snaps back and the confirm dialog decides.
213− confirmValueChange = { value ->
214− if (value == SwipeToDismissBoxValue.EndToStart) {
215− pendingDeleteId = session.id
216− }
217− false
218− },
136+ items(state.sessions, key = { it.id }) { session ->
137+ val dismissState = rememberSwipeToDismissBoxState(
138+ // Only a swipe from the end (right-to-left) triggers deletion;
139+ // return false so the row snaps back and the confirm dialog decides.
140+ confirmValueChange = { value ->
141+ if (value == SwipeToDismissBoxValue.EndToStart) {
142+ pendingDeleteId = session.id
143+ }
144+ false
145+ },
146+ )
147+ SwipeToDismissBox(
148+ state = dismissState,
149+ enableDismissFromStartToEnd = false,
150+ backgroundContent = { SwipeDeleteBackground() },
151+ ) {
152+ SessionRow(
153+ session = session,
154+ onOpen = { dispatch(Event.SelectSession(session.id)) },
155+ onDelete = { pendingDeleteId = session.id },
219156 )
220− SwipeToDismissBox(
221− state = dismissState,
222− enableDismissFromStartToEnd = false,
223− backgroundContent = { SwipeDeleteBackground() },
224− ) {
225− SessionRow(
226− session = session,
227− onOpen = { dispatch(Event.SelectSession(session.id)) },
228− onDelete = { pendingDeleteId = session.id },
229− )
230− }
231− HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
232157 }
158+ HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
233159 }
234160 }
235161 }
@@ -238,21 +164,13 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
238164 }
239165}
240166
241−@OptIn(ExperimentalFoundationApi::class)
242167@Composable
243168private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
244− val context = LocalContext.current
245169 Row(
246170 modifier = Modifier
247171 .fillMaxWidth()
248172 .background(MaterialTheme.colorScheme.surface)
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− )
173+ .clickable(onClick = onOpen)
256174 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
257175 verticalAlignment = Alignment.CenterVertically,
258176 ) {
@@ -277,23 +195,17 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
277195 overflow = TextOverflow.Ellipsis,
278196 )
279197 }
280− Icon(
281− Icons.Filled.ChevronRight,
282− contentDescription = null,
283− tint = MaterialTheme.colorScheme.onSurfaceVariant,
284− modifier = Modifier.padding(horizontal = 4.dp),
285− )
286198 IconButton(onClick = onDelete) {
287199 Icon(
288200 Icons.Filled.DeleteOutline,
289201 contentDescription = "Delete session",
290− tint = MaterialTheme.colorScheme.error,
202+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
291203 )
292204 }
293205 }
294206}
295207
296−/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
208+/** Red background with a trailing delete icon, revealed while swiping a session row away. */
297209@Composable
298210private fun SwipeDeleteBackground() {
299211 Box(
@@ -303,71 +215,18 @@ private fun SwipeDeleteBackground() {
303215 .padding(horizontal = 24.dp),
304216 contentAlignment = Alignment.CenterEnd,
305217 ) {
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− }
319− }
320−}
321−
322−/** Shown at the top of the list while the SSE stream is down, since session updates stall too. */
323−@Composable
324−private fun ReconnectingBanner() {
325− Surface(
326− modifier = Modifier.fillMaxWidth(),
327− color = MaterialTheme.colorScheme.tertiaryContainer,
328− ) {
329− Row(
330− modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
331− verticalAlignment = Alignment.CenterVertically,
332− horizontalArrangement = Arrangement.spacedBy(8.dp),
333− ) {
334− CircularProgressIndicator(
335− modifier = Modifier.size(14.dp),
336− strokeWidth = 2.dp,
337− color = MaterialTheme.colorScheme.onTertiaryContainer,
338− )
339− Text(
340− text = "Reconnecting…",
341− style = MaterialTheme.typography.bodySmall,
342− color = MaterialTheme.colorScheme.onTertiaryContainer,
343− )
344− }
218+ Icon(
219+ Icons.Filled.DeleteOutline,
220+ contentDescription = null,
221+ tint = MaterialTheme.colorScheme.onError,
222+ )
345223 }
346224}
347225
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−
353226/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
354227private fun shortSessionId(id: String): String =
355228 if (id.length > 12) id.take(8) + "…" else id
356229
357−@Composable
358−private fun NoSearchResults(query: String) {
359− Box(
360− modifier = Modifier.fillMaxSize().padding(32.dp),
361− contentAlignment = Alignment.Center,
362− ) {
363− Text(
364− text = "No results for “$query”",
365− style = MaterialTheme.typography.bodyMedium,
366− color = MaterialTheme.colorScheme.onSurfaceVariant,
367− )
368− }
369−}
370−
371230@Composable
372231private fun EmptySessions() {
373232 Column(
@@ -391,12 +250,5 @@ private fun EmptySessions() {
391250 style = MaterialTheme.typography.bodyMedium,
392251 color = MaterialTheme.colorScheme.onSurfaceVariant,
393252 )
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− )
401253 }
402254}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+1−23
@@ -14,18 +14,7 @@ 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),
1917 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),
2918 background = DarkBackground,
3019 surface = DarkSurface,
3120 surfaceVariant = DarkSurfaceVariant,
@@ -35,18 +24,7 @@ private val DarkColors = darkColorScheme(
3524
3625private val LightColors = lightColorScheme(
3726 primary = EmeraldDark,
38− primaryContainer = Color(0xFFD7F5E3),
39− onPrimaryContainer = Color(0xFF0A3D22),
4027 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),
5028 background = LightBackground,
5129 surface = LightSurface,
5230 surfaceVariant = LightSurfaceVariant,
@@ -57,7 +35,7 @@ private val LightColors = lightColorScheme(
5735@Composable
5836fun OpencodeTheme(
5937 darkTheme: Boolean = isSystemInDarkTheme(),
60− dynamicColor: Boolean = false,
38+ dynamicColor: Boolean = true,
6139 content: @Composable () -> Unit,
6240) {
6341 val context = LocalContext.current
shared/src/app.rs−14
@@ -297,27 +297,16 @@ impl App for OpencodeApp {
297297 // Store the field verbatim while typing; normalizing here would fight
298298 // the user's edits (e.g. eat the "://" as they type it). The URL is
299299 // normalized once, on Connect.
300− // Clear any prior error as soon as the user edits a field, so a stale
301− // message (e.g. "Invalid credentials") doesn't linger while they correct it.
302300 Event::ServerUrlChanged(url) => {
303301 model.server_url = url;
304− if model.error.is_some() {
305− model.error = None;
306− }
307302 render()
308303 }
309304 Event::UsernameChanged(u) => {
310305 model.username = u;
311− if model.error.is_some() {
312− model.error = None;
313− }
314306 render()
315307 }
316308 Event::PasswordChanged(p) => {
317309 model.password = p;
318− if model.error.is_some() {
319− model.error = None;
320− }
321310 render()
322311 }
323312
@@ -352,9 +341,6 @@ impl App for OpencodeApp {
352341 title: display_title(&s.title),
353342 })
354343 .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());
358344 }
359345 Err(e) => model.error = Some(e),
360346 }