git.iko.soy/opencode-android
on master help sign in
.github/workflows/release.yml+9−3
since splitsnapshots
unifiedsplit
@@ -2,9 +2,14 @@ name: Release
2
2
3# Build a minified, signed release APK and publish it as a GitHub Release.
3# Build a minified, signed release APK and publish it as a GitHub Release.
4#
4#
5+# Runs automatically on every push to `master` (e.g. a merged PR), on a pushed
5−# Trigger by pushing a version tag (e.g. `git tag v1.2.0 && git push --tags`),
6+# version tag (e.g. `git tag v1.2.0 && git push --tags`), or manually from the
6−# or run manually from the Actions tab (workflow_dispatch), in which case the
7+# Actions tab (workflow_dispatch). For a branch push or manual run the version
7−# version is derived from the current UTC time as YYYY.MM.DD.HHMM.
8+# is derived from the current UTC time as YYYY.MM.DD.HHMM; a tag push uses the
9+# tag name (with the leading `v` stripped) as the version.
10+#
11+# The `v*` tag this workflow pushes when publishing a release does NOT retrigger
12+# it: events created with the default GITHUB_TOKEN don't start new workflow runs.
8#
13#
9# Signing: if the `OPENCODE_STORE_*` secrets are configured the APK is signed
14# Signing: if the `OPENCODE_STORE_*` secrets are configured the APK is signed
10# with that keystore; otherwise the Gradle build falls back to the debug key so
15# with that keystore; otherwise the Gradle build falls back to the debug key so
@@ -12,6 +17,7 @@ name: Release
12# is passed to Gradle as `-PversionName/-PversionCode` and stamped into the APK.
17# is passed to Gradle as `-PversionName/-PversionCode` and stamped into the APK.
13on:
18on:
14 push:
19 push:
20+ branches: [master]
15 tags: ["v*"]
21 tags: ["v*"]
16 workflow_dispatch:
22 workflow_dispatch:
17
23
CLAUDE.mdnew file+40
@@ -0,0 +1,40 @@
1+# opencode-android
2+
3+Native Android client for the opencode server, built with Crux (Rust core), Kotlin, and Jetpack Compose.
4+
5+## Architecture
6+
7+- **shared/** — Rust Crux core (canonical spec, unit-tested with `cargo test`)
8+- **app/** — Android shell with Kotlin port of the reducer (`OpencodeCore`)
9+- All app logic in `OpencodeCore.kt`; UI is a thin Compose shell
10+- Three screens: Connect → Sessions → Chat
11+
12+## Key Files
13+
14+- `app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt` — reducer, all state management
15+- `app/src/main/java/soy/iko/opencode/core/ViewModel.kt` — UiState, Event, data classes
16+- `app/src/main/java/soy/iko/opencode/core/Protocol.kt` — wire types, SSE event parser
17+- `app/src/main/java/soy/iko/opencode/core/HttpClient.kt` — OkHttp wrapper
18+- `app/src/main/java/soy/iko/opencode/core/SseClient.kt` — SSE stream client
19+- `app/src/main/java/soy/iko/opencode/ui/screens/` — ConnectScreen, SessionsScreen, ChatScreen
20+- `app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt` — message rendering
21+
22+## Build
23+
24+```sh
25+source .buildenv.sh
26+nix develop -c ./gradlew assembleDebug
27+```
28+
29+## Code Conventions
30+
31+- Kotlin + Jetpack Compose (Material 3)
32+- State flows through `MutableStateFlow<UiState>` → `collectAsStateWithLifecycle`
33+- All state mutations on main dispatcher (viewModelScope)
34+- Network I/O on `Dispatchers.IO` inside HttpClient/SseClient
35+- Keep the Rust core and Kotlin port behaviourally identical
36+
37+## Version Control
38+
39+- Uses `jj` (jujutsu) colocated with git
40+- Push to master: `jj git push --change @` to create a bookmark, or commit then push
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+18
@@ -23,6 +23,22 @@ 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+
30+ // 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`).
32+ core.resumeStreamingIfConnected()
33+
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+ }
26
42
27 // Persist connection details once a connection succeeds.
43 // Persist connection details once a connection succeeds.
28 viewModelScope.launch {
44 viewModelScope.launch {
@@ -31,6 +47,7 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
31 prefs.edit {
47 prefs.edit {
32 putString(KEY_URL, state.serverUrl)
48 putString(KEY_URL, state.serverUrl)
33 putString(KEY_USER, state.username)
49 putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
34 }
51 }
35 }
52 }
36 }
53 }
@@ -44,5 +61,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
44 private companion object {
61 private companion object {
45 const val KEY_URL = "serverUrl"
62 const val KEY_URL = "serverUrl"
46 const val KEY_USER = "username"
63 const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
47 }
65 }
48}
66}
app/src/main/java/soy/iko/opencode/MainActivity.kt+8
@@ -2,7 +2,9 @@ package soy.iko.opencode
2
2
3import android.os.Bundle
3import android.os.Bundle
4import androidx.activity.ComponentActivity
4import androidx.activity.ComponentActivity
5+import androidx.activity.SystemBarStyle
5import androidx.activity.compose.setContent
6import androidx.activity.compose.setContent
7+import androidx.activity.enableEdgeToEdge
6import androidx.compose.runtime.getValue
8import androidx.compose.runtime.getValue
7import androidx.lifecycle.compose.collectAsStateWithLifecycle
9import androidx.lifecycle.compose.collectAsStateWithLifecycle
8import androidx.lifecycle.viewmodel.compose.viewModel
10import androidx.lifecycle.viewmodel.compose.viewModel
@@ -11,6 +13,12 @@ import soy.iko.opencode.ui.theme.OpencodeTheme
11
13
12class MainActivity : ComponentActivity() {
14class MainActivity : ComponentActivity() {
13 override fun onCreate(savedInstanceState: Bundle?) {
15 override fun onCreate(savedInstanceState: Bundle?) {
16+ enableEdgeToEdge(
17+ statusBarStyle = SystemBarStyle.auto(
18+ lightScrim = 0xFF0F1115.toInt(),
19+ darkScrim = 0xFF0F1115.toInt(),
20+ ),
21+ )
14 super.onCreate(savedInstanceState)
22 super.onCreate(savedInstanceState)
15 setContent {
23 setContent {
16 OpencodeTheme {
24 OpencodeTheme {
app/src/main/java/soy/iko/opencode/core/HttpClient.kt+1
@@ -51,6 +51,7 @@ 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")
54 if (auth != null) builder.header("Authorization", auth)
55 if (auth != null) builder.header("Authorization", auth)
55 await(okhttp.newCall(builder.build()))
56 await(okhttp.newCall(builder.build()))
56 }
57 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+256−53
@@ -1,6 +1,7 @@
1package soy.iko.opencode.core
1package soy.iko.opencode.core
2
2
3import kotlinx.coroutines.CoroutineScope
3import kotlinx.coroutines.CoroutineScope
4+import kotlinx.coroutines.Job
4import kotlinx.coroutines.delay
5import kotlinx.coroutines.delay
5import kotlinx.coroutines.flow.MutableStateFlow
6import kotlinx.coroutines.flow.MutableStateFlow
6import kotlinx.coroutines.flow.StateFlow
7import kotlinx.coroutines.flow.StateFlow
@@ -29,7 +30,6 @@ class OpencodeCore(
29 private var username = ""
30 private var username = ""
30 private var password = ""
31 private var password = ""
31 private var authRequired = false
32 private var authRequired = false
32− private var authed = false
33 private var connected = false
33 private var connected = false
34 private var loading = false
34 private var loading = false
35 private var error: String? = null
35 private var error: String? = null
@@ -40,6 +40,7 @@ class OpencodeCore(
40 private val messages = mutableListOf<MsgState>()
40 private val messages = mutableListOf<MsgState>()
41 private var draft = ""
41 private var draft = ""
42 private var generating = false
42 private var generating = false
43+ private var sseConnected = true
43 private var localSeq = 0L
44 private var localSeq = 0L
44
45
45 private val _view = MutableStateFlow(snapshot())
46 private val _view = MutableStateFlow(snapshot())
@@ -47,44 +48,123 @@ class OpencodeCore(
47
48
48 private var sse: SseClient? = null
49 private var sse: SseClient? = null
49 private var sseClosedIntentionally = false
50 private var sseClosedIntentionally = false
51+ 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>()
50
77
51 // ── Event entry point ──────────────────────────────────────────────────────
78 // ── Event entry point ──────────────────────────────────────────────────────
52 fun dispatch(event: Event) {
79 fun dispatch(event: Event) {
53 when (event) {
80 when (event) {
81+ // Store the field verbatim while typing; normalizing here would fight
82+ // the user's edits (e.g. eat the "://" as they type it). The URL is
83+ // 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.
54− is Event.ServerUrlChanged -> { serverUrl = normalizeUrl(event.url); emit() }
86+ is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
55− is Event.UsernameChanged -> { username = event.value; emit() }
87+ is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
56− is Event.PasswordChanged -> { password = event.value; emit() }
88+ is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
57
89
58 Event.Connect -> {
90 Event.Connect -> {
91+ serverUrl = normalizeUrl(serverUrl)
59 if (serverUrl.isEmpty()) { error = "Enter a server URL"; emit(); return }
92 if (serverUrl.isEmpty()) { error = "Enter a server URL"; emit(); return }
93+ // The auth fields are showing but empty — sending the request now
94+ // would just 401 again in a loop. Prompt for credentials instead.
95+ 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.
60− loading = true; error = null; authRequired = false; emit()
98+ loading = true; error = null; emit()
99+ connectJob?.cancel()
61− scope.launch { probeHealth() }
100+ connectJob = scope.launch { probeHealth() }
62 }
101 }
63
102
103+ Event.LoadSessions -> {
104+ if (!connected) { error = "Not connected"; emit(); return }
105+ loading = true; emit()
106+ loadSessionsJob?.cancel()
64− Event.LoadSessions -> { loading = true; emit(); scope.launch { loadSessions() } }
107+ loadSessionsJob = scope.launch { loadSessions() }
108+ }
65
109
66 is Event.SelectSession -> {
110 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.
67− currentSessionTitle = sessions.firstOrNull { it.id == event.id }?.title.orEmpty()
113+ val session = sessions.firstOrNull { it.id == event.id }
114+ if (session == null) { error = "Session no longer exists"; emit(); return }
115+ currentSessionTitle = session.title
68 currentSessionId = event.id
116 currentSessionId = event.id
69 messages.clear()
117 messages.clear()
118+ removedMessageIds.clear()
70 screen = Screen.Chat
119 screen = Screen.Chat
71 loading = true
120 loading = true
121+ generating = false
72 error = null
122 error = null
73 emit()
123 emit()
124+ connectJob?.cancel()
125+ abortJob?.cancel()
126+ sendMessageJob?.cancel()
127+ deleteSessionJob?.cancel()
128+ loadMessagesJob?.cancel()
74− scope.launch { loadMessages(event.id) }
129+ loadMessagesJob = scope.launch { loadMessages(event.id) }
75 }
130 }
76
131
132+ Event.CreateSession -> {
133+ if (!connected) { error = "Not connected"; emit(); return }
134+ loading = true; error = null; emit()
135+ createSessionJob?.cancel()
77− Event.CreateSession -> { loading = true; emit(); scope.launch { createSession() } }
136+ createSessionJob = scope.launch { createSession() }
137+ }
78
138
79 is Event.DeleteSession -> {
139 is Event.DeleteSession -> {
140+ if (!connected) { error = "Not connected"; emit(); return }
141+ val id = event.id
142+ // Delete on the server first; only drop it from the UI once that
143+ // succeeds, so a failed request leaves the session recoverable.
144+ loading = true; error = null; emit()
145+ deleteSessionJob?.cancel()
146+ deleteSessionJob = scope.launch {
147+ http.delete("$serverUrl/session/$id", authHeader()).fold(
148+ onSuccess = { resp ->
149+ if (resp.code in 200..299) {
80− sessions.removeAll { it.id == event.id }
150+ sessions.removeAll { it.id == id }
81− if (isCurrent(event.id)) {
151+ if (isCurrent(id)) {
82− currentSessionId = null
152+ currentSessionId = null
83− messages.clear()
153+ messages.clear()
84− screen = Screen.Sessions
154+ screen = Screen.Sessions
155+ }
156+ } else {
157+ error = "Failed to delete session"
158+ }
159+ loading = false
160+ },
161+ onFailure = {
162+ error = "Failed to delete session"
163+ loading = false
164+ },
165+ )
166+ emit()
85 }
167 }
86− emit()
87− scope.launch { http.delete("$serverUrl/session/${event.id}", authHeader()) }
88 }
168 }
89
169
90 is Event.DraftChanged -> { draft = event.text; emit() }
170 is Event.DraftChanged -> { draft = event.text; emit() }
@@ -92,26 +172,57 @@ class OpencodeCore(
92 is Event.SendMessage -> sendMessage(event.text)
172 is Event.SendMessage -> sendMessage(event.text)
93
173
94 Event.CancelGeneration -> {
174 Event.CancelGeneration -> {
95− generating = false; emit()
175+ generating = false
176+ messages.forEach { it.streaming = false }
177+ emit()
96 val id = currentSessionId ?: return
178 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()
97− scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
182+ abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
98 }
183 }
99
184
100 Event.NavigateToSessions -> {
185 Event.NavigateToSessions -> {
101 screen = Screen.Sessions
186 screen = Screen.Sessions
102 currentSessionId = null
187 currentSessionId = null
103 messages.clear()
188 messages.clear()
189+ removedMessageIds.clear()
190+ draft = ""
104 generating = false
191 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
105 emit()
196 emit()
197+ connectJob?.cancel()
198+ abortJob?.cancel()
199+ createSessionJob?.cancel()
200+ deleteSessionJob?.cancel()
201+ sendMessageJob?.cancel()
202+ loadMessagesJob?.cancel()
203+ loadSessionsJob?.cancel()
106− scope.launch { loadSessions() }
204+ loadSessionsJob = scope.launch { loadSessions() }
107 }
205 }
108
206
109 Event.NavigateToConnect -> {
207 Event.NavigateToConnect -> {
110 screen = Screen.Connect
208 screen = Screen.Connect
111 connected = false
209 connected = false
210+ loading = false
211+ generating = false
112 sessions.clear()
212 sessions.clear()
113 messages.clear()
213 messages.clear()
214+ removedMessageIds.clear()
114 currentSessionId = null
215 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()
115 closeSse()
226 closeSse()
116 emit()
227 emit()
117 }
228 }
@@ -125,26 +236,44 @@ class OpencodeCore(
125 if (connected && sse == null) startSse()
236 if (connected && sse == null) startSse()
126 }
237 }
127
238
128− fun shutdown() = closeSse()
239+ fun shutdown() {
240+ // Cancel every tracked coroutine before tearing down the stream so none can
241+ // emit into a cancelled scope after the ViewModel is cleared.
242+ connectJob?.cancel()
243+ loadSessionsJob?.cancel()
244+ createSessionJob?.cancel()
245+ loadMessagesJob?.cancel()
246+ deleteSessionJob?.cancel()
247+ sendMessageJob?.cancel()
248+ abortJob?.cancel()
249+ closeSse()
250+ }
129
251
130 // ── Effects ────────────────────────────────────────────────────────────────
252 // ── Effects ────────────────────────────────────────────────────────────────
131 private fun sendMessage(raw: String) {
253 private fun sendMessage(raw: String) {
132 val text = raw.trim()
254 val text = raw.trim()
133 val session = currentSessionId ?: return
255 val session = currentSessionId ?: return
134 if (text.isEmpty()) return
256 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
135 localSeq += 1
260 localSeq += 1
136− val user = MsgState("local-$localSeq", "user", 0).apply {
261+ val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
137 status = MessageStatus.Pending
262 status = MessageStatus.Pending
138 textParts["local"] = text
263 textParts["local"] = text
139 }
264 }
140 messages.add(user)
265 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
141 draft = ""
269 draft = ""
142 generating = true
270 generating = true
143 error = null
271 error = null
144 emit()
272 emit()
145
273
146 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
274 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275+ sendMessageJob?.cancel()
147− scope.launch {
276+ sendMessageJob = scope.launch {
148 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
277 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
149 result.fold(
278 result.fold(
150 onSuccess = { resp ->
279 onSuccess = { resp ->
@@ -153,12 +282,16 @@ class OpencodeCore(
153 } else {
282 } else {
154 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
283 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
155 generating = false
284 generating = false
285+ messages.forEach { it.streaming = false }
286+ draft = savedDraft
156 error = "Server returned status ${resp.code}"
287 error = "Server returned status ${resp.code}"
157 }
288 }
158 },
289 },
159 onFailure = { e ->
290 onFailure = { e ->
160 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
291 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
161 generating = false
292 generating = false
293+ messages.forEach { it.streaming = false }
294+ draft = savedDraft
162 error = "Request failed: ${e.message}"
295 error = "Request failed: ${e.message}"
163 },
296 },
164 )
297 )
@@ -173,11 +306,17 @@ class OpencodeCore(
173 when {
306 when {
174 resp.code == 401 -> {
307 resp.code == 401 -> {
175 loading = false
308 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
314+ // their credentials — even when the ones supplied were wrong.
315+ authRequired = true
176− if (hasCreds) error = "Invalid credentials" else authRequired = true
316+ if (hasCreds) error = "Invalid credentials"
177 emit()
317 emit()
178 }
318 }
179 resp.code in 200..299 -> {
319 resp.code in 200..299 -> {
180− if (hasCreds) authed = true
181 connected = true
320 connected = true
182 authRequired = false
321 authRequired = false
183 error = null
322 error = null
@@ -185,10 +324,14 @@ class OpencodeCore(
185 loading = true
324 loading = true
186 emit()
325 emit()
187 startSse()
326 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()
188− loadSessions()
330+ loadSessionsJob = scope.launch { loadSessions() }
189 }
331 }
190 else -> {
332 else -> {
191 loading = false
333 loading = false
334+ connected = false
192 error = "Server returned status ${resp.code}"
335 error = "Server returned status ${resp.code}"
193 emit()
336 emit()
194 }
337 }
@@ -196,6 +339,7 @@ class OpencodeCore(
196 },
339 },
197 onFailure = { e ->
340 onFailure = { e ->
198 loading = false
341 loading = false
342+ connected = false
199 error = "Connection failed: ${e.message}"
343 error = "Connection failed: ${e.message}"
200 emit()
344 emit()
201 },
345 },
@@ -203,31 +347,38 @@ class OpencodeCore(
203 }
347 }
204
348
205 private suspend fun loadSessions() {
349 private suspend fun loadSessions() {
206− loading = false
207 http.get("$serverUrl/session", authHeader()).fold(
350 http.get("$serverUrl/session", authHeader()).fold(
208 onSuccess = { resp ->
351 onSuccess = { resp ->
209 if (resp.code in 200..299) {
352 if (resp.code in 200..299) {
210 sessions.clear()
353 sessions.clear()
211 sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
354 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() }
212 } else {
358 } else {
213 error = "Server returned status ${resp.code}"
359 error = "Server returned status ${resp.code}"
214 }
360 }
215 },
361 },
216 onFailure = { e -> error = "Request failed: ${e.message}" },
362 onFailure = { e -> error = "Request failed: ${e.message}" },
217 )
363 )
364+ loading = false
218 emit()
365 emit()
219 }
366 }
220
367
221 private suspend fun createSession() {
368 private suspend fun createSession() {
222− loading = false
223 http.postJson("$serverUrl/session", "{}", authHeader()).fold(
369 http.postJson("$serverUrl/session", "{}", authHeader()).fold(
224 onSuccess = { resp ->
370 onSuccess = { resp ->
225 val session = if (resp.code in 200..299) Protocol.parseSession(resp.body) else null
371 val session = if (resp.code in 200..299) Protocol.parseSession(resp.body) else null
226 if (session != null) {
372 if (session != null) {
227 if (sessions.none { it.id == session.id }) {
373 if (sessions.none { it.id == session.id }) {
228 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
374 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() }
229 }
379 }
230 emit()
380 emit()
381+ // SelectSession takes over the loading state (loads messages).
231 dispatch(Event.SelectSession(session.id))
382 dispatch(Event.SelectSession(session.id))
232 return
383 return
233 }
384 }
@@ -235,16 +386,18 @@ class OpencodeCore(
235 },
386 },
236 onFailure = { e -> error = "Request failed: ${e.message}" },
387 onFailure = { e -> error = "Request failed: ${e.message}" },
237 )
388 )
389+ loading = false
238 emit()
390 emit()
239 }
391 }
240
392
241 private suspend fun loadMessages(sessionId: String) {
393 private suspend fun loadMessages(sessionId: String) {
242 http.get("$serverUrl/session/$sessionId/message", authHeader()).fold(
394 http.get("$serverUrl/session/$sessionId/message", authHeader()).fold(
243 onSuccess = { resp ->
395 onSuccess = { resp ->
244− if (!isCurrent(sessionId)) return // user navigated away while loading
396+ if (!isCurrent(sessionId)) { loading = false; return } // user navigated away while loading
245 loading = false
397 loading = false
246 if (resp.code in 200..299) {
398 if (resp.code in 200..299) {
247 messages.clear()
399 messages.clear()
400+ removedMessageIds.clear()
248 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
401 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
249 generating = messages.any { it.streaming }
402 generating = messages.any { it.streaming }
250 } else {
403 } else {
@@ -253,8 +406,9 @@ class OpencodeCore(
253 emit()
406 emit()
254 },
407 },
255 onFailure = { e ->
408 onFailure = { e ->
256− if (!isCurrent(sessionId)) return
409+ if (!isCurrent(sessionId)) { loading = false; return }
257 loading = false
410 loading = false
411+ generating = false
258 error = "Request failed: ${e.message}"
412 error = "Request failed: ${e.message}"
259 emit()
413 emit()
260 },
414 },
@@ -269,7 +423,13 @@ class OpencodeCore(
269 url = "$serverUrl/event",
423 url = "$serverUrl/event",
270 auth = authHeader(),
424 auth = authHeader(),
271 onEvent = { json -> scope.launch { handleServerEvent(json) } },
425 onEvent = { json -> scope.launch { handleServerEvent(json) } },
272− onStateChange = { open -> if (!open) scheduleReconnect() },
426+ onStateChange = { open ->
427+ scope.launch {
428+ sseConnected = open
429+ if (open) reconnectAttempts = 0 else scheduleReconnect()
430+ emit()
431+ }
432+ },
273 )
433 )
274 sse = client
434 sse = client
275 client.connect()
435 client.connect()
@@ -277,29 +437,43 @@ class OpencodeCore(
277
437
278 private fun closeSse() {
438 private fun closeSse() {
279 sseClosedIntentionally = true
439 sseClosedIntentionally = true
440+ reconnectJob?.cancel()
441+ reconnectJob = null
280 sse?.close()
442 sse?.close()
281 sse = null
443 sse = null
282 }
444 }
283
445
284 private fun scheduleReconnect() {
446 private fun scheduleReconnect() {
285 if (sseClosedIntentionally || !connected) return
447 if (sseClosedIntentionally || !connected) return
448+ // Exponential backoff: 2s, 4s, 8s, 16s, capped at 30s. Reset to 0 once the
449+ // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
450+ val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
451+ 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()
286− scope.launch {
455+ reconnectJob = scope.launch {
287− delay(2000)
456+ delay(delayMs)
288 if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
457 if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
289 }
458 }
290 }
459 }
291
460
292 private fun handleServerEvent(json: String) {
461 private fun handleServerEvent(json: String) {
293 val event = Protocol.parseEvent(json) ?: return
462 val event = Protocol.parseEvent(json) ?: return
294− applyEvent(event)
463+ // Only re-render if the event actually changed our state; applyEvent returns
295− emit()
464+ // false for events that don't apply (other session, unknown message, …).
465+ if (applyEvent(event)) emit()
296 }
466 }
297
467
468+ /** Apply a server event to the model. Returns true iff any state actually changed. */
298− private fun applyEvent(event: Protocol.Event) {
469+ private fun applyEvent(event: Protocol.Event): Boolean {
299 when (event) {
470 when (event) {
300 is Protocol.Event.MessageUpdated -> {
471 is Protocol.Event.MessageUpdated -> {
301 val info = event.info
472 val info = event.info
302− if (info.role != "assistant" || !isCurrent(info.sessionId)) return
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
303 val streaming = info.time.completed == null && info.error == null
477 val streaming = info.time.completed == null && info.error == null
304 val existing = messages.firstOrNull { it.id == info.id }
478 val existing = messages.firstOrNull { it.id == info.id }
305 if (existing != null) {
479 if (existing != null) {
@@ -308,38 +482,59 @@ class OpencodeCore(
308 } else {
482 } else {
309 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
483 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
310 }
484 }
311− info.error?.let { error = it.message(); generating = false }
485+ info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
486+ return true
312 }
487 }
313
488
314 is Protocol.Event.PartUpdated -> {
489 is Protocol.Event.PartUpdated -> {
315 val part = event.part
490 val part = event.part
316− val msg = messages.firstOrNull { it.id == part.messageId } ?: return
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.
317− when (part) {
494+ return when (part) {
318− is Protocol.Part.Text -> if (!part.synthetic) {
495+ is Protocol.Part.Text -> if (part.synthetic) {
496+ false
497+ } else {
319 msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
498 msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
499+ true
320 }
500 }
321− is Protocol.Part.Reasoning ->
501+ is Protocol.Part.Reasoning -> {
322 msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
502 msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
503+ true
504+ }
323− is Protocol.Part.Tool ->
505+ is Protocol.Part.Tool -> {
324 msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
506 msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
507+ true
508+ }
325 }
509 }
326 }
510 }
327
511
512+ is Protocol.Event.PartRemoved -> {
328− is Protocol.Event.PartRemoved -> messages.firstOrNull { it.id == event.messageId }?.remove(event.partId)
513+ val msg = messages.firstOrNull { it.id == event.messageId } ?: return false
514+ msg.remove(event.partId)
515+ return true
516+ }
329
517
518+ is Protocol.Event.MessageRemoved -> {
519+ // Remember the ID so a late MessageUpdated can't resurrect the message.
520+ removedMessageIds.add(event.messageId)
330− is Protocol.Event.MessageRemoved -> messages.removeAll { it.id == event.messageId }
521+ return messages.removeAll { it.id == event.messageId }
522+ }
331
523
332− is Protocol.Event.SessionIdle -> if (isCurrent(event.sessionId)) {
524+ is Protocol.Event.SessionIdle -> {
525+ if (!isCurrent(event.sessionId)) return false
333 generating = false
526 generating = false
334 messages.forEach { it.streaming = false }
527 messages.forEach { it.streaming = false }
528+ return true
335 }
529 }
336
530
337 is Protocol.Event.SessionError -> {
531 is Protocol.Event.SessionError -> {
338 val scoped = event.sessionId == null || isCurrent(event.sessionId)
532 val scoped = event.sessionId == null || isCurrent(event.sessionId)
339− if (scoped) {
533+ if (!scoped) return false
340− event.error?.let { error = it.message() }
534+ event.error?.let { error = it.message() }
341− generating = false
535+ generating = false
342− }
536+ messages.forEach { it.streaming = false }
537+ return true
343 }
538 }
344
539
345 is Protocol.Event.SessionUpserted -> {
540 is Protocol.Event.SessionUpserted -> {
@@ -350,19 +545,26 @@ class OpencodeCore(
350 } else {
545 } else {
351 sessions.add(0, SessionView(event.info.id, title))
546 sessions.add(0, SessionView(event.info.id, title))
352 }
547 }
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() }
353 if (isCurrent(event.info.id)) currentSessionTitle = title
551 if (isCurrent(event.info.id)) currentSessionTitle = title
552+ return true
354 }
553 }
355
554
356− is Protocol.Event.SessionDeleted -> event.sessionId?.let { id ->
555+ is Protocol.Event.SessionDeleted -> {
556+ val id = event.sessionId ?: return false
357− sessions.removeAll { it.id == id }
557+ val removed = sessions.removeAll { it.id == id }
358 if (isCurrent(id)) {
558 if (isCurrent(id)) {
359 currentSessionId = null
559 currentSessionId = null
360 messages.clear()
560 messages.clear()
361 screen = Screen.Sessions
561 screen = Screen.Sessions
562+ return true
362 }
563 }
564+ return removed
363 }
565 }
364
566
365− Protocol.Event.Other -> Unit
567+ Protocol.Event.Other -> return false
366 }
568 }
367 }
569 }
368
570
@@ -382,6 +584,7 @@ class OpencodeCore(
382 messages = messages.map { it.toView() },
584 messages = messages.map { it.toView() },
383 draft = draft,
585 draft = draft,
384 generating = generating,
586 generating = generating,
587+ sseConnected = sseConnected,
385 )
588 )
386
589
387 private fun emit() { _view.value = snapshot() }
590 private fun emit() { _view.value = snapshot() }
app/src/main/java/soy/iko/opencode/core/SseClient.kt+1
@@ -33,6 +33,7 @@ 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")
36 if (auth != null) builder.header("Authorization", auth)
37 if (auth != null) builder.header("Authorization", auth)
37 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
38 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
38 }
39 }
app/src/main/java/soy/iko/opencode/core/ViewModel.kt+1
@@ -48,6 +48,7 @@ data class UiState(
48 val messages: List<MessageView> = emptyList(),
48 val messages: List<MessageView> = emptyList(),
49 val draft: String = "",
49 val draft: String = "",
50 val generating: Boolean = false,
50 val generating: Boolean = false,
51+ val sseConnected: Boolean = true,
51)
52)
52
53
53/**
54/**
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+71−7
@@ -2,18 +2,24 @@ package soy.iko.opencode.ui
2
2
3import androidx.activity.compose.BackHandler
3import androidx.activity.compose.BackHandler
4import androidx.compose.animation.AnimatedContent
4import androidx.compose.animation.AnimatedContent
5−import androidx.compose.animation.SizeTransform
5+import androidx.compose.animation.slideInHorizontally
6−import androidx.compose.animation.fadeIn
6+import androidx.compose.animation.slideOutHorizontally
7−import androidx.compose.animation.fadeOut
8import androidx.compose.animation.togetherWith
7import androidx.compose.animation.togetherWith
9import androidx.compose.foundation.layout.fillMaxSize
8import androidx.compose.foundation.layout.fillMaxSize
10import androidx.compose.foundation.layout.padding
9import androidx.compose.foundation.layout.padding
10+import androidx.compose.material3.AlertDialog
11import androidx.compose.material3.Scaffold
11import androidx.compose.material3.Scaffold
12+import androidx.compose.material3.SnackbarDuration
12import androidx.compose.material3.SnackbarHost
13import androidx.compose.material3.SnackbarHost
13import androidx.compose.material3.SnackbarHostState
14import androidx.compose.material3.SnackbarHostState
15+import androidx.compose.material3.Text
16+import androidx.compose.material3.TextButton
14import androidx.compose.runtime.Composable
17import androidx.compose.runtime.Composable
15import androidx.compose.runtime.LaunchedEffect
18import androidx.compose.runtime.LaunchedEffect
19+import androidx.compose.runtime.getValue
20+import androidx.compose.runtime.mutableStateOf
16import androidx.compose.runtime.remember
21import androidx.compose.runtime.remember
22+import androidx.compose.runtime.setValue
17import androidx.compose.ui.Modifier
23import androidx.compose.ui.Modifier
18import soy.iko.opencode.core.Event
24import soy.iko.opencode.core.Event
19import soy.iko.opencode.core.Screen
25import soy.iko.opencode.core.Screen
@@ -25,28 +31,86 @@ import soy.iko.opencode.ui.screens.SessionsScreen
25@Composable
31@Composable
26fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
32fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
27 val snackbar = remember { SnackbarHostState() }
33 val snackbar = remember { SnackbarHostState() }
34+ var showStopConfirm by remember { mutableStateOf(false) }
35+ var showDisconnectConfirm by remember { mutableStateOf(false) }
28
36
29 LaunchedEffect(state.error) {
37 LaunchedEffect(state.error) {
30 state.error?.let {
38 state.error?.let {
31− snackbar.showSnackbar(it)
39+ snackbar.showSnackbar(
40+ message = it,
41+ actionLabel = "Dismiss",
42+ duration = SnackbarDuration.Short,
43+ )
44+ // Always clear the error from state after showing.
32 dispatch(Event.DismissError)
45 dispatch(Event.DismissError)
33 }
46 }
34 }
47 }
35
48
36 BackHandler(enabled = state.screen != Screen.Connect) {
49 BackHandler(enabled = state.screen != Screen.Connect) {
37 when (state.screen) {
50 when (state.screen) {
51+ // Leaving mid-generation would silently drop the reply, so confirm first.
38− Screen.Chat -> dispatch(Event.NavigateToSessions)
52+ Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
39− Screen.Sessions -> dispatch(Event.NavigateToConnect)
53+ // Disconnecting drops the server session, so guard the back button.
54+ Screen.Sessions -> showDisconnectConfirm = true
40 Screen.Connect -> Unit
55 Screen.Connect -> Unit
41 }
56 }
42 }
57 }
43
58
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+
44 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
102 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
45 AnimatedContent(
103 AnimatedContent(
46 targetState = state.screen,
104 targetState = state.screen,
47 modifier = Modifier.fillMaxSize().padding(padding),
105 modifier = Modifier.fillMaxSize().padding(padding),
48 transitionSpec = {
106 transitionSpec = {
49− (fadeIn() togetherWith fadeOut()).using(SizeTransform(clip = false))
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+ }
50 },
114 },
51 label = "screen",
115 label = "screen",
52 ) { screen ->
116 ) { screen ->
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+376−27
@@ -1,37 +1,75 @@
1package soy.iko.opencode.ui.components
1package soy.iko.opencode.ui.components
2
2
3+import android.content.ClipData
4+import android.content.ClipboardManager
5+import android.content.Context
6+import android.content.Intent
7+import android.net.Uri
8+import android.widget.Toast
9+import androidx.compose.foundation.ExperimentalFoundationApi
3import androidx.compose.foundation.background
10import androidx.compose.foundation.background
11+import androidx.compose.foundation.clickable
12+import androidx.compose.foundation.combinedClickable
4import androidx.compose.foundation.layout.Arrangement
13import androidx.compose.foundation.layout.Arrangement
5import androidx.compose.foundation.layout.Column
14import androidx.compose.foundation.layout.Column
6import androidx.compose.foundation.layout.Row
15import androidx.compose.foundation.layout.Row
7import androidx.compose.foundation.layout.fillMaxWidth
16import androidx.compose.foundation.layout.fillMaxWidth
8import androidx.compose.foundation.layout.padding
17import androidx.compose.foundation.layout.padding
18+import androidx.compose.foundation.layout.size
9import androidx.compose.foundation.layout.widthIn
19import androidx.compose.foundation.layout.widthIn
10import androidx.compose.foundation.shape.RoundedCornerShape
20import androidx.compose.foundation.shape.RoundedCornerShape
21+import androidx.compose.foundation.text.selection.SelectionContainer
11import androidx.compose.material.icons.Icons
22import androidx.compose.material.icons.Icons
12import androidx.compose.material.icons.filled.Build
23import androidx.compose.material.icons.filled.Build
24+import androidx.compose.material.icons.filled.Check
13import androidx.compose.material.icons.filled.ErrorOutline
25import androidx.compose.material.icons.filled.ErrorOutline
26+import androidx.compose.material.icons.filled.ExpandLess
27+import androidx.compose.material.icons.filled.ExpandMore
14import androidx.compose.material.icons.filled.Schedule
28import 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
15import androidx.compose.material3.Icon
32import androidx.compose.material3.Icon
16import androidx.compose.material3.MaterialTheme
33import androidx.compose.material3.MaterialTheme
17import androidx.compose.material3.Text
34import androidx.compose.material3.Text
18import androidx.compose.runtime.Composable
35import androidx.compose.runtime.Composable
36+import androidx.compose.runtime.getValue
37+import androidx.compose.runtime.mutableStateOf
38+import androidx.compose.runtime.remember
39+import androidx.compose.runtime.setValue
19import androidx.compose.ui.Alignment
40import androidx.compose.ui.Alignment
20import androidx.compose.ui.Modifier
41import androidx.compose.ui.Modifier
21import androidx.compose.ui.draw.clip
42import androidx.compose.ui.draw.clip
22import androidx.compose.ui.graphics.Color
43import androidx.compose.ui.graphics.Color
44+import 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
23import androidx.compose.ui.text.font.FontStyle
51import 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
56+import androidx.compose.ui.text.style.TextOverflow
24import androidx.compose.ui.unit.dp
57import androidx.compose.ui.unit.dp
58+import androidx.compose.ui.unit.sp
25import soy.iko.opencode.core.MessageStatus
59import soy.iko.opencode.core.MessageStatus
26import soy.iko.opencode.core.MessageView
60import soy.iko.opencode.core.MessageView
27import soy.iko.opencode.core.ToolView
61import soy.iko.opencode.core.ToolView
28import soy.iko.opencode.ui.theme.MonoStyle
62import soy.iko.opencode.ui.theme.MonoStyle
29
63
64+private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
65+
66+@OptIn(ExperimentalFoundationApi::class)
30@Composable
67@Composable
31−fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
68+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
32 val isUser = message.isUser
69 val isUser = message.isUser
33 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
70 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
34 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
71 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
72+ val mutedColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.6f) else MaterialTheme.colorScheme.onSurfaceVariant
35 val shape = RoundedCornerShape(
73 val shape = RoundedCornerShape(
36 topStart = 16.dp,
74 topStart = 16.dp,
37 topEnd = 16.dp,
75 topEnd = 16.dp,
@@ -39,53 +77,337 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
39 bottomEnd = if (isUser) 4.dp else 16.dp,
77 bottomEnd = if (isUser) 4.dp else 16.dp,
40 )
78 )
41
79
80+ val context = LocalContext.current
81+ var showMenu by remember { mutableStateOf(false) }
82+
42 Row(
83 Row(
43− modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
84+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
44 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
85 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
45 ) {
86 ) {
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+ }
46 Column(
95 Column(
47 modifier = Modifier
96 modifier = Modifier
97+ .fillMaxWidth(0.85f)
48 .widthIn(max = 320.dp)
98 .widthIn(max = 320.dp)
49 .clip(shape)
99 .clip(shape)
50 .background(bubbleColor)
100 .background(bubbleColor)
101+ .combinedClickable(
102+ onClick = {},
103+ onLongClick = {
104+ if (message.text.isNotEmpty()) {
105+ showMenu = true
106+ }
107+ },
108+ )
51 .padding(horizontal = 14.dp, vertical = 10.dp),
109 .padding(horizontal = 14.dp, vertical = 10.dp),
52 ) {
110 ) {
111+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
112+ DropdownMenuItem(
113+ text = { Text("Copy") },
114+ onClick = {
115+ copyToClipboard(context, message.text)
116+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
117+ showMenu = false
118+ },
119+ )
120+ DropdownMenuItem(
121+ text = { Text("Share") },
122+ onClick = {
123+ shareText(context, message.text)
124+ showMenu = false
125+ },
126+ )
127+ }
128+
53− message.reasoning?.let { ReasoningBlock(it) }
129+ message.reasoning?.let { ReasoningBlock(it, context) }
130+
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+ }
54
140
55 message.tools.forEach { ToolRow(it) }
141 message.tools.forEach { ToolRow(it) }
56
142
143+ SelectionContainer {
57− if (message.text.isNotEmpty()) {
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+ }
166+ }
167+
168+ if (message.time > 0) {
58 Text(
169 Text(
59− text = message.text + if (message.streaming) " ▌" else "",
170+ text = timeFormat.format(java.time.Instant.ofEpochMilli(message.time).atZone(java.time.ZoneId.systemDefault()).toLocalTime()),
60− color = textColor,
61− style = MaterialTheme.typography.bodyLarge,
171+ style = MaterialTheme.typography.labelSmall,
172+ color = mutedColor,
173+ modifier = Modifier.padding(top = 4.dp),
62 )
174 )
63− } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
64− Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
65 }
175 }
66
176
67 if (isUser && message.status != MessageStatus.Sent) {
177 if (isUser && message.status != MessageStatus.Sent) {
68− StatusLine(message.status)
178+ StatusLine(message.status, onRetry = onRetry)
179+ }
180+ }
181+ }
182+}
183+
184+private fun copyToClipboard(context: Context, text: String) {
185+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
186+ clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
187+}
188+
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)
69 }
246 }
247+ } else {
248+ if (isUnclosedTail) append("**")
249+ appendItalicText(segment, linkColor, codeBackground, context)
70 }
250 }
71 }
251 }
72}
252}
73
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+
74@Composable
353@Composable
75−private fun ReasoningBlock(text: String) {
354+private fun ReasoningBlock(text: String, context: Context) {
355+ var expanded by remember { mutableStateOf(false) }
356+ Column(modifier = Modifier.padding(bottom = 6.dp)) {
357+ Row(
358+ verticalAlignment = Alignment.CenterVertically,
359+ modifier = Modifier.clickable { expanded = !expanded },
360+ ) {
76− Text(
361+ Text(
362+ text = if (expanded) "Show less" else "Reasoning",
363+ style = MaterialTheme.typography.bodySmall,
364+ color = MaterialTheme.colorScheme.onSurfaceVariant,
365+ )
366+ Icon(
367+ imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
368+ contentDescription = if (expanded) "Collapse reasoning" else "Expand reasoning",
369+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
370+ modifier = Modifier.padding(start = 2.dp).widthIn(max = 18.dp),
371+ )
372+ }
373+ if (expanded) {
374+ Text(
77− text = text,
375+ text = text,
78− style = MaterialTheme.typography.bodySmall.copy(fontStyle = FontStyle.Italic),
376+ style = MaterialTheme.typography.bodySmall.copy(fontStyle = FontStyle.Italic),
79− color = MaterialTheme.colorScheme.onSurfaceVariant,
377+ color = MaterialTheme.colorScheme.onSurfaceVariant,
378+ modifier = Modifier.padding(top = 4.dp),
379+ )
380+ Text(
381+ text = "Copy",
382+ style = MaterialTheme.typography.labelSmall,
383+ color = MaterialTheme.colorScheme.primary,
80− modifier = Modifier.padding(bottom = 6.dp),
384+ modifier = Modifier
81− )
385+ .padding(top = 4.dp)
386+ .clickable {
387+ copyToClipboard(context, text)
388+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
389+ },
390+ )
391+ }
392+ }
82}
393}
83
394
84@Composable
395@Composable
85private fun ToolRow(tool: ToolView) {
396private fun ToolRow(tool: ToolView) {
397+ 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+ }
86 Row(
405 Row(
87 verticalAlignment = Alignment.CenterVertically,
406 verticalAlignment = Alignment.CenterVertically,
88− modifier = Modifier.padding(bottom = 6.dp),
407+ modifier = Modifier
408+ .fillMaxWidth()
409+ .clickable { expanded = !expanded }
410+ .padding(bottom = 6.dp),
89 ) {
411 ) {
90 Icon(
412 Icon(
91 Icons.Filled.Build,
413 Icons.Filled.Build,
@@ -94,25 +416,42 @@ private fun ToolRow(tool: ToolView) {
94 modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
416 modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
95 )
417 )
96 Text(
418 Text(
97− text = buildString {
419+ text = buildAnnotatedString {
420+ withStyle(SpanStyle(color = baseColor)) {
98− append(tool.name)
421+ append(tool.name)
99− append(" · ")
422+ append(" · ")
423+ }
424+ withStyle(SpanStyle(color = statusColor)) {
100− append(tool.status)
425+ append(tool.status)
426+ }
101− tool.title?.let { append(" — "); append(it) }
427+ if (expanded) tool.title?.let {
428+ withStyle(SpanStyle(color = baseColor)) {
429+ append(" — ")
430+ append(it)
431+ }
432+ }
102 },
433 },
103 style = MonoStyle,
434 style = MonoStyle,
435+ color = baseColor,
436+ maxLines = if (expanded) Int.MAX_VALUE else 1,
437+ overflow = TextOverflow.Ellipsis,
438+ modifier = Modifier.weight(1f),
439+ )
440+ Icon(
441+ imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore,
442+ contentDescription = if (expanded) "Collapse tool details" else "Expand tool details",
104− color = MaterialTheme.colorScheme.onSurfaceVariant,
443+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
105− maxLines = 3,
444+ modifier = Modifier.padding(start = 2.dp).widthIn(max = 18.dp),
106 )
445 )
107 }
446 }
108}
447}
109
448
110@Composable
449@Composable
111−private fun StatusLine(status: MessageStatus) {
450+private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
112 val (icon, label, tint) = when (status) {
451 val (icon, label, tint) = when (status) {
113 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
452 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
114 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
453 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
115− MessageStatus.Sent -> Triple(Icons.Filled.Schedule, "", Color.Unspecified)
454+ MessageStatus.Sent -> Triple(Icons.Filled.Check, "", Color.Unspecified)
116 }
455 }
117 Row(
456 Row(
118 verticalAlignment = Alignment.CenterVertically,
457 verticalAlignment = Alignment.CenterVertically,
@@ -126,5 +465,15 @@ private fun StatusLine(status: MessageStatus) {
126 color = tint,
465 color = tint,
127 modifier = Modifier.padding(start = 4.dp),
466 modifier = Modifier.padding(start = 4.dp),
128 )
467 )
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+ }
129 }
478 }
130}
479}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+468−24
@@ -1,53 +1,146 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
2
2
3+import android.content.ClipData
4+import android.content.ClipboardManager
5+import android.content.Context
6+import android.widget.Toast
7+import androidx.compose.animation.AnimatedVisibility
8+import androidx.compose.animation.core.RepeatMode
9+import androidx.compose.animation.core.animateFloat
10+import androidx.compose.animation.core.infiniteRepeatable
11+import androidx.compose.animation.core.rememberInfiniteTransition
12+import androidx.compose.animation.core.tween
13+import androidx.compose.animation.fadeIn
14+import androidx.compose.animation.fadeOut
15+import androidx.compose.animation.scaleIn
16+import androidx.compose.animation.scaleOut
17+import androidx.compose.foundation.ExperimentalFoundationApi
18+import androidx.compose.foundation.background
19+import androidx.compose.foundation.clickable
20+import androidx.compose.foundation.combinedClickable
3import androidx.compose.foundation.layout.Arrangement
21import androidx.compose.foundation.layout.Arrangement
4import androidx.compose.foundation.layout.Box
22import androidx.compose.foundation.layout.Box
23+import androidx.compose.foundation.layout.BoxScope
5import androidx.compose.foundation.layout.Column
24import androidx.compose.foundation.layout.Column
6import androidx.compose.foundation.layout.Row
25import androidx.compose.foundation.layout.Row
26+import androidx.compose.foundation.layout.Spacer
7import androidx.compose.foundation.layout.fillMaxSize
27import androidx.compose.foundation.layout.fillMaxSize
8import androidx.compose.foundation.layout.fillMaxWidth
28import androidx.compose.foundation.layout.fillMaxWidth
29+import androidx.compose.foundation.layout.heightIn
9import androidx.compose.foundation.layout.PaddingValues
30import androidx.compose.foundation.layout.PaddingValues
31+import androidx.compose.foundation.layout.WindowInsets
32+import androidx.compose.foundation.layout.ime
10import androidx.compose.foundation.layout.imePadding
33import androidx.compose.foundation.layout.imePadding
11import androidx.compose.foundation.layout.padding
34import androidx.compose.foundation.layout.padding
12import androidx.compose.foundation.layout.size
35import androidx.compose.foundation.layout.size
13import androidx.compose.foundation.lazy.LazyColumn
36import androidx.compose.foundation.lazy.LazyColumn
14−import androidx.compose.foundation.lazy.items
37+import androidx.compose.foundation.lazy.itemsIndexed
15import androidx.compose.foundation.lazy.rememberLazyListState
38import androidx.compose.foundation.lazy.rememberLazyListState
39+import androidx.compose.foundation.shape.CircleShape
40+import androidx.compose.foundation.shape.RoundedCornerShape
41+import androidx.compose.foundation.text.KeyboardActions
42+import androidx.compose.foundation.text.KeyboardOptions
16import androidx.compose.material.icons.Icons
43import androidx.compose.material.icons.Icons
17import androidx.compose.material.icons.automirrored.filled.ArrowBack
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
18import androidx.compose.material.icons.automirrored.filled.Send
45import androidx.compose.material.icons.automirrored.filled.Send
46+import androidx.compose.material.icons.filled.ChatBubbleOutline
47+import androidx.compose.material.icons.filled.Close
48+import androidx.compose.material.icons.filled.KeyboardArrowDown
49+import androidx.compose.material.icons.filled.KeyboardArrowUp
19import androidx.compose.material.icons.filled.Stop
50import androidx.compose.material.icons.filled.Stop
20import androidx.compose.material3.CircularProgressIndicator
51import androidx.compose.material3.CircularProgressIndicator
21import androidx.compose.material3.ExperimentalMaterial3Api
52import androidx.compose.material3.ExperimentalMaterial3Api
22import androidx.compose.material3.FilledIconButton
53import androidx.compose.material3.FilledIconButton
54+import androidx.compose.material3.FilledTonalButton
55+import androidx.compose.material3.FloatingActionButton
23import androidx.compose.material3.Icon
56import androidx.compose.material3.Icon
24import androidx.compose.material3.IconButton
57import androidx.compose.material3.IconButton
58+import androidx.compose.material3.LinearProgressIndicator
25import androidx.compose.material3.MaterialTheme
59import androidx.compose.material3.MaterialTheme
26import androidx.compose.material3.OutlinedTextField
60import androidx.compose.material3.OutlinedTextField
27import androidx.compose.material3.Scaffold
61import androidx.compose.material3.Scaffold
28import androidx.compose.material3.Surface
62import androidx.compose.material3.Surface
29import androidx.compose.material3.Text
63import androidx.compose.material3.Text
64+import androidx.compose.material3.TextButton
30import androidx.compose.material3.TopAppBar
65import androidx.compose.material3.TopAppBar
31import androidx.compose.runtime.Composable
66import androidx.compose.runtime.Composable
32import androidx.compose.runtime.LaunchedEffect
67import androidx.compose.runtime.LaunchedEffect
68+import androidx.compose.runtime.derivedStateOf
69+import androidx.compose.runtime.getValue
70+import androidx.compose.runtime.mutableStateOf
71+import androidx.compose.runtime.remember
72+import androidx.compose.runtime.rememberCoroutineScope
73+import androidx.compose.runtime.setValue
33import androidx.compose.ui.Alignment
74import androidx.compose.ui.Alignment
34import androidx.compose.ui.Modifier
75import androidx.compose.ui.Modifier
76+import androidx.compose.ui.draw.clip
77+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
78+import androidx.compose.ui.platform.LocalClipboardManager
79+import androidx.compose.ui.platform.LocalContext
80+import androidx.compose.ui.platform.LocalDensity
81+import androidx.compose.ui.platform.LocalHapticFeedback
82+import androidx.compose.ui.text.font.FontStyle
83+import androidx.compose.ui.text.input.ImeAction
84+import androidx.compose.ui.text.style.TextAlign
35import androidx.compose.ui.text.style.TextOverflow
85import androidx.compose.ui.text.style.TextOverflow
36import androidx.compose.ui.unit.dp
86import androidx.compose.ui.unit.dp
87+import kotlinx.coroutines.launch
37import soy.iko.opencode.core.Event
88import soy.iko.opencode.core.Event
38import soy.iko.opencode.core.UiState
89import soy.iko.opencode.core.UiState
39import soy.iko.opencode.ui.components.MessageBubble
90import soy.iko.opencode.ui.components.MessageBubble
40
91
41−@OptIn(ExperimentalMaterial3Api::class)
92+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
42@Composable
93@Composable
43fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
94fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
44 val listState = rememberLazyListState()
95 val listState = rememberLazyListState()
96+ val coroutineScope = rememberCoroutineScope()
97+ val context = LocalContext.current
45
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
103+
104+ // Show a jump-to-bottom button once the user scrolls up away from the latest
105+ // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
106+ // it only flips when the near-bottom threshold is actually crossed.
107+ val showScrollButton by remember {
108+ derivedStateOf {
109+ val layoutInfo = listState.layoutInfo
110+ val lastVisibleIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
111+ val totalItems = layoutInfo.totalItemsCount
112+ totalItems > 0 && lastVisibleIndex < totalItems - 3
113+ }
114+ }
115+
116+ // Offer a jump-to-top shortcut once the conversation is long and the user has
117+ // scrolled a few messages down — saves flick-scrolling back through history.
118+ val showScrollTop by remember {
119+ derivedStateOf { state.messages.size > 10 && listState.firstVisibleItemIndex > 3 }
120+ }
121+
122+ // Track how many messages the user has "seen" (i.e. was at the bottom for). While
123+ // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
124+ var lastSeenCount by remember { mutableStateOf(0) }
125+ LaunchedEffect(showScrollButton, state.messages.size) {
126+ if (!showScrollButton) {
127+ lastSeenCount = state.messages.size
128+ }
129+ }
130+ val hasUnseenMessages = showScrollButton && state.messages.size > lastSeenCount
131+
46− // Keep the newest content in view as it streams in.
132+ // Keep the newest content in view as it streams in, but only when the user is
133+ // already near the bottom. If they've scrolled up to read history, leave it alone.
47 val lastLen = state.messages.lastOrNull()?.text?.length ?: 0
134 val lastLen = state.messages.lastOrNull()?.text?.length ?: 0
48 LaunchedEffect(state.messages.size, lastLen, state.generating) {
135 LaunchedEffect(state.messages.size, lastLen, state.generating) {
49 if (state.messages.isNotEmpty()) {
136 if (state.messages.isNotEmpty()) {
137+ val layoutInfo = listState.layoutInfo
138+ val lastVisibleIndex = layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0
139+ val totalItems = layoutInfo.totalItemsCount
140+ val nearBottom = totalItems == 0 || lastVisibleIndex >= totalItems - 3
141+ if (nearBottom) {
50− listState.animateScrollToItem(state.messages.size - 1)
142+ listState.animateScrollToItem(state.messages.size - 1)
143+ }
51 }
144 }
52 }
145 }
53
146
@@ -55,10 +148,20 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
55 topBar = {
148 topBar = {
56 TopAppBar(
149 TopAppBar(
57 title = {
150 title = {
151+ val title = state.currentSessionTitle.ifEmpty { "Chat" }
58 Text(
152 Text(
59− text = state.currentSessionTitle.ifEmpty { "Chat" },
153+ text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
60 maxLines = 1,
154 maxLines = 1,
61 overflow = TextOverflow.Ellipsis,
155 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+ ),
62 )
165 )
63 },
166 },
64 navigationIcon = {
167 navigationIcon = {
@@ -80,67 +183,408 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
80 ChatInputBar(
183 ChatInputBar(
81 draft = state.draft,
184 draft = state.draft,
82 generating = state.generating,
185 generating = state.generating,
186+ loading = state.loading && state.messages.isEmpty(),
83 onDraftChange = { dispatch(Event.DraftChanged(it)) },
187 onDraftChange = { dispatch(Event.DraftChanged(it)) },
84 onSend = { dispatch(Event.SendMessage(state.draft)) },
188 onSend = { dispatch(Event.SendMessage(state.draft)) },
85 onStop = { dispatch(Event.CancelGeneration) },
189 onStop = { dispatch(Event.CancelGeneration) },
86 )
190 )
87 },
191 },
88 ) { padding ->
192 ) { padding ->
89− Box(Modifier.fillMaxSize().padding(padding)) {
193+ Column(Modifier.fillMaxSize().padding(padding)) {
194+ if (!state.sseConnected && !state.generating) {
195+ ReconnectingBanner()
196+ }
90− if (state.messages.isEmpty() && !state.loading) {
197+ if (state.loading && state.messages.isEmpty()) {
198+ LinearProgressIndicator(Modifier.fillMaxWidth())
199+ }
200+ if (state.error != null && state.messages.isNotEmpty()) {
201+ ErrorBanner(
202+ message = state.error,
203+ onDismiss = { dispatch(Event.DismissError) },
204+ )
205+ }
206+ Box(Modifier.fillMaxWidth().weight(1f)) {
207+ if (state.messages.isEmpty() && !state.loading) {
208+ Column(
209+ 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))
91− Text(
219+ Text(
92− text = "Send a message to start the conversation.",
220+ text = "Send a message to start the conversation.",
93− style = MaterialTheme.typography.bodyMedium,
221+ style = MaterialTheme.typography.bodyMedium,
94− color = MaterialTheme.colorScheme.onSurfaceVariant,
222+ color = MaterialTheme.colorScheme.onSurfaceVariant,
223+ textAlign = TextAlign.Center,
224+ )
225+ }
226+ }
227+ LazyColumn(
228+ state = listState,
95− modifier = Modifier.align(Alignment.Center).padding(32.dp),
229+ modifier = Modifier.fillMaxSize(),
230+ contentPadding = PaddingValues(vertical = 8.dp),
231+ ) {
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+ }
253+ }
254+ }
255+ ScrollToBottomButton(
256+ visible = showScrollButton && !isImeVisible,
257+ showBadge = hasUnseenMessages,
258+ onClick = {
259+ coroutineScope.launch {
260+ if (state.messages.isNotEmpty()) {
261+ // When the typing indicator is showing it occupies the item
262+ // just past the last message, so scroll one further to reach it.
263+ val target = if (state.generating && state.messages.none { it.streaming })
264+ state.messages.size
265+ else
266+ state.messages.size - 1
267+ listState.animateScrollToItem(target)
268+ }
269+ }
270+ },
271+ )
272+ ScrollToTopButton(
273+ visible = showScrollTop,
274+ onClick = {
275+ coroutineScope.launch {
276+ listState.animateScrollToItem(0)
277+ }
278+ },
279+ )
280+ }
281+ }
282+ }
283+}
284+
285+// Extracted into a BoxScope extension so the top-level AnimatedVisibility overload
286+// resolves cleanly. Called inline inside a Column, the enclosing ColumnScope receiver
287+// would otherwise capture the ColumnScope.AnimatedVisibility overload and fail to compile.
288+@Composable
289+private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean, onClick: () -> Unit) {
290+ AnimatedVisibility(
291+ visible = visible,
292+ modifier = Modifier.align(Alignment.BottomEnd),
293+ enter = scaleIn() + fadeIn(),
294+ exit = scaleOut() + fadeOut(),
295+ ) {
296+ Box(Modifier.padding(16.dp)) {
297+ FloatingActionButton(
298+ onClick = onClick,
299+ modifier = Modifier.size(44.dp),
300+ ) {
301+ Icon(
302+ Icons.Filled.KeyboardArrowDown,
303+ contentDescription = "Scroll to latest message",
96 )
304 )
97 }
305 }
98− LazyColumn(
306+ if (showBadge) {
99− state = listState,
307+ Box(
100− modifier = Modifier.fillMaxSize(),
308+ modifier = Modifier
101− contentPadding = PaddingValues(vertical = 8.dp),
309+ .align(Alignment.TopEnd)
310+ .size(8.dp)
311+ .clip(CircleShape)
312+ .background(MaterialTheme.colorScheme.error),
313+ )
314+ }
315+ }
316+ }
317+}
318+
319+// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
320+// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
321+@Composable
322+private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
323+ AnimatedVisibility(
324+ visible = visible,
325+ modifier = Modifier.align(Alignment.TopStart),
326+ enter = scaleIn() + fadeIn(),
327+ exit = scaleOut() + fadeOut(),
328+ ) {
329+ Box(Modifier.padding(16.dp)) {
330+ FloatingActionButton(
331+ onClick = onClick,
332+ modifier = Modifier.size(44.dp),
102 ) {
333 ) {
103− items(state.messages, key = { it.id }) { message ->
334+ Icon(
104− MessageBubble(message)
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+ )
105 }
430 }
106 }
431 }
107 }
432 }
108 }
433 }
109}
434}
110
435
436+@Composable
437+private fun ReconnectingBanner() {
438+ Surface(
439+ modifier = Modifier.fillMaxWidth(),
440+ color = MaterialTheme.colorScheme.tertiaryContainer,
441+ ) {
442+ Row(
443+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
444+ verticalAlignment = Alignment.CenterVertically,
445+ horizontalArrangement = Arrangement.spacedBy(8.dp),
446+ ) {
447+ CircularProgressIndicator(
448+ modifier = Modifier.size(14.dp),
449+ strokeWidth = 2.dp,
450+ color = MaterialTheme.colorScheme.onTertiaryContainer,
451+ )
452+ Text(
453+ text = "Reconnecting…",
454+ style = MaterialTheme.typography.bodySmall,
455+ color = MaterialTheme.colorScheme.onTertiaryContainer,
456+ )
457+ }
458+ }
459+}
460+
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+
111@Composable
490@Composable
112private fun ChatInputBar(
491private fun ChatInputBar(
113 draft: String,
492 draft: String,
114 generating: Boolean,
493 generating: Boolean,
494+ loading: Boolean,
115 onDraftChange: (String) -> Unit,
495 onDraftChange: (String) -> Unit,
116 onSend: () -> Unit,
496 onSend: () -> Unit,
117 onStop: () -> Unit,
497 onStop: () -> Unit,
118) {
498) {
499+ val haptic = LocalHapticFeedback.current
500+ val clipboardManager = LocalClipboardManager.current
119 Surface(tonalElevation = 3.dp) {
501 Surface(tonalElevation = 3.dp) {
120− Row(
502+ Column(
121 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
503 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504+ ) {
505+ Row(
506+ modifier = Modifier.fillMaxWidth(),
122 verticalAlignment = Alignment.Bottom,
507 verticalAlignment = Alignment.Bottom,
123 horizontalArrangement = Arrangement.spacedBy(8.dp),
508 horizontalArrangement = Arrangement.spacedBy(8.dp),
124 ) {
509 ) {
125 OutlinedTextField(
510 OutlinedTextField(
126 value = draft,
511 value = draft,
127 onValueChange = onDraftChange,
512 onValueChange = onDraftChange,
128− modifier = Modifier.weight(1f),
513+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
514+ enabled = !loading,
129 placeholder = { Text("Message opencode…") },
515 placeholder = { Text("Message opencode…") },
130 maxLines = 5,
516 maxLines = 5,
517+ // Offer a quick way to wipe the draft once there's something to clear
518+ // and we're not mid-generation (where the field is a poor place to fuss).
519+ trailingIcon = if (draft.isNotEmpty() && !generating) {
520+ {
521+ IconButton(
522+ onClick = { onDraftChange("") },
523+ modifier = Modifier.size(20.dp),
524+ ) {
525+ Icon(
526+ Icons.Filled.Close,
527+ contentDescription = "Clear draft",
528+ modifier = Modifier.size(16.dp),
529+ )
530+ }
531+ }
532+ } else {
533+ null
534+ },
535+ // Surface a running count once the draft gets long, so the user has a
536+ // sense of scale before sending a wall of text.
537+ supportingText = if (draft.length > 500) {
538+ {
539+ Text(
540+ text = "${draft.length} characters",
541+ style = MaterialTheme.typography.labelSmall,
542+ color = MaterialTheme.colorScheme.onSurfaceVariant,
543+ textAlign = TextAlign.End,
544+ modifier = Modifier.fillMaxWidth(),
545+ )
546+ }
547+ } else {
548+ null
549+ },
550+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551+ keyboardActions = KeyboardActions(onSend = {
552+ if (!generating && !loading && draft.isNotBlank()) onSend()
553+ }),
131 )
554 )
132 if (generating) {
555 if (generating) {
133− FilledIconButton(onClick = onStop) {
556+ FilledTonalButton(onClick = onStop) {
557+ Icon(
558+ Icons.Filled.Stop,
134− Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
559+ contentDescription = null,
560+ modifier = Modifier.size(18.dp),
561+ )
562+ Spacer(Modifier.size(6.dp))
563+ Text("Stop")
135 }
564 }
136 } else {
565 } else {
137 FilledIconButton(
566 FilledIconButton(
138− onClick = onSend,
567+ onClick = {
568+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
569+ onSend()
570+ },
139− enabled = draft.isNotBlank(),
571+ enabled = draft.isNotBlank() && !loading,
140 ) {
572 ) {
141 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
573 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
142 }
574 }
143 }
575 }
144 }
576 }
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+ }
145 }
589 }
146}
590}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+100−4
@@ -8,6 +8,7 @@ import androidx.compose.foundation.layout.fillMaxWidth
8import androidx.compose.foundation.layout.height
8import androidx.compose.foundation.layout.height
9import androidx.compose.foundation.layout.imePadding
9import androidx.compose.foundation.layout.imePadding
10import androidx.compose.foundation.layout.padding
10import androidx.compose.foundation.layout.padding
11+import androidx.compose.foundation.layout.size
11import androidx.compose.foundation.rememberScrollState
12import androidx.compose.foundation.rememberScrollState
12import androidx.compose.foundation.text.KeyboardActions
13import androidx.compose.foundation.text.KeyboardActions
13import androidx.compose.foundation.text.KeyboardOptions
14import androidx.compose.foundation.text.KeyboardOptions
@@ -15,18 +16,30 @@ import androidx.compose.foundation.verticalScroll
15import androidx.compose.material.icons.Icons
16import androidx.compose.material.icons.Icons
16import androidx.compose.material.icons.filled.Lock
17import androidx.compose.material.icons.filled.Lock
17import androidx.compose.material.icons.filled.Person
18import androidx.compose.material.icons.filled.Person
19+import androidx.compose.material.icons.filled.Terminal
20+import androidx.compose.material.icons.filled.Visibility
21+import androidx.compose.material.icons.filled.VisibilityOff
18import androidx.compose.material3.Button
22import androidx.compose.material3.Button
19import androidx.compose.material3.CircularProgressIndicator
23import androidx.compose.material3.CircularProgressIndicator
20import androidx.compose.material3.Icon
24import androidx.compose.material3.Icon
25+import androidx.compose.material3.IconButton
21import androidx.compose.material3.MaterialTheme
26import androidx.compose.material3.MaterialTheme
22import androidx.compose.material3.OutlinedTextField
27import androidx.compose.material3.OutlinedTextField
23import androidx.compose.material3.Text
28import androidx.compose.material3.Text
24import androidx.compose.runtime.Composable
29import 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
25import androidx.compose.ui.Alignment
35import androidx.compose.ui.Alignment
26import androidx.compose.ui.Modifier
36import androidx.compose.ui.Modifier
37+import androidx.compose.ui.focus.FocusRequester
38+import androidx.compose.ui.focus.focusRequester
27import androidx.compose.ui.text.input.ImeAction
39import androidx.compose.ui.text.input.ImeAction
28import androidx.compose.ui.text.input.KeyboardType
40import androidx.compose.ui.text.input.KeyboardType
29import androidx.compose.ui.text.input.PasswordVisualTransformation
41import androidx.compose.ui.text.input.PasswordVisualTransformation
42+import androidx.compose.ui.text.input.VisualTransformation
30import androidx.compose.ui.text.style.TextAlign
43import androidx.compose.ui.text.style.TextAlign
31import androidx.compose.ui.unit.dp
44import androidx.compose.ui.unit.dp
32import soy.iko.opencode.core.Event
45import soy.iko.opencode.core.Event
@@ -34,6 +47,15 @@ import soy.iko.opencode.core.UiState
34
47
35@Composable
48@Composable
36fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
49fun 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+
37 Column(
59 Column(
38 modifier = Modifier
60 modifier = Modifier
39 .fillMaxSize()
61 .fillMaxSize()
@@ -43,6 +65,13 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
43 verticalArrangement = Arrangement.Center,
65 verticalArrangement = Arrangement.Center,
44 horizontalAlignment = Alignment.CenterHorizontally,
66 horizontalAlignment = Alignment.CenterHorizontally,
45 ) {
67 ) {
68+ Icon(
69+ Icons.Filled.Terminal,
70+ contentDescription = null,
71+ tint = MaterialTheme.colorScheme.primary,
72+ modifier = Modifier.size(72.dp),
73+ )
74+ Spacer(Modifier.height(16.dp))
46 Text(
75 Text(
47 text = "opencode",
76 text = "opencode",
48 style = MaterialTheme.typography.displaySmall,
77 style = MaterialTheme.typography.displaySmall,
@@ -63,7 +92,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
63 label = { Text("Server URL") },
92 label = { Text("Server URL") },
64 placeholder = { Text("http://192.168.1.10:4096") },
93 placeholder = { Text("http://192.168.1.10:4096") },
65 singleLine = true,
94 singleLine = true,
66− modifier = Modifier.fillMaxWidth(),
95+ modifier = Modifier.fillMaxWidth().focusRequester(focusRequester),
67 keyboardOptions = KeyboardOptions(
96 keyboardOptions = KeyboardOptions(
68 keyboardType = KeyboardType.Uri,
97 keyboardType = KeyboardType.Uri,
69 imeAction = if (state.authRequired) ImeAction.Next else ImeAction.Go,
98 imeAction = if (state.authRequired) ImeAction.Next else ImeAction.Go,
@@ -72,6 +101,30 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
72 enabled = !state.loading,
101 enabled = !state.loading,
73 )
102 )
74
103
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+
75 if (state.authRequired) {
128 if (state.authRequired) {
76 Spacer(Modifier.height(12.dp))
129 Spacer(Modifier.height(12.dp))
77 OutlinedTextField(
130 OutlinedTextField(
@@ -90,11 +143,27 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
90 onValueChange = { dispatch(Event.PasswordChanged(it)) },
143 onValueChange = { dispatch(Event.PasswordChanged(it)) },
91 label = { Text("Password") },
144 label = { Text("Password") },
92 singleLine = true,
145 singleLine = true,
93− visualTransformation = PasswordVisualTransformation(),
146+ visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
94 leadingIcon = { Icon(Icons.Filled.Lock, contentDescription = null) },
147 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+ },
95 modifier = Modifier.fillMaxWidth(),
156 modifier = Modifier.fillMaxWidth(),
96 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
97− keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
158+ keyboardActions = KeyboardActions(onGo = {
159+ // Mirror the connect button's enabled condition so the keyboard's
160+ // Go action can't fire a request the form isn't ready for.
161+ if (!state.loading && state.serverUrl.isNotBlank() &&
162+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank())
163+ ) {
164+ dispatch(Event.Connect)
165+ }
166+ }),
98 enabled = !state.loading,
167 enabled = !state.loading,
99 )
168 )
100 Spacer(Modifier.height(4.dp))
169 Spacer(Modifier.height(4.dp))
@@ -109,7 +178,10 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
109
178
110 Button(
179 Button(
111 onClick = { dispatch(Event.Connect) },
180 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.
112− enabled = !state.loading && state.serverUrl.isNotBlank(),
183+ enabled = !state.loading && state.serverUrl.isNotBlank() &&
184+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
113 modifier = Modifier.fillMaxWidth(),
185 modifier = Modifier.fillMaxWidth(),
114 ) {
186 ) {
115 if (state.loading) {
187 if (state.loading) {
@@ -122,5 +194,29 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
122 Text(if (state.authRequired) "Sign in" else "Connect")
194 Text(if (state.authRequired) "Sign in" else "Connect")
123 }
195 }
124 }
196 }
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+ }
125 }
221 }
126}
222}
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+275−19
@@ -1,21 +1,37 @@
1package soy.iko.opencode.ui.screens
1package soy.iko.opencode.ui.screens
2
2
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
8+import androidx.compose.foundation.background
3import androidx.compose.foundation.clickable
9import androidx.compose.foundation.clickable
10+import androidx.compose.foundation.combinedClickable
4import androidx.compose.foundation.layout.Arrangement
11import androidx.compose.foundation.layout.Arrangement
12+import androidx.compose.foundation.layout.Box
5import androidx.compose.foundation.layout.Column
13import androidx.compose.foundation.layout.Column
6import androidx.compose.foundation.layout.PaddingValues
14import androidx.compose.foundation.layout.PaddingValues
7import androidx.compose.foundation.layout.Row
15import androidx.compose.foundation.layout.Row
16+import androidx.compose.foundation.layout.Spacer
8import androidx.compose.foundation.layout.fillMaxSize
17import androidx.compose.foundation.layout.fillMaxSize
9import androidx.compose.foundation.layout.fillMaxWidth
18import androidx.compose.foundation.layout.fillMaxWidth
19+import androidx.compose.foundation.layout.height
10import androidx.compose.foundation.layout.padding
20import androidx.compose.foundation.layout.padding
21+import androidx.compose.foundation.layout.size
11import androidx.compose.foundation.lazy.LazyColumn
22import androidx.compose.foundation.lazy.LazyColumn
12import 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
13import androidx.compose.material.icons.Icons
26import androidx.compose.material.icons.Icons
14import androidx.compose.material.icons.automirrored.filled.ArrowBack
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
15import androidx.compose.material.icons.filled.Add
28import androidx.compose.material.icons.filled.Add
16import androidx.compose.material.icons.filled.ChatBubbleOutline
29import androidx.compose.material.icons.filled.ChatBubbleOutline
30+import androidx.compose.material.icons.filled.ChevronRight
17import androidx.compose.material.icons.filled.DeleteOutline
31import androidx.compose.material.icons.filled.DeleteOutline
18import androidx.compose.material.icons.filled.Refresh
32import androidx.compose.material.icons.filled.Refresh
33+import androidx.compose.material3.AlertDialog
34+import androidx.compose.material3.CircularProgressIndicator
19import androidx.compose.material3.ExperimentalMaterial3Api
35import androidx.compose.material3.ExperimentalMaterial3Api
20import androidx.compose.material3.ExtendedFloatingActionButton
36import androidx.compose.material3.ExtendedFloatingActionButton
21import androidx.compose.material3.HorizontalDivider
37import androidx.compose.material3.HorizontalDivider
@@ -23,12 +39,31 @@ import androidx.compose.material3.Icon
23import androidx.compose.material3.IconButton
39import androidx.compose.material3.IconButton
24import androidx.compose.material3.LinearProgressIndicator
40import androidx.compose.material3.LinearProgressIndicator
25import androidx.compose.material3.MaterialTheme
41import androidx.compose.material3.MaterialTheme
42+import androidx.compose.material3.OutlinedTextField
26import androidx.compose.material3.Scaffold
43import androidx.compose.material3.Scaffold
44+import androidx.compose.material3.Surface
45+import androidx.compose.material3.SwipeToDismissBox
46+import androidx.compose.material3.SwipeToDismissBoxValue
27import androidx.compose.material3.Text
47import androidx.compose.material3.Text
48+import androidx.compose.material3.TextButton
28import androidx.compose.material3.TopAppBar
49import androidx.compose.material3.TopAppBar
50+import androidx.compose.material3.rememberSwipeToDismissBoxState
51+import androidx.compose.material3.pulltorefresh.PullToRefreshBox
52+import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
29import androidx.compose.runtime.Composable
53import androidx.compose.runtime.Composable
54+import androidx.compose.runtime.LaunchedEffect
55+import androidx.compose.runtime.getValue
56+import androidx.compose.runtime.mutableStateOf
57+import androidx.compose.runtime.remember
58+import androidx.compose.runtime.setValue
30import androidx.compose.ui.Alignment
59import androidx.compose.ui.Alignment
31import androidx.compose.ui.Modifier
60import androidx.compose.ui.Modifier
61+import androidx.compose.ui.draw.clip
62+import androidx.compose.ui.graphics.Color
63+import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64+import androidx.compose.ui.platform.LocalContext
65+import androidx.compose.ui.platform.LocalHapticFeedback
66+import androidx.compose.ui.text.style.TextAlign
32import androidx.compose.ui.text.style.TextOverflow
67import androidx.compose.ui.text.style.TextOverflow
33import androidx.compose.ui.unit.dp
68import androidx.compose.ui.unit.dp
34import soy.iko.opencode.core.Event
69import soy.iko.opencode.core.Event
@@ -38,10 +73,69 @@ import soy.iko.opencode.core.UiState
38@OptIn(ExperimentalMaterial3Api::class)
73@OptIn(ExperimentalMaterial3Api::class)
39@Composable
74@Composable
40fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
75fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
76+ val haptic = LocalHapticFeedback.current
77+ var pendingDeleteId by remember { mutableStateOf<String?>(null) }
78+ 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+ }
89+
90+ // The pull-to-refresh spinner should only reflect a user-initiated pull, not
91+ // every loading operation. Clear it once the underlying load completes.
92+ LaunchedEffect(state.loading) {
93+ if (!state.loading) isPullRefreshing = false
94+ }
95+
96+ pendingDeleteId?.let { deleteId ->
97+ val pendingSession = state.sessions.firstOrNull { it.id == deleteId }
98+ AlertDialog(
99+ onDismissRequest = { pendingDeleteId = null },
100+ title = { Text("Delete session?") },
101+ text = { Text(pendingSession?.title ?: deleteId) },
102+ confirmButton = {
103+ TextButton(onClick = {
104+ haptic.performHapticFeedback(HapticFeedbackType.LongPress)
105+ dispatch(Event.DeleteSession(deleteId))
106+ pendingDeleteId = null
107+ }) {
108+ Text("Delete")
109+ }
110+ },
111+ dismissButton = {
112+ TextButton(onClick = { pendingDeleteId = null }) {
113+ Text("Cancel")
114+ }
115+ },
116+ )
117+ }
118+
41 Scaffold(
119 Scaffold(
42 topBar = {
120 topBar = {
43 TopAppBar(
121 TopAppBar(
44− title = { Text("Sessions") },
122+ title = {
123+ Row(verticalAlignment = Alignment.CenterVertically) {
124+ // A quick at-a-glance health dot for the SSE stream: green when
125+ // connected, error-tinted when the stream is down (updates stall).
126+ Box(
127+ modifier = Modifier
128+ .size(8.dp)
129+ .clip(CircleShape)
130+ .background(
131+ if (state.sseConnected) Color(0xFF4CAF50)
132+ else MaterialTheme.colorScheme.error,
133+ ),
134+ )
135+ Spacer(Modifier.size(8.dp))
136+ Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "Sessions")
137+ }
138+ },
45 navigationIcon = {
139 navigationIcon = {
46 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
47 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -55,30 +149,88 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
55 )
149 )
56 },
150 },
57 floatingActionButton = {
151 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()) {
58− ExtendedFloatingActionButton(
155+ ExtendedFloatingActionButton(
59− onClick = { dispatch(Event.CreateSession) },
156+ onClick = { dispatch(Event.CreateSession) },
60− icon = { Icon(Icons.Filled.Add, contentDescription = null) },
157+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
61− text = { Text("New session") },
158+ text = { Text("New session") },
62− )
159+ )
160+ }
63 },
161 },
64 ) { padding ->
162 ) { padding ->
65 Column(Modifier.fillMaxSize().padding(padding)) {
163 Column(Modifier.fillMaxSize().padding(padding)) {
164+ if (!state.sseConnected) {
165+ ReconnectingBanner()
166+ }
66− if (state.loading) {
167+ if (state.loading && !isPullRefreshing) {
67 LinearProgressIndicator(Modifier.fillMaxWidth())
168 LinearProgressIndicator(Modifier.fillMaxWidth())
68 }
169 }
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+ }
69 when {
189 when {
70 state.sessions.isEmpty() && !state.loading -> EmptySessions()
190 state.sessions.isEmpty() && !state.loading -> EmptySessions()
71− else -> LazyColumn(
191+ filteredSessions.isEmpty() && searchQuery.isNotEmpty() -> NoSearchResults(searchQuery)
192+ else -> PullToRefreshBox(
193+ isRefreshing = isPullRefreshing,
194+ onRefresh = {
195+ isPullRefreshing = true
196+ dispatch(Event.LoadSessions)
197+ },
72 modifier = Modifier.fillMaxSize(),
198 modifier = Modifier.fillMaxSize(),
73− contentPadding = PaddingValues(bottom = 88.dp),
199+ state = rememberPullToRefreshState(),
74 ) {
200 ) {
201+ LazyColumn(
202+ state = sessionsListState,
203+ modifier = Modifier.fillMaxSize(),
204+ contentPadding = PaddingValues(bottom = 88.dp),
205+ ) {
75− items(state.sessions, key = { it.id }) { session ->
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+ },
219+ )
220+ SwipeToDismissBox(
221+ state = dismissState,
222+ enableDismissFromStartToEnd = false,
223+ backgroundContent = { SwipeDeleteBackground() },
224+ ) {
76− SessionRow(
225+ SessionRow(
77− session = session,
226+ session = session,
78− onOpen = { dispatch(Event.SelectSession(session.id)) },
227+ onOpen = { dispatch(Event.SelectSession(session.id)) },
79− onDelete = { dispatch(Event.DeleteSession(session.id)) },
228+ onDelete = { pendingDeleteId = session.id },
80− )
229+ )
230+ }
81− HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
231+ HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
232+ }
233+ }
82 }
234 }
83 }
235 }
84 }
236 }
@@ -86,12 +238,21 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
86 }
238 }
87}
239}
88
240
241+@OptIn(ExperimentalFoundationApi::class)
89@Composable
242@Composable
90private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
243private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
244+ val context = LocalContext.current
91 Row(
245 Row(
92 modifier = Modifier
246 modifier = Modifier
93 .fillMaxWidth()
247 .fillMaxWidth()
248+ .background(MaterialTheme.colorScheme.surface)
249+ .combinedClickable(
94− .clickable(onClick = onOpen)
250+ onClick = onOpen,
251+ onLongClick = {
252+ copyToClipboard(context, session.id)
253+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
254+ },
255+ )
95 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
256 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
96 verticalAlignment = Alignment.CenterVertically,
257 verticalAlignment = Alignment.CenterVertically,
97 ) {
258 ) {
@@ -109,23 +270,104 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
109 overflow = TextOverflow.Ellipsis,
270 overflow = TextOverflow.Ellipsis,
110 )
271 )
111 Text(
272 Text(
112− text = session.id,
273+ text = shortSessionId(session.id),
113 style = MaterialTheme.typography.bodySmall,
274 style = MaterialTheme.typography.bodySmall,
114 color = MaterialTheme.colorScheme.onSurfaceVariant,
275 color = MaterialTheme.colorScheme.onSurfaceVariant,
115 maxLines = 1,
276 maxLines = 1,
116 overflow = TextOverflow.Ellipsis,
277 overflow = TextOverflow.Ellipsis,
117 )
278 )
118 }
279 }
280+ Icon(
281+ Icons.Filled.ChevronRight,
282+ contentDescription = null,
283+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
284+ modifier = Modifier.padding(horizontal = 4.dp),
285+ )
119 IconButton(onClick = onDelete) {
286 IconButton(onClick = onDelete) {
120 Icon(
287 Icon(
121 Icons.Filled.DeleteOutline,
288 Icons.Filled.DeleteOutline,
122 contentDescription = "Delete session",
289 contentDescription = "Delete session",
123− tint = MaterialTheme.colorScheme.onSurfaceVariant,
290+ tint = MaterialTheme.colorScheme.error,
124 )
291 )
125 }
292 }
126 }
293 }
127}
294}
128
295
296+/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
297+@Composable
298+private fun SwipeDeleteBackground() {
299+ Box(
300+ modifier = Modifier
301+ .fillMaxSize()
302+ .background(MaterialTheme.colorScheme.error)
303+ .padding(horizontal = 24.dp),
304+ contentAlignment = Alignment.CenterEnd,
305+ ) {
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+ }
345+ }
346+}
347+
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+
353+/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
354+private fun shortSessionId(id: String): String =
355+ if (id.length > 12) id.take(8) + "…" else id
356+
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+
129@Composable
371@Composable
130private fun EmptySessions() {
372private fun EmptySessions() {
131 Column(
373 Column(
@@ -133,6 +375,13 @@ private fun EmptySessions() {
133 verticalArrangement = Arrangement.Center,
375 verticalArrangement = Arrangement.Center,
134 horizontalAlignment = Alignment.CenterHorizontally,
376 horizontalAlignment = Alignment.CenterHorizontally,
135 ) {
377 ) {
378+ Icon(
379+ Icons.Filled.ChatBubbleOutline,
380+ contentDescription = null,
381+ modifier = Modifier.size(64.dp),
382+ tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
383+ )
384+ Spacer(Modifier.height(16.dp))
136 Text(
385 Text(
137 text = "No sessions yet",
386 text = "No sessions yet",
138 style = MaterialTheme.typography.titleMedium,
387 style = MaterialTheme.typography.titleMedium,
@@ -142,5 +391,12 @@ private fun EmptySessions() {
142 style = MaterialTheme.typography.bodyMedium,
391 style = MaterialTheme.typography.bodyMedium,
143 color = MaterialTheme.colorScheme.onSurfaceVariant,
392 color = MaterialTheme.colorScheme.onSurfaceVariant,
144 )
393 )
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+ )
145 }
401 }
146}
402}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+23−4
@@ -1,6 +1,5 @@
1package soy.iko.opencode.ui.theme
1package soy.iko.opencode.ui.theme
2
2
3−import android.app.Activity
4import android.os.Build
3import android.os.Build
5import androidx.compose.foundation.isSystemInDarkTheme
4import androidx.compose.foundation.isSystemInDarkTheme
6import androidx.compose.material3.MaterialTheme
5import androidx.compose.material3.MaterialTheme
@@ -15,7 +14,18 @@ import androidx.compose.ui.platform.LocalContext
15private val DarkColors = darkColorScheme(
14private val DarkColors = darkColorScheme(
16 primary = Emerald,
15 primary = Emerald,
17 onPrimary = Color(0xFF0F1115),
16 onPrimary = Color(0xFF0F1115),
17+ primaryContainer = Color(0xFF1A3D2A),
18+ onPrimaryContainer = Color(0xFFA8E6C1),
18 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),
26+ onTertiaryContainer = Color(0xFFC5C5E6),
27+ errorContainer = Color(0xFF4D2626),
28+ onErrorContainer = Color(0xFFFFB4B4),
19 background = DarkBackground,
29 background = DarkBackground,
20 surface = DarkSurface,
30 surface = DarkSurface,
21 surfaceVariant = DarkSurfaceVariant,
31 surfaceVariant = DarkSurfaceVariant,
@@ -25,7 +35,18 @@ private val DarkColors = darkColorScheme(
25
35
26private val LightColors = lightColorScheme(
36private val LightColors = lightColorScheme(
27 primary = EmeraldDark,
37 primary = EmeraldDark,
38+ primaryContainer = Color(0xFFD7F5E3),
39+ onPrimaryContainer = Color(0xFF0A3D22),
28 secondary = Emerald,
40 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),
29 background = LightBackground,
50 background = LightBackground,
30 surface = LightSurface,
51 surface = LightSurface,
31 surfaceVariant = LightSurfaceVariant,
52 surfaceVariant = LightSurfaceVariant,
@@ -33,12 +54,10 @@ private val LightColors = lightColorScheme(
33 outline = LightOutline,
54 outline = LightOutline,
34)
55)
35
56
36−private val Color0x0F1115 = androidx.compose.ui.graphics.Color(0xFF0F1115)
37−
38@Composable
57@Composable
39fun OpencodeTheme(
58fun OpencodeTheme(
40 darkTheme: Boolean = isSystemInDarkTheme(),
59 darkTheme: Boolean = isSystemInDarkTheme(),
41− dynamicColor: Boolean = true,
60+ dynamicColor: Boolean = false,
42 content: @Composable () -> Unit,
61 content: @Composable () -> Unit,
43) {
62) {
44 val context = LocalContext.current
63 val context = LocalContext.current
app/src/test/java/soy/iko/opencode/core/ConnectUrlTest.kt+34−11
@@ -3,39 +3,62 @@ package soy.iko.opencode.core
3import kotlinx.coroutines.CoroutineScope
3import kotlinx.coroutines.CoroutineScope
4import kotlinx.coroutines.Dispatchers
4import kotlinx.coroutines.Dispatchers
5import kotlinx.coroutines.test.runTest
5import kotlinx.coroutines.test.runTest
6+import okhttp3.OkHttpClient
7+import okhttp3.Interceptor
6import org.junit.Assert.assertEquals
8import org.junit.Assert.assertEquals
7import org.junit.Assert.assertTrue
9import org.junit.Assert.assertTrue
8import org.junit.Test
10import org.junit.Test
11+import java.io.IOException
9
12
10/**
13/**
11− * Regression coverage for the "app crashes after submitting a URL" bug: a
14+ * Covers two related connect-screen bugs:
12− * scheme-less server URL (e.g. "192.168.1.10:4096") used to reach OkHttp's URL
15+ * - the URL field must stay editable — normalizing per keystroke made it
13− * parser and throw, crashing the connect coroutine. It must now (a) be
16+ * "impossible to input" (it ate the "://" as you typed);
14− * normalized to an http:// URL by the core, and (b) never crash the HTTP client
17+ * - a scheme-less URL must still be normalized to http:// on connect, and the
15− * even if something un-parseable slips through.
18+ * HTTP client must never crash on a malformed URL.
16 */
19 */
17class ConnectUrlTest {
20class ConnectUrlTest {
18 private fun core() = OpencodeCore(CoroutineScope(Dispatchers.Unconfined))
21 private fun core() = OpencodeCore(CoroutineScope(Dispatchers.Unconfined))
19
22
23+ /** A client that never touches the network, so Connect's probe can't hang. */
24+ private fun offlineCore(): OpencodeCore {
25+ val offline = OkHttpClient.Builder()
26+ .addInterceptor(Interceptor { throw IOException("offline in test") })
27+ .build()
28+ return OpencodeCore(CoroutineScope(Dispatchers.Unconfined), HttpClient(offline))
29+ }
30+
20 @Test
31 @Test
21− fun `scheme-less url defaults to http`() {
32+ fun `typing preserves raw input verbatim`() {
22 val core = core()
33 val core = core()
34+ // Mid-scheme text the user is still typing must not be rewritten.
35+ core.dispatch(Event.ServerUrlChanged("http:/"))
36+ assertEquals("http:/", core.view.value.serverUrl)
37+ }
38+
39+ @Test
40+ fun `connect normalizes a scheme-less url to http`() {
41+ val core = offlineCore()
23 core.dispatch(Event.ServerUrlChanged("192.168.1.10:4096"))
42 core.dispatch(Event.ServerUrlChanged("192.168.1.10:4096"))
43+ assertEquals("192.168.1.10:4096", core.view.value.serverUrl) // raw while typing
44+ core.dispatch(Event.Connect)
24− assertEquals("http://192.168.1.10:4096", core.view.value.serverUrl)
45+ assertEquals("http://192.168.1.10:4096", core.view.value.serverUrl) // normalized on connect
25 }
46 }
26
47
27 @Test
48 @Test
28− fun `url with scheme is preserved and trimmed`() {
49+ fun `connect trims and keeps an explicit scheme`() {
29− val core = core()
50+ val core = offlineCore()
30 core.dispatch(Event.ServerUrlChanged(" https://host:4096/ "))
51 core.dispatch(Event.ServerUrlChanged(" https://host:4096/ "))
52+ core.dispatch(Event.Connect)
31 assertEquals("https://host:4096", core.view.value.serverUrl)
53 assertEquals("https://host:4096", core.view.value.serverUrl)
32 }
54 }
33
55
34 @Test
56 @Test
35− fun `blank url normalizes to empty`() {
57+ fun `connect on a blank url reports an error`() {
36 val core = core()
58 val core = core()
37 core.dispatch(Event.ServerUrlChanged(" "))
59 core.dispatch(Event.ServerUrlChanged(" "))
60+ core.dispatch(Event.Connect)
38− assertEquals("", core.view.value.serverUrl)
61+ assertEquals("Enter a server URL", core.view.value.error)
39 }
62 }
40
63
41 @Test
64 @Test
shared/src/app.rs+32−9
@@ -294,20 +294,35 @@ impl App for OpencodeApp {
294 // ── Lifecycle / connect ─────────────────────────────────────────
294 // ── Lifecycle / connect ─────────────────────────────────────────
295 Event::Start => render(),
295 Event::Start => render(),
296
296
297+ // Store the field verbatim while typing; normalizing here would fight
298+ // the user's edits (e.g. eat the "://" as they type it). The URL is
299+ // 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.
297 Event::ServerUrlChanged(url) => {
302 Event::ServerUrlChanged(url) => {
298− model.server_url = normalize_url(&url);
303+ model.server_url = url;
304+ if model.error.is_some() {
305+ model.error = None;
306+ }
299 render()
307 render()
300 }
308 }
301 Event::UsernameChanged(u) => {
309 Event::UsernameChanged(u) => {
302 model.username = u;
310 model.username = u;
311+ if model.error.is_some() {
312+ model.error = None;
313+ }
303 render()
314 render()
304 }
315 }
305 Event::PasswordChanged(p) => {
316 Event::PasswordChanged(p) => {
306 model.password = p;
317 model.password = p;
318+ if model.error.is_some() {
319+ model.error = None;
320+ }
307 render()
321 render()
308 }
322 }
309
323
310 Event::Connect => {
324 Event::Connect => {
325+ model.server_url = normalize_url(&model.server_url);
311 if model.server_url.is_empty() {
326 if model.server_url.is_empty() {
312 model.error = Some("Enter a server URL".to_string());
327 model.error = Some("Enter a server URL".to_string());
313 return render();
328 return render();
@@ -337,6 +352,9 @@ impl App for OpencodeApp {
337 title: display_title(&s.title),
352 title: display_title(&s.title),
338 })
353 })
339 .collect();
354 .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());
340 }
358 }
341 Err(e) => model.error = Some(e),
359 Err(e) => model.error = Some(e),
342 }
360 }
@@ -803,28 +821,33 @@ mod tests {
803 }
821 }
804
822
805 #[test]
823 #[test]
806− fn server_url_is_normalized() {
824+ fn server_url_is_kept_raw_while_typing() {
807 let app = app();
825 let app = app();
808 let mut model = Model::default();
826 let mut model = Model::default();
827+ // Mid-scheme input must survive verbatim — normalizing per keystroke
828+ // would eat the "://" the user is typing and make the field unusable.
809− let _ = app.update(Event::ServerUrlChanged(" http://host:4096/ ".into()), &mut model);
829+ let _ = app.update(Event::ServerUrlChanged("http:/".into()), &mut model);
810− assert_eq!(app.view(&model).server_url, "http://host:4096");
830+ assert_eq!(app.view(&model).server_url, "http:/");
811 }
831 }
812
832
813 #[test]
833 #[test]
814− fn server_url_without_scheme_defaults_to_http() {
834+ fn connect_normalizes_scheme_less_url() {
815 let app = app();
835 let app = app();
816 let mut model = Model::default();
836 let mut model = Model::default();
817− // A scheme-less host (what a user often types) must gain http://, or the
837+ // A scheme-less host (what a user often types) must gain http:// on
818− // shell's URL parser throws and the connect attempt crashes.
838+ // connect, or the shell's URL parser throws and the attempt crashes.
819 let _ = app.update(Event::ServerUrlChanged("192.168.1.10:4096".into()), &mut model);
839 let _ = app.update(Event::ServerUrlChanged("192.168.1.10:4096".into()), &mut model);
840+ assert_eq!(app.view(&model).server_url, "192.168.1.10:4096");
841+ let _ = app.update(Event::Connect, &mut model);
820 assert_eq!(app.view(&model).server_url, "http://192.168.1.10:4096");
842 assert_eq!(app.view(&model).server_url, "http://192.168.1.10:4096");
821 }
843 }
822
844
823 #[test]
845 #[test]
824− fn server_url_keeps_https_scheme() {
846+ fn connect_trims_and_keeps_explicit_scheme() {
825 let app = app();
847 let app = app();
826 let mut model = Model::default();
848 let mut model = Model::default();
827− let _ = app.update(Event::ServerUrlChanged("https://host:4096".into()), &mut model);
849+ let _ = app.update(Event::ServerUrlChanged(" https://host:4096/ ".into()), &mut model);
850+ let _ = app.update(Event::Connect, &mut model);
828 assert_eq!(app.view(&model).server_url, "https://host:4096");
851 assert_eq!(app.view(&model).server_url, "https://host:4096");
829 }
852 }
830
853