git.iko.soy/opencode-android
on 9ba5eec help sign in
app/src/main/java/soy/iko/opencode/CoreViewModel.kt−14
since splitsnapshots
unifiedsplit
@@ -23,23 +23,11 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
23 init {
23 init {
24 prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
24 prefs.getString(KEY_URL, null)?.let { core.dispatch(Event.ServerUrlChanged(it)) }
25 prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
25 prefs.getString(KEY_USER, null)?.let { core.dispatch(Event.UsernameChanged(it)) }
26− // The password is stored in plain text in SharedPreferences — a deliberate
27− // convenience trade-off for a local dev tool so reconnecting is one tap.
28− prefs.getString(KEY_PASSWORD, null)?.let { core.dispatch(Event.PasswordChanged(it)) }
29
26
30 // On a fresh process after a configuration change, resume the SSE stream if
27 // On a fresh process after a configuration change, resume the SSE stream if
31 // the core is already connected (no-op otherwise — it guards on `connected`).
28 // the core is already connected (no-op otherwise — it guards on `connected`).
32 core.resumeStreamingIfConnected()
29 core.resumeStreamingIfConnected()
33
30
34− // Returning users shouldn't have to tap Connect: if a URL was restored and we
35− // aren't already connected, kick off the connection attempt on launch. The core
36− // handles an empty/invalid URL, so this only fires when there's something to try.
37− core.view.value.let { restored ->
38− if (restored.serverUrl.isNotEmpty() && !restored.connected) {
39− core.dispatch(Event.Connect)
40− }
41− }
42−
43 // Persist connection details once a connection succeeds.
31 // Persist connection details once a connection succeeds.
44 viewModelScope.launch {
32 viewModelScope.launch {
45 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
33 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
@@ -47,7 +35,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
47 prefs.edit {
35 prefs.edit {
48 putString(KEY_URL, state.serverUrl)
36 putString(KEY_URL, state.serverUrl)
49 putString(KEY_USER, state.username)
37 putString(KEY_USER, state.username)
50− putString(KEY_PASSWORD, state.password)
51 }
38 }
52 }
39 }
53 }
40 }
@@ -61,6 +48,5 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
61 private companion object {
48 private companion object {
62 const val KEY_URL = "serverUrl"
49 const val KEY_URL = "serverUrl"
63 const val KEY_USER = "username"
50 const val KEY_USER = "username"
64− const val KEY_PASSWORD = "password"
65 }
51 }
66}
52}
app/src/main/java/soy/iko/opencode/MainActivity.kt+1−7
@@ -2,7 +2,6 @@ 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
6import androidx.activity.compose.setContent
5import androidx.activity.compose.setContent
7import androidx.activity.enableEdgeToEdge
6import androidx.activity.enableEdgeToEdge
8import androidx.compose.runtime.getValue
7import androidx.compose.runtime.getValue
@@ -13,12 +12,7 @@ import soy.iko.opencode.ui.theme.OpencodeTheme
13
12
14class MainActivity : ComponentActivity() {
13class MainActivity : ComponentActivity() {
15 override fun onCreate(savedInstanceState: Bundle?) {
14 override fun onCreate(savedInstanceState: Bundle?) {
16− enableEdgeToEdge(
15+ enableEdgeToEdge()
17− statusBarStyle = SystemBarStyle.auto(
18− lightScrim = 0xFF0F1115.toInt(),
19− darkScrim = 0xFF0F1115.toInt(),
20− ),
21− )
22 super.onCreate(savedInstanceState)
16 super.onCreate(savedInstanceState)
23 setContent {
17 setContent {
24 OpencodeTheme {
18 OpencodeTheme {
app/src/main/java/soy/iko/opencode/core/HttpClient.kt−1
@@ -51,7 +51,6 @@ class HttpClient(
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
52 runCatching {
52 runCatching {
53 val builder = Request.Builder().url(url).method()
53 val builder = Request.Builder().url(url).method()
54− builder.header("User-Agent", "opencode-android/1.0")
55 if (auth != null) builder.header("Authorization", auth)
54 if (auth != null) builder.header("Authorization", auth)
56 await(okhttp.newCall(builder.build()))
55 await(okhttp.newCall(builder.build()))
57 }
56 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+22−160
@@ -1,7 +1,6 @@
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
5import kotlinx.coroutines.delay
4import kotlinx.coroutines.delay
6import kotlinx.coroutines.flow.MutableStateFlow
5import kotlinx.coroutines.flow.MutableStateFlow
7import kotlinx.coroutines.flow.StateFlow
6import kotlinx.coroutines.flow.StateFlow
@@ -49,31 +48,6 @@ class OpencodeCore(
49 private var sse: SseClient? = null
48 private var sse: SseClient? = null
50 private var sseClosedIntentionally = false
49 private var sseClosedIntentionally = false
51 private var reconnectAttempts = 0
50 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>()
77
51
78 // ── Event entry point ──────────────────────────────────────────────────────
52 // ── Event entry point ──────────────────────────────────────────────────────
79 fun dispatch(event: Event) {
53 fun dispatch(event: Event) {
@@ -81,11 +55,9 @@ class OpencodeCore(
81 // Store the field verbatim while typing; normalizing here would fight
55 // 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
56 // the user's edits (e.g. eat the "://" as they type it). The URL is
83 // normalized once, on Connect.
57 // normalized once, on Connect.
84− // Clear any prior error as soon as the user edits a field, so a stale
85− // message (e.g. "Invalid credentials") doesn't linger while they correct it.
86− is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
58+ is Event.ServerUrlChanged -> { serverUrl = event.url; emit() }
87− is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
59+ is Event.UsernameChanged -> { username = event.value; emit() }
88− is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
60+ is Event.PasswordChanged -> { password = event.value; emit() }
89
61
90 Event.Connect -> {
62 Event.Connect -> {
91 serverUrl = normalizeUrl(serverUrl)
63 serverUrl = normalizeUrl(serverUrl)
@@ -96,54 +68,30 @@ class OpencodeCore(
96 // Leave authRequired as-is; probeHealth sets it from the response (true on
68 // 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.
69 // 401, false on success). Resetting it here just flickers the auth fields.
98 loading = true; error = null; emit()
70 loading = true; error = null; emit()
99− connectJob?.cancel()
100− connectJob = scope.launch { probeHealth() }
71+ scope.launch { probeHealth() }
101 }
72 }
102
73
103− Event.LoadSessions -> {
104− if (!connected) { error = "Not connected"; emit(); return }
105− loading = true; emit()
106− loadSessionsJob?.cancel()
107− loadSessionsJob = scope.launch { loadSessions() }
74+ Event.LoadSessions -> { loading = true; emit(); scope.launch { loadSessions() } }
108− }
109
75
110 is Event.SelectSession -> {
76 is Event.SelectSession -> {
111− // The session may have been deleted (e.g. via SSE) while the list was on
112− // screen; opening it would only 404 on loadMessages. Bail with an error.
113− val session = sessions.firstOrNull { it.id == event.id }
77+ currentSessionTitle = sessions.firstOrNull { it.id == event.id }?.title.orEmpty()
114− if (session == null) { error = "Session no longer exists"; emit(); return }
115− currentSessionTitle = session.title
116 currentSessionId = event.id
78 currentSessionId = event.id
117 messages.clear()
79 messages.clear()
118− removedMessageIds.clear()
119 screen = Screen.Chat
80 screen = Screen.Chat
120 loading = true
81 loading = true
121− generating = false
122 error = null
82 error = null
123 emit()
83 emit()
124− connectJob?.cancel()
125− abortJob?.cancel()
126− sendMessageJob?.cancel()
127− deleteSessionJob?.cancel()
128− loadMessagesJob?.cancel()
129− loadMessagesJob = scope.launch { loadMessages(event.id) }
84+ scope.launch { loadMessages(event.id) }
130 }
85 }
131
86
132− Event.CreateSession -> {
133− if (!connected) { error = "Not connected"; emit(); return }
134− loading = true; error = null; emit()
87+ Event.CreateSession -> { loading = true; error = null; emit(); scope.launch { createSession() } }
135− createSessionJob?.cancel()
136− createSessionJob = scope.launch { createSession() }
137− }
138
88
139 is Event.DeleteSession -> {
89 is Event.DeleteSession -> {
140− if (!connected) { error = "Not connected"; emit(); return }
141 val id = event.id
90 val id = event.id
142 // Delete on the server first; only drop it from the UI once that
91 // Delete on the server first; only drop it from the UI once that
143 // succeeds, so a failed request leaves the session recoverable.
92 // succeeds, so a failed request leaves the session recoverable.
144 loading = true; error = null; emit()
93 loading = true; error = null; emit()
145− deleteSessionJob?.cancel()
146− deleteSessionJob = scope.launch {
94+ scope.launch {
147 http.delete("$serverUrl/session/$id", authHeader()).fold(
95 http.delete("$serverUrl/session/$id", authHeader()).fold(
148 onSuccess = { resp ->
96 onSuccess = { resp ->
149 if (resp.code in 200..299) {
97 if (resp.code in 200..299) {
@@ -176,32 +124,17 @@ class OpencodeCore(
176 messages.forEach { it.streaming = false }
124 messages.forEach { it.streaming = false }
177 emit()
125 emit()
178 val id = currentSessionId ?: return
126 val id = currentSessionId ?: return
179− // Debounce rapid cancel taps: cancel any in-flight abort before firing
180− // another so we don't stack duplicate abort requests.
181− abortJob?.cancel()
182− abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
127+ scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
183 }
128 }
184
129
185 Event.NavigateToSessions -> {
130 Event.NavigateToSessions -> {
186 screen = Screen.Sessions
131 screen = Screen.Sessions
187 currentSessionId = null
132 currentSessionId = null
188 messages.clear()
133 messages.clear()
189− removedMessageIds.clear()
190− draft = ""
191 generating = false
134 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
135 loading = true
196 emit()
136 emit()
197− connectJob?.cancel()
198− abortJob?.cancel()
199− createSessionJob?.cancel()
200− deleteSessionJob?.cancel()
201− sendMessageJob?.cancel()
202− loadMessagesJob?.cancel()
203− loadSessionsJob?.cancel()
204− loadSessionsJob = scope.launch { loadSessions() }
137+ scope.launch { loadSessions() }
205 }
138 }
206
139
207 Event.NavigateToConnect -> {
140 Event.NavigateToConnect -> {
@@ -211,18 +144,10 @@ class OpencodeCore(
211 generating = false
144 generating = false
212 sessions.clear()
145 sessions.clear()
213 messages.clear()
146 messages.clear()
214− removedMessageIds.clear()
215 currentSessionId = null
147 currentSessionId = null
216− draft = ""
217 // Reset to the default so a late-firing close callback from the old
148 // 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.
149 // SSE connection can't flash the reconnecting banner on the next connect.
219 sseConnected = true
150 sseConnected = true
220− connectJob?.cancel()
221− abortJob?.cancel()
222− createSessionJob?.cancel()
223− deleteSessionJob?.cancel()
224− sendMessageJob?.cancel()
225− loadMessagesJob?.cancel()
226 closeSse()
151 closeSse()
227 emit()
152 emit()
228 }
153 }
@@ -236,44 +161,26 @@ class OpencodeCore(
236 if (connected && sse == null) startSse()
161 if (connected && sse == null) startSse()
237 }
162 }
238
163
239− fun shutdown() {
164+ fun shutdown() = closeSse()
240− // Cancel every tracked coroutine before tearing down the stream so none can
241− // emit into a cancelled scope after the ViewModel is cleared.
242− connectJob?.cancel()
243− loadSessionsJob?.cancel()
244− createSessionJob?.cancel()
245− loadMessagesJob?.cancel()
246− deleteSessionJob?.cancel()
247− sendMessageJob?.cancel()
248− abortJob?.cancel()
249− closeSse()
250− }
251
165
252 // ── Effects ────────────────────────────────────────────────────────────────
166 // ── Effects ────────────────────────────────────────────────────────────────
253 private fun sendMessage(raw: String) {
167 private fun sendMessage(raw: String) {
254 val text = raw.trim()
168 val text = raw.trim()
255 val session = currentSessionId ?: return
169 val session = currentSessionId ?: return
256 if (text.isEmpty()) return
170 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
260 localSeq += 1
171 localSeq += 1
261 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
172 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
262 status = MessageStatus.Pending
173 status = MessageStatus.Pending
263 textParts["local"] = text
174 textParts["local"] = text
264 }
175 }
265 messages.add(user)
176 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
269 draft = ""
177 draft = ""
270 generating = true
178 generating = true
271 error = null
179 error = null
272 emit()
180 emit()
273
181
274 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
182 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275− sendMessageJob?.cancel()
276− sendMessageJob = scope.launch {
183+ scope.launch {
277 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
184 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
278 result.fold(
185 result.fold(
279 onSuccess = { resp ->
186 onSuccess = { resp ->
@@ -282,16 +189,12 @@ class OpencodeCore(
282 } else {
189 } else {
283 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
190 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
284 generating = false
191 generating = false
285− messages.forEach { it.streaming = false }
286− draft = savedDraft
287 error = "Server returned status ${resp.code}"
192 error = "Server returned status ${resp.code}"
288 }
193 }
289 },
194 },
290 onFailure = { e ->
195 onFailure = { e ->
291 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
196 messages.firstOrNull { it.id == user.id }?.status = MessageStatus.Failed
292 generating = false
197 generating = false
293− messages.forEach { it.streaming = false }
294− draft = savedDraft
295 error = "Request failed: ${e.message}"
198 error = "Request failed: ${e.message}"
296 },
199 },
297 )
200 )
@@ -306,10 +209,6 @@ class OpencodeCore(
306 when {
209 when {
307 resp.code == 401 -> {
210 resp.code == 401 -> {
308 loading = false
211 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
212 // Always reveal the auth fields so the user can see/edit
314 // their credentials — even when the ones supplied were wrong.
213 // their credentials — even when the ones supplied were wrong.
315 authRequired = true
214 authRequired = true
@@ -324,14 +223,10 @@ class OpencodeCore(
324 loading = true
223 loading = true
325 emit()
224 emit()
326 startSse()
225 startSse()
327− // Route through loadSessionsJob so a prior in-flight loadSessions
328− // (e.g. from a rapid double-connect) is cancelled first.
329− loadSessionsJob?.cancel()
330− loadSessionsJob = scope.launch { loadSessions() }
226+ loadSessions()
331 }
227 }
332 else -> {
228 else -> {
333 loading = false
229 loading = false
334− connected = false
335 error = "Server returned status ${resp.code}"
230 error = "Server returned status ${resp.code}"
336 emit()
231 emit()
337 }
232 }
@@ -339,7 +234,6 @@ class OpencodeCore(
339 },
234 },
340 onFailure = { e ->
235 onFailure = { e ->
341 loading = false
236 loading = false
342− connected = false
343 error = "Connection failed: ${e.message}"
237 error = "Connection failed: ${e.message}"
344 emit()
238 emit()
345 },
239 },
@@ -352,9 +246,6 @@ class OpencodeCore(
352 if (resp.code in 200..299) {
246 if (resp.code in 200..299) {
353 sessions.clear()
247 sessions.clear()
354 sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
248 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() }
358 } else {
249 } else {
359 error = "Server returned status ${resp.code}"
250 error = "Server returned status ${resp.code}"
360 }
251 }
@@ -372,10 +263,6 @@ class OpencodeCore(
372 if (session != null) {
263 if (session != null) {
373 if (sessions.none { it.id == session.id }) {
264 if (sessions.none { it.id == session.id }) {
374 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
265 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
375− // Restore the alphabetical order immediately (matching loadSessions /
376− // SessionUpserted) so the new session doesn't sit out-of-order at the
377− // top until the SSE SessionUpserted event arrives to re-sort.
378− sessions.sortBy { it.title.lowercase() }
379 }
266 }
380 emit()
267 emit()
381 // SelectSession takes over the loading state (loads messages).
268 // SelectSession takes over the loading state (loads messages).
@@ -397,7 +284,6 @@ class OpencodeCore(
397 loading = false
284 loading = false
398 if (resp.code in 200..299) {
285 if (resp.code in 200..299) {
399 messages.clear()
286 messages.clear()
400− removedMessageIds.clear()
401 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
287 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
402 generating = messages.any { it.streaming }
288 generating = messages.any { it.streaming }
403 } else {
289 } else {
@@ -408,7 +294,6 @@ class OpencodeCore(
408 onFailure = { e ->
294 onFailure = { e ->
409 if (!isCurrent(sessionId)) { loading = false; return }
295 if (!isCurrent(sessionId)) { loading = false; return }
410 loading = false
296 loading = false
411− generating = false
412 error = "Request failed: ${e.message}"
297 error = "Request failed: ${e.message}"
413 emit()
298 emit()
414 },
299 },
@@ -437,8 +322,6 @@ class OpencodeCore(
437
322
438 private fun closeSse() {
323 private fun closeSse() {
439 sseClosedIntentionally = true
324 sseClosedIntentionally = true
440− reconnectJob?.cancel()
441− reconnectJob = null
442 sse?.close()
325 sse?.close()
443 sse = null
326 sse = null
444 }
327 }
@@ -449,10 +332,7 @@ class OpencodeCore(
449 // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
332 // stream reconnects (onStateChange(true)) so a healthy server starts fresh.
450 val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
333 val delayMs = (2000L * (1L shl reconnectAttempts)).coerceAtMost(30_000L)
451 if (delayMs < 30_000L) reconnectAttempts += 1
334 if (delayMs < 30_000L) reconnectAttempts += 1
452− // Cancel any pending reconnect so rapid network flapping can't stack multiple
453− // coroutines that each open a new SSE connection.
454− reconnectJob?.cancel()
455− reconnectJob = scope.launch {
335+ scope.launch {
456 delay(delayMs)
336 delay(delayMs)
457 if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
337 if (!sseClosedIntentionally && connected && screen != Screen.Connect) startSse()
458 }
338 }
@@ -471,9 +351,6 @@ class OpencodeCore(
471 is Protocol.Event.MessageUpdated -> {
351 is Protocol.Event.MessageUpdated -> {
472 val info = event.info
352 val info = event.info
473 if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
353 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
477 val streaming = info.time.completed == null && info.error == null
354 val streaming = info.time.completed == null && info.error == null
478 val existing = messages.firstOrNull { it.id == info.id }
355 val existing = messages.firstOrNull { it.id == info.id }
479 if (existing != null) {
356 if (existing != null) {
@@ -482,31 +359,23 @@ class OpencodeCore(
482 } else {
359 } else {
483 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
360 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
484 }
361 }
485− info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
362+ info.error?.let { error = it.message(); generating = false }
486 return true
363 return true
487 }
364 }
488
365
489 is Protocol.Event.PartUpdated -> {
366 is Protocol.Event.PartUpdated -> {
490 val part = event.part
367 val part = event.part
491 val msg = messages.firstOrNull { it.id == part.messageId } ?: return false
368 val msg = messages.firstOrNull { it.id == part.messageId } ?: return false
492− // Synthetic text parts are intentionally skipped; report no change so we
493− // don't trigger a needless re-render/emit for them.
494− return when (part) {
369+ when (part) {
495− is Protocol.Part.Text -> if (part.synthetic) {
370+ is Protocol.Part.Text -> if (!part.synthetic) {
496− false
497− } else {
498 msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
371 msg.textParts[part.id] = pickText(part.text, event.delta, msg.textParts[part.id])
499− true
500 }
372 }
501− is Protocol.Part.Reasoning -> {
373+ is Protocol.Part.Reasoning ->
502 msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
374 msg.reasoningParts[part.id] = pickText(part.text, event.delta, msg.reasoningParts[part.id])
503− true
504− }
505− is Protocol.Part.Tool -> {
375+ is Protocol.Part.Tool ->
506 msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
376 msg.toolParts[part.id] = ToolView(part.tool, part.status, part.title)
507− true
508− }
509 }
377 }
378+ return true
510 }
379 }
511
380
512 is Protocol.Event.PartRemoved -> {
381 is Protocol.Event.PartRemoved -> {
@@ -515,11 +384,7 @@ class OpencodeCore(
515 return true
384 return true
516 }
385 }
517
386
518− is Protocol.Event.MessageRemoved -> {
519− // Remember the ID so a late MessageUpdated can't resurrect the message.
520− removedMessageIds.add(event.messageId)
521− return messages.removeAll { it.id == event.messageId }
387+ is Protocol.Event.MessageRemoved -> return messages.removeAll { it.id == event.messageId }
522− }
523
388
524 is Protocol.Event.SessionIdle -> {
389 is Protocol.Event.SessionIdle -> {
525 if (!isCurrent(event.sessionId)) return false
390 if (!isCurrent(event.sessionId)) return false
@@ -545,9 +410,6 @@ class OpencodeCore(
545 } else {
410 } else {
546 sessions.add(0, SessionView(event.info.id, title))
411 sessions.add(0, SessionView(event.info.id, title))
547 }
412 }
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() }
551 if (isCurrent(event.info.id)) currentSessionTitle = title
413 if (isCurrent(event.info.id)) currentSessionTitle = title
552 return true
414 return true
553 }
415 }
app/src/main/java/soy/iko/opencode/core/SseClient.kt−1
@@ -33,7 +33,6 @@ class SseClient(
33
33
34 fun connect() {
34 fun connect() {
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36− builder.header("User-Agent", "opencode-android/1.0")
37 if (auth != null) builder.header("Authorization", auth)
36 if (auth != null) builder.header("Authorization", auth)
38 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
37 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
39 }
38 }
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+2−55
@@ -7,19 +7,13 @@ import androidx.compose.animation.slideOutHorizontally
7import androidx.compose.animation.togetherWith
7import androidx.compose.animation.togetherWith
8import androidx.compose.foundation.layout.fillMaxSize
8import androidx.compose.foundation.layout.fillMaxSize
9import androidx.compose.foundation.layout.padding
9import androidx.compose.foundation.layout.padding
10−import androidx.compose.material3.AlertDialog
11import androidx.compose.material3.Scaffold
10import androidx.compose.material3.Scaffold
12import androidx.compose.material3.SnackbarDuration
11import androidx.compose.material3.SnackbarDuration
13import androidx.compose.material3.SnackbarHost
12import androidx.compose.material3.SnackbarHost
14import androidx.compose.material3.SnackbarHostState
13import androidx.compose.material3.SnackbarHostState
15−import androidx.compose.material3.Text
16−import androidx.compose.material3.TextButton
17import androidx.compose.runtime.Composable
14import androidx.compose.runtime.Composable
18import androidx.compose.runtime.LaunchedEffect
15import androidx.compose.runtime.LaunchedEffect
19−import androidx.compose.runtime.getValue
20−import androidx.compose.runtime.mutableStateOf
21import androidx.compose.runtime.remember
16import androidx.compose.runtime.remember
22−import androidx.compose.runtime.setValue
23import androidx.compose.ui.Modifier
17import androidx.compose.ui.Modifier
24import soy.iko.opencode.core.Event
18import soy.iko.opencode.core.Event
25import soy.iko.opencode.core.Screen
19import soy.iko.opencode.core.Screen
@@ -31,8 +25,6 @@ import soy.iko.opencode.ui.screens.SessionsScreen
31@Composable
25@Composable
32fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
26fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
33 val snackbar = remember { SnackbarHostState() }
27 val snackbar = remember { SnackbarHostState() }
34− var showStopConfirm by remember { mutableStateOf(false) }
35− var showDisconnectConfirm by remember { mutableStateOf(false) }
36
28
37 LaunchedEffect(state.error) {
29 LaunchedEffect(state.error) {
38 state.error?.let {
30 state.error?.let {
@@ -48,57 +40,12 @@ fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
48
40
49 BackHandler(enabled = state.screen != Screen.Connect) {
41 BackHandler(enabled = state.screen != Screen.Connect) {
50 when (state.screen) {
42 when (state.screen) {
51− // Leaving mid-generation would silently drop the reply, so confirm first.
52− Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
43+ Screen.Chat -> dispatch(Event.NavigateToSessions)
53− // Disconnecting drops the server session, so guard the back button.
44+ Screen.Sessions -> dispatch(Event.NavigateToConnect)
54− Screen.Sessions -> showDisconnectConfirm = true
55 Screen.Connect -> Unit
45 Screen.Connect -> Unit
56 }
46 }
57 }
47 }
58
48
59− if (showStopConfirm) {
60− AlertDialog(
61− onDismissRequest = { showStopConfirm = false },
62− title = { Text("Stop generation?") },
63− text = { Text("Leaving will stop the current generation.") },
64− confirmButton = {
65− TextButton(onClick = {
66− showStopConfirm = false
67− dispatch(Event.CancelGeneration)
68− dispatch(Event.NavigateToSessions)
69− }) {
70− Text("Stop and leave")
71− }
72− },
73− dismissButton = {
74− TextButton(onClick = { showStopConfirm = false }) {
75− Text("Stay")
76− }
77− },
78− )
79− }
80−
81− if (showDisconnectConfirm) {
82− AlertDialog(
83− onDismissRequest = { showDisconnectConfirm = false },
84− title = { Text("Disconnect?") },
85− text = { Text("You will be disconnected from the server.") },
86− confirmButton = {
87− TextButton(onClick = {
88− showDisconnectConfirm = false
89− dispatch(Event.NavigateToConnect)
90− }) {
91− Text("Disconnect")
92− }
93− },
94− dismissButton = {
95− TextButton(onClick = { showDisconnectConfirm = false }) {
96− Text("Cancel")
97− }
98− },
99− )
100− }
101−
102 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
49 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
103 AnimatedContent(
50 AnimatedContent(
104 targetState = state.screen,
51 targetState = state.screen,
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+21−281
@@ -3,8 +3,6 @@ package soy.iko.opencode.ui.components
3import android.content.ClipData
3import android.content.ClipData
4import android.content.ClipboardManager
4import android.content.ClipboardManager
5import android.content.Context
5import android.content.Context
6−import android.content.Intent
7−import android.net.Uri
8import android.widget.Toast
6import android.widget.Toast
9import androidx.compose.foundation.ExperimentalFoundationApi
7import androidx.compose.foundation.ExperimentalFoundationApi
10import androidx.compose.foundation.background
8import androidx.compose.foundation.background
@@ -15,20 +13,14 @@ import androidx.compose.foundation.layout.Column
15import androidx.compose.foundation.layout.Row
13import androidx.compose.foundation.layout.Row
16import androidx.compose.foundation.layout.fillMaxWidth
14import androidx.compose.foundation.layout.fillMaxWidth
17import androidx.compose.foundation.layout.padding
15import androidx.compose.foundation.layout.padding
18−import androidx.compose.foundation.layout.size
19import androidx.compose.foundation.layout.widthIn
16import androidx.compose.foundation.layout.widthIn
20import androidx.compose.foundation.shape.RoundedCornerShape
17import androidx.compose.foundation.shape.RoundedCornerShape
21−import androidx.compose.foundation.text.selection.SelectionContainer
22import androidx.compose.material.icons.Icons
18import androidx.compose.material.icons.Icons
23import androidx.compose.material.icons.filled.Build
19import androidx.compose.material.icons.filled.Build
24−import androidx.compose.material.icons.filled.Check
25import androidx.compose.material.icons.filled.ErrorOutline
20import androidx.compose.material.icons.filled.ErrorOutline
26import androidx.compose.material.icons.filled.ExpandLess
21import androidx.compose.material.icons.filled.ExpandLess
27import androidx.compose.material.icons.filled.ExpandMore
22import androidx.compose.material.icons.filled.ExpandMore
28import androidx.compose.material.icons.filled.Schedule
23import 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
32import androidx.compose.material3.Icon
24import androidx.compose.material3.Icon
33import androidx.compose.material3.MaterialTheme
25import androidx.compose.material3.MaterialTheme
34import androidx.compose.material3.Text
26import androidx.compose.material3.Text
@@ -42,20 +34,9 @@ import androidx.compose.ui.Modifier
42import androidx.compose.ui.draw.clip
34import androidx.compose.ui.draw.clip
43import androidx.compose.ui.graphics.Color
35import androidx.compose.ui.graphics.Color
44import androidx.compose.ui.platform.LocalContext
36import 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
51import androidx.compose.ui.text.font.FontStyle
37import 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
56import androidx.compose.ui.text.style.TextOverflow
38import androidx.compose.ui.text.style.TextOverflow
57import androidx.compose.ui.unit.dp
39import androidx.compose.ui.unit.dp
58−import androidx.compose.ui.unit.sp
59import soy.iko.opencode.core.MessageStatus
40import soy.iko.opencode.core.MessageStatus
60import soy.iko.opencode.core.MessageView
41import soy.iko.opencode.core.MessageView
61import soy.iko.opencode.core.ToolView
42import soy.iko.opencode.core.ToolView
@@ -65,7 +46,7 @@ private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
65
46
66@OptIn(ExperimentalFoundationApi::class)
47@OptIn(ExperimentalFoundationApi::class)
67@Composable
48@Composable
68−fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
49+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
69 val isUser = message.isUser
50 val isUser = message.isUser
70 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
51 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
71 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
52 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
@@ -78,20 +59,11 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
78 )
59 )
79
60
80 val context = LocalContext.current
61 val context = LocalContext.current
81− var showMenu by remember { mutableStateOf(false) }
82
62
83 Row(
63 Row(
84− modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
64+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
85 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
65 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
86 ) {
66 ) {
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− }
95 Column(
67 Column(
96 modifier = Modifier
68 modifier = Modifier
97 .fillMaxWidth(0.85f)
69 .fillMaxWidth(0.85f)
@@ -102,67 +74,25 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
102 onClick = {},
74 onClick = {},
103 onLongClick = {
75 onLongClick = {
104 if (message.text.isNotEmpty()) {
76 if (message.text.isNotEmpty()) {
105− showMenu = true
77+ copyToClipboard(context, message.text)
78+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
106 }
79 }
107 },
80 },
108 )
81 )
109 .padding(horizontal = 14.dp, vertical = 10.dp),
82 .padding(horizontal = 14.dp, vertical = 10.dp),
110 ) {
83 ) {
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−
129 message.reasoning?.let { ReasoningBlock(it, context) }
84 message.reasoning?.let { ReasoningBlock(it, context) }
130
85
131− // Give a quick overview of how many tools ran before listing them.
132− if (message.tools.size > 1) {
133− Text(
134− text = "${message.tools.size} tool calls",
135− style = MaterialTheme.typography.labelSmall,
136− color = MaterialTheme.colorScheme.onSurfaceVariant,
137− modifier = Modifier.padding(bottom = 4.dp),
138− )
139− }
140−
141 message.tools.forEach { ToolRow(it) }
86 message.tools.forEach { ToolRow(it) }
142
87
143− SelectionContainer {
144− if (message.text.isNotEmpty()) {
88+ if (message.text.isNotEmpty()) {
145− val linkColor = MaterialTheme.colorScheme.primary
89+ Text(
146− // Tint the code background off the bubble's own foreground colour so it
90+ text = message.text + if (message.streaming) " ▌" else "",
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,
91+ 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
92+ style = MaterialTheme.typography.bodyLarge,
159− } else {
160− MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp)
161− },
162− )
93+ )
163− } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
94+ } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
164− Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
95+ Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
165− }
166 }
96 }
167
97
168 if (message.time > 0) {
98 if (message.time > 0) {
@@ -175,7 +105,7 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry:
175 }
105 }
176
106
177 if (isUser && message.status != MessageStatus.Sent) {
107 if (isUser && message.status != MessageStatus.Sent) {
178− StatusLine(message.status, onRetry = onRetry)
108+ StatusLine(message.status)
179 }
109 }
180 }
110 }
181 }
111 }
@@ -186,170 +116,6 @@ private fun copyToClipboard(context: Context, text: String) {
186 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
116 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
187}
117}
188
118
189−private val urlRegex = Regex("""https?://[^\s]+""")
190−
191−/**
192− * Render [text] as an AnnotatedString. Triple-backtick fences split the text into
193− * prose and code segments: code segments are rendered monospace on a tinted
194− * [codeBackground] (fences dropped), while prose has each http(s) URL turned into a
195− * clickable link. The streaming cursor (" ▌") is appended outside any annotation.
196− */
197−private fun buildLinkedText(
198− text: String,
199− streaming: Boolean,
200− linkColor: Color,
201− codeBackground: Color,
202− context: Context,
203−): AnnotatedString = buildAnnotatedString {
204− // Odd-indexed segments sit between a pair of ``` fences, so they're code. An
205− // unclosed fence leaves the trailing segment styled as code, mirroring markdown.
206− val segments = text.split("```")
207− segments.forEachIndexed { index, segment ->
208− if (index % 2 == 1) {
209− withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
210− append(segment)
211− }
212− } else {
213− appendLinkedText(segment, linkColor, codeBackground, context)
214− }
215− }
216− if (streaming) append(" ▌")
217−}
218−
219−/**
220− * Append [text] to the builder. Double-asterisk pairs are rendered bold; within each
221− * segment, single-backtick pairs are rendered as inline code (monospace, backticks
222− * dropped), and the remaining prose has each http(s) URL turned into a clickable link.
223− * Triple-backtick fences are already stripped upstream in [buildLinkedText], so only
224− * inline spans reach here.
225− */
226−private fun AnnotatedString.Builder.appendLinkedText(
227− text: String,
228− linkColor: Color,
229− codeBackground: Color,
230− context: Context,
231−) {
232− // Bold is the outermost inline layer: split on ** first so a bold span can wrap
233− // inline code and links inside it. Odd-indexed segments sit between a pair of **
234− // markers, so they're bold (markers dropped); even segments are ordinary prose.
235− // Only the non-bold (even) segments get single-* italic handling — splitting a bold
236− // segment on "*" would misfire on the leftover asterisks from the ** markers.
237− val segments = text.split("**")
238− // An even segment count means an odd number of ** markers, so the final ** is unclosed:
239− // its trailing segment isn't bold. Restore the literal ** and render it as ordinary prose.
240− val unclosed = segments.size % 2 == 0
241− segments.forEachIndexed { index, segment ->
242− val isUnclosedTail = unclosed && index == segments.size - 1
243− if (index % 2 == 1 && !isUnclosedTail) {
244− withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
245− appendInlineCode(segment, linkColor, codeBackground, context)
246− }
247− } else {
248− if (isUnclosedTail) append("**")
249− appendItalicText(segment, linkColor, codeBackground, context)
250− }
251− }
252−}
253−
254−/**
255− * Append [text] to the builder, rendering single-asterisk pairs as italic. Double
256− * asterisks are already consumed as bold upstream in [appendLinkedText], so only lone
257− * `*` markers reach here. Each segment then flows through inline-code and URL handling.
258− */
259−private fun AnnotatedString.Builder.appendItalicText(
260− text: String,
261− linkColor: Color,
262− codeBackground: Color,
263− context: Context,
264−) {
265− // Odd-indexed segments sit between a pair of single asterisks, so they're italic
266− // (markers dropped); even segments are ordinary prose.
267− val segments = text.split("*")
268− // An even segment count means an odd number of * markers, so the final * is unclosed:
269− // its trailing segment isn't italic. Restore the literal * and render it as prose.
270− val unclosed = segments.size % 2 == 0
271− segments.forEachIndexed { index, segment ->
272− val isUnclosedTail = unclosed && index == segments.size - 1
273− if (index % 2 == 1 && !isUnclosedTail) {
274− withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
275− appendInlineCode(segment, linkColor, codeBackground, context)
276− }
277− } else {
278− if (isUnclosedTail) append("*")
279− appendInlineCode(segment, linkColor, codeBackground, context)
280− }
281− }
282−}
283−
284−/**
285− * Append [text] to the builder, rendering single-backtick pairs as inline code
286− * (monospace, backticks dropped) and turning each http(s) URL in the remaining prose
287− * into a clickable link.
288− */
289−private fun AnnotatedString.Builder.appendInlineCode(
290− text: String,
291− linkColor: Color,
292− codeBackground: Color,
293− context: Context,
294−) {
295− // Odd-indexed segments sit between a pair of single backticks, so they're inline
296− // code. Even segments are ordinary prose and get URL linking applied.
297− val segments = text.split("`")
298− // An even segment count means an odd number of backtick markers, so the final backtick
299− // is unclosed: its trailing segment isn't code. Restore the literal ` and treat as prose.
300− val unclosed = segments.size % 2 == 0
301− segments.forEachIndexed { index, segment ->
302− val isUnclosedTail = unclosed && index == segments.size - 1
303− if (index % 2 == 1 && !isUnclosedTail) {
304− withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
305− append(segment)
306− }
307− } else {
308− if (isUnclosedTail) append("`")
309− appendUrls(segment, linkColor, context)
310− }
311− }
312−}
313−
314−/** Append [text] to the builder, turning each http(s) URL into a clickable link. */
315−private fun AnnotatedString.Builder.appendUrls(
316− text: String,
317− linkColor: Color,
318− context: Context,
319−) {
320− val matches = urlRegex.findAll(text).toList()
321− var cursor = 0
322− for (match in matches) {
323− append(text.substring(cursor, match.range.first))
324− val url = match.value
325− withLink(
326− LinkAnnotation.Clickable(
327− tag = url,
328− styles = TextLinkStyles(
329− SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline),
330− ),
331− linkInteractionListener = {
332− runCatching {
333− context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
334− }
335− },
336− ),
337− ) {
338− append(url)
339− }
340− cursor = match.range.last + 1
341− }
342− append(text.substring(cursor))
343−}
344−
345−private fun shareText(context: Context, text: String) {
346− val intent = Intent(Intent.ACTION_SEND).apply {
347− type = "text/plain"
348− putExtra(Intent.EXTRA_TEXT, text)
349− }
350− context.startActivity(Intent.createChooser(intent, null))
351−}
352−
353@Composable
119@Composable
354private fun ReasoningBlock(text: String, context: Context) {
120private fun ReasoningBlock(text: String, context: Context) {
355 var expanded by remember { mutableStateOf(false) }
121 var expanded by remember { mutableStateOf(false) }
@@ -395,13 +161,6 @@ private fun ReasoningBlock(text: String, context: Context) {
395@Composable
161@Composable
396private fun ToolRow(tool: ToolView) {
162private fun ToolRow(tool: ToolView) {
397 var expanded by remember { mutableStateOf(false) }
163 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− }
405 Row(
164 Row(
406 verticalAlignment = Alignment.CenterVertically,
165 verticalAlignment = Alignment.CenterVertically,
407 modifier = Modifier
166 modifier = Modifier
@@ -416,23 +175,14 @@ private fun ToolRow(tool: ToolView) {
416 modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
175 modifier = Modifier.padding(end = 6.dp).widthIn(max = 16.dp),
417 )
176 )
418 Text(
177 Text(
419− text = buildAnnotatedString {
178+ text = buildString {
420− withStyle(SpanStyle(color = baseColor)) {
421− append(tool.name)
179+ append(tool.name)
422− append(" · ")
180+ append(" · ")
423− }
424− withStyle(SpanStyle(color = statusColor)) {
425− append(tool.status)
181+ append(tool.status)
426− }
427− if (expanded) tool.title?.let {
182+ if (expanded) tool.title?.let { append(" — "); append(it) }
428− withStyle(SpanStyle(color = baseColor)) {
429− append(" — ")
430− append(it)
431− }
432− }
433 },
183 },
434 style = MonoStyle,
184 style = MonoStyle,
435− color = baseColor,
185+ color = MaterialTheme.colorScheme.onSurfaceVariant,
436 maxLines = if (expanded) Int.MAX_VALUE else 1,
186 maxLines = if (expanded) Int.MAX_VALUE else 1,
437 overflow = TextOverflow.Ellipsis,
187 overflow = TextOverflow.Ellipsis,
438 modifier = Modifier.weight(1f),
188 modifier = Modifier.weight(1f),
@@ -447,11 +197,11 @@ private fun ToolRow(tool: ToolView) {
447}
197}
448
198
449@Composable
199@Composable
450−private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
200+private fun StatusLine(status: MessageStatus) {
451 val (icon, label, tint) = when (status) {
201 val (icon, label, tint) = when (status) {
452 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
202 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
453 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
203 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
454− MessageStatus.Sent -> Triple(Icons.Filled.Check, "", Color.Unspecified)
204+ MessageStatus.Sent -> Triple(Icons.Filled.Schedule, "", Color.Unspecified)
455 }
205 }
456 Row(
206 Row(
457 verticalAlignment = Alignment.CenterVertically,
207 verticalAlignment = Alignment.CenterVertically,
@@ -465,15 +215,5 @@ private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
465 color = tint,
215 color = tint,
466 modifier = Modifier.padding(start = 4.dp),
216 modifier = Modifier.padding(start = 4.dp),
467 )
217 )
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− }
478 }
218 }
479}
219}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+19−321
@@ -1,57 +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
7import androidx.compose.animation.AnimatedVisibility
3import 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
13import androidx.compose.animation.fadeIn
4import androidx.compose.animation.fadeIn
14import androidx.compose.animation.fadeOut
5import androidx.compose.animation.fadeOut
15import androidx.compose.animation.scaleIn
6import androidx.compose.animation.scaleIn
16import androidx.compose.animation.scaleOut
7import androidx.compose.animation.scaleOut
17−import androidx.compose.foundation.ExperimentalFoundationApi
18import androidx.compose.foundation.background
8import androidx.compose.foundation.background
19import androidx.compose.foundation.clickable
9import androidx.compose.foundation.clickable
20−import androidx.compose.foundation.combinedClickable
21import androidx.compose.foundation.layout.Arrangement
10import androidx.compose.foundation.layout.Arrangement
22import androidx.compose.foundation.layout.Box
11import androidx.compose.foundation.layout.Box
23import androidx.compose.foundation.layout.BoxScope
12import androidx.compose.foundation.layout.BoxScope
24import androidx.compose.foundation.layout.Column
13import androidx.compose.foundation.layout.Column
25import androidx.compose.foundation.layout.Row
14import androidx.compose.foundation.layout.Row
26−import androidx.compose.foundation.layout.Spacer
27import androidx.compose.foundation.layout.fillMaxSize
15import androidx.compose.foundation.layout.fillMaxSize
28import androidx.compose.foundation.layout.fillMaxWidth
16import androidx.compose.foundation.layout.fillMaxWidth
29−import androidx.compose.foundation.layout.heightIn
30import androidx.compose.foundation.layout.PaddingValues
17import androidx.compose.foundation.layout.PaddingValues
31−import androidx.compose.foundation.layout.WindowInsets
32−import androidx.compose.foundation.layout.ime
33import androidx.compose.foundation.layout.imePadding
18import androidx.compose.foundation.layout.imePadding
34import androidx.compose.foundation.layout.padding
19import androidx.compose.foundation.layout.padding
35import androidx.compose.foundation.layout.size
20import androidx.compose.foundation.layout.size
36import androidx.compose.foundation.lazy.LazyColumn
21import androidx.compose.foundation.lazy.LazyColumn
37−import androidx.compose.foundation.lazy.itemsIndexed
22+import androidx.compose.foundation.lazy.items
38import androidx.compose.foundation.lazy.rememberLazyListState
23import androidx.compose.foundation.lazy.rememberLazyListState
39import androidx.compose.foundation.shape.CircleShape
24import androidx.compose.foundation.shape.CircleShape
40−import androidx.compose.foundation.shape.RoundedCornerShape
41import androidx.compose.foundation.text.KeyboardActions
25import androidx.compose.foundation.text.KeyboardActions
42import androidx.compose.foundation.text.KeyboardOptions
26import androidx.compose.foundation.text.KeyboardOptions
43import androidx.compose.material.icons.Icons
27import androidx.compose.material.icons.Icons
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
28import androidx.compose.material.icons.automirrored.filled.ArrowBack
45import androidx.compose.material.icons.automirrored.filled.Send
29import androidx.compose.material.icons.automirrored.filled.Send
46−import androidx.compose.material.icons.filled.ChatBubbleOutline
47−import androidx.compose.material.icons.filled.Close
48import androidx.compose.material.icons.filled.KeyboardArrowDown
30import androidx.compose.material.icons.filled.KeyboardArrowDown
49−import androidx.compose.material.icons.filled.KeyboardArrowUp
50import androidx.compose.material.icons.filled.Stop
31import androidx.compose.material.icons.filled.Stop
51import androidx.compose.material3.CircularProgressIndicator
32import androidx.compose.material3.CircularProgressIndicator
52import androidx.compose.material3.ExperimentalMaterial3Api
33import androidx.compose.material3.ExperimentalMaterial3Api
53import androidx.compose.material3.FilledIconButton
34import androidx.compose.material3.FilledIconButton
54−import androidx.compose.material3.FilledTonalButton
55import androidx.compose.material3.FloatingActionButton
35import androidx.compose.material3.FloatingActionButton
56import androidx.compose.material3.Icon
36import androidx.compose.material3.Icon
57import androidx.compose.material3.IconButton
37import androidx.compose.material3.IconButton
@@ -61,7 +41,6 @@ import androidx.compose.material3.OutlinedTextField
61import androidx.compose.material3.Scaffold
41import androidx.compose.material3.Scaffold
62import androidx.compose.material3.Surface
42import androidx.compose.material3.Surface
63import androidx.compose.material3.Text
43import androidx.compose.material3.Text
64−import androidx.compose.material3.TextButton
65import androidx.compose.material3.TopAppBar
44import androidx.compose.material3.TopAppBar
66import androidx.compose.runtime.Composable
45import androidx.compose.runtime.Composable
67import androidx.compose.runtime.LaunchedEffect
46import androidx.compose.runtime.LaunchedEffect
@@ -75,13 +54,8 @@ import androidx.compose.ui.Alignment
75import androidx.compose.ui.Modifier
54import androidx.compose.ui.Modifier
76import androidx.compose.ui.draw.clip
55import androidx.compose.ui.draw.clip
77import androidx.compose.ui.hapticfeedback.HapticFeedbackType
56import 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
81import androidx.compose.ui.platform.LocalHapticFeedback
57import androidx.compose.ui.platform.LocalHapticFeedback
82−import androidx.compose.ui.text.font.FontStyle
83import androidx.compose.ui.text.input.ImeAction
58import androidx.compose.ui.text.input.ImeAction
84−import androidx.compose.ui.text.style.TextAlign
85import androidx.compose.ui.text.style.TextOverflow
59import androidx.compose.ui.text.style.TextOverflow
86import androidx.compose.ui.unit.dp
60import androidx.compose.ui.unit.dp
87import kotlinx.coroutines.launch
61import kotlinx.coroutines.launch
@@ -89,17 +63,11 @@ import soy.iko.opencode.core.Event
89import soy.iko.opencode.core.UiState
63import soy.iko.opencode.core.UiState
90import soy.iko.opencode.ui.components.MessageBubble
64import soy.iko.opencode.ui.components.MessageBubble
91
65
92−@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
66+@OptIn(ExperimentalMaterial3Api::class)
93@Composable
67@Composable
94fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
68fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
95 val listState = rememberLazyListState()
69 val listState = rememberLazyListState()
96 val coroutineScope = rememberCoroutineScope()
70 val coroutineScope = rememberCoroutineScope()
97− val context = LocalContext.current
98−
99− // Hide the jump-to-bottom FAB while the keyboard is up: it would otherwise
100− // sit over the top of the IME. Reading the ime inset bottom during composition
101− // observes snapshot state, so this flips as the keyboard opens/closes.
102− val isImeVisible = WindowInsets.ime.getBottom(LocalDensity.current) > 0
103
71
104 // Show a jump-to-bottom button once the user scrolls up away from the latest
72 // 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 —
73 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -113,12 +81,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
113 }
81 }
114 }
82 }
115
83
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
84 // 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.
85 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
124 var lastSeenCount by remember { mutableStateOf(0) }
86 var lastSeenCount by remember { mutableStateOf(0) }
@@ -148,20 +110,11 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
148 topBar = {
110 topBar = {
149 TopAppBar(
111 TopAppBar(
150 title = {
112 title = {
151− val title = state.currentSessionTitle.ifEmpty { "Chat" }
152 Text(
113 Text(
153− text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
114+ text = state.currentSessionTitle.ifEmpty { "Chat" },
154 maxLines = 1,
115 maxLines = 1,
155 overflow = TextOverflow.Ellipsis,
116 overflow = TextOverflow.Ellipsis,
156− modifier = Modifier.combinedClickable(
157− onClick = { dispatch(Event.NavigateToSessions) },
117+ modifier = Modifier.clickable { 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− ),
165 )
118 )
166 },
119 },
167 navigationIcon = {
120 navigationIcon = {
@@ -183,7 +136,6 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
183 ChatInputBar(
136 ChatInputBar(
184 draft = state.draft,
137 draft = state.draft,
185 generating = state.generating,
138 generating = state.generating,
186− loading = state.loading && state.messages.isEmpty(),
187 onDraftChange = { dispatch(Event.DraftChanged(it)) },
139 onDraftChange = { dispatch(Event.DraftChanged(it)) },
188 onSend = { dispatch(Event.SendMessage(state.draft)) },
140 onSend = { dispatch(Event.SendMessage(state.draft)) },
189 onStop = { dispatch(Event.CancelGeneration) },
141 onStop = { dispatch(Event.CancelGeneration) },
@@ -197,86 +149,35 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
197 if (state.loading && state.messages.isEmpty()) {
149 if (state.loading && state.messages.isEmpty()) {
198 LinearProgressIndicator(Modifier.fillMaxWidth())
150 LinearProgressIndicator(Modifier.fillMaxWidth())
199 }
151 }
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)) {
152 Box(Modifier.fillMaxWidth().weight(1f)) {
207 if (state.messages.isEmpty() && !state.loading) {
153 if (state.messages.isEmpty() && !state.loading) {
208− Column(
154+ Text(
155+ text = "Send a message to start the conversation.",
156+ style = MaterialTheme.typography.bodyMedium,
157+ color = MaterialTheme.colorScheme.onSurfaceVariant,
209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
158 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210− horizontalAlignment = Alignment.CenterHorizontally,
211− ) {
159+ )
212− Icon(
213− Icons.Filled.ChatBubbleOutline,
214− contentDescription = null,
215− modifier = Modifier.size(48.dp),
216− tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
217− )
218− Spacer(Modifier.size(16.dp))
219− Text(
220− text = "Send a message to start the conversation.",
221− style = MaterialTheme.typography.bodyMedium,
222− color = MaterialTheme.colorScheme.onSurfaceVariant,
223− textAlign = TextAlign.Center,
224− )
225− }
226 }
160 }
227 LazyColumn(
161 LazyColumn(
228 state = listState,
162 state = listState,
229 modifier = Modifier.fillMaxSize(),
163 modifier = Modifier.fillMaxSize(),
230 contentPadding = PaddingValues(vertical = 8.dp),
164 contentPadding = PaddingValues(vertical = 8.dp),
231 ) {
165 ) {
232− itemsIndexed(state.messages, key = { _, message -> message.id }) { index, message ->
166+ items(state.messages, key = { it.id }) { 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(
167+ MessageBubble(message)
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 }
168 }
254 }
169 }
255 ScrollToBottomButton(
170 ScrollToBottomButton(
256− visible = showScrollButton && !isImeVisible,
171+ visible = showScrollButton,
257 showBadge = hasUnseenMessages,
172 showBadge = hasUnseenMessages,
258 onClick = {
173 onClick = {
259 coroutineScope.launch {
174 coroutineScope.launch {
260 if (state.messages.isNotEmpty()) {
175 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
176+ listState.animateScrollToItem(state.messages.size - 1)
267− listState.animateScrollToItem(target)
268 }
177 }
269 }
178 }
270 },
179 },
271 )
180 )
272− ScrollToTopButton(
273− visible = showScrollTop,
274− onClick = {
275− coroutineScope.launch {
276− listState.animateScrollToItem(0)
277− }
278− },
279− )
280 }
181 }
281 }
182 }
282 }
183 }
@@ -316,123 +217,6 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
316 }
217 }
317}
218}
318
219
319−// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
320−// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
321−@Composable
322−private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
323− AnimatedVisibility(
324− visible = visible,
325− modifier = Modifier.align(Alignment.TopStart),
326− enter = scaleIn() + fadeIn(),
327− exit = scaleOut() + fadeOut(),
328− ) {
329− Box(Modifier.padding(16.dp)) {
330− FloatingActionButton(
331− onClick = onClick,
332− modifier = Modifier.size(44.dp),
333− ) {
334− Icon(
335− Icons.Filled.KeyboardArrowUp,
336− contentDescription = "Scroll to top",
337− )
338− }
339− }
340− }
341−}
342−
343−private fun copyToClipboard(context: Context, text: String) {
344− val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
345− clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
346−}
347−
348−private val dateSeparatorFormat = java.time.format.DateTimeFormatter.ofPattern("MMM d")
349−
350−/** Convert an epoch-millis timestamp to the local calendar day it falls on. */
351−private fun localDayOf(epochMillis: Long): java.time.LocalDate =
352− java.time.Instant.ofEpochMilli(epochMillis)
353− .atZone(java.time.ZoneId.systemDefault())
354− .toLocalDate()
355−
356−/**
357− * A separator is shown above a message when it starts a new calendar day — i.e. the
358− * first timestamped message, or one whose day differs from the previous message's.
359− * Messages without a valid time (time <= 0) never get one.
360− */
361−private fun shouldShowDateSeparator(previous: soy.iko.opencode.core.MessageView?, current: soy.iko.opencode.core.MessageView): Boolean {
362− if (current.time <= 0) return false
363− if (previous == null || previous.time <= 0) return true
364− return localDayOf(previous.time) != localDayOf(current.time)
365−}
366−
367−/** Human-friendly day label: "Today", "Yesterday", or "MMM d" (e.g. "Jul 8"). */
368−private fun dateSeparatorLabel(day: java.time.LocalDate): String {
369− val today = java.time.LocalDate.now()
370− return when (day) {
371− today -> "Today"
372− today.minusDays(1) -> "Yesterday"
373− else -> day.format(dateSeparatorFormat)
374− }
375−}
376−
377−@Composable
378−private fun DateSeparator(epochMillis: Long) {
379− Text(
380− text = dateSeparatorLabel(localDayOf(epochMillis)),
381− style = MaterialTheme.typography.labelSmall,
382− color = MaterialTheme.colorScheme.onSurfaceVariant,
383− textAlign = TextAlign.Center,
384− modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
385− )
386−}
387−
388−// Assistant-style bubble with three sequentially-pulsing dots, shown as a stand-in
389−// until the real streaming reply starts. Mirrors MessageBubble's left-aligned,
390−// surfaceVariant look so it reads as an incoming message.
391−@Composable
392−private fun TypingIndicator() {
393− val shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp, bottomStart = 4.dp, bottomEnd = 16.dp)
394− val transition = rememberInfiniteTransition(label = "typing")
395− Row(
396− modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
397− horizontalArrangement = Arrangement.Start,
398− ) {
399− Row(
400− modifier = Modifier
401− .clip(shape)
402− .background(MaterialTheme.colorScheme.surfaceVariant)
403− .padding(horizontal = 14.dp, vertical = 12.dp),
404− verticalAlignment = Alignment.CenterVertically,
405− horizontalArrangement = Arrangement.spacedBy(6.dp),
406− ) {
407− Text(
408− text = "Thinking",
409− style = MaterialTheme.typography.bodyMedium.copy(fontStyle = FontStyle.Italic),
410− color = MaterialTheme.colorScheme.onSurfaceVariant,
411− )
412− Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
413− // Stagger the three dots so they fade in and out in sequence.
414− listOf(0, 150, 300).forEach { staggerMs ->
415− val alpha by transition.animateFloat(
416− initialValue = 0.2f,
417− targetValue = 1f,
418− animationSpec = infiniteRepeatable(
419− animation = tween(durationMillis = 600, delayMillis = staggerMs),
420− repeatMode = RepeatMode.Reverse,
421− ),
422− label = "dot",
423− )
424− Box(
425− modifier = Modifier
426− .size(6.dp)
427− .clip(CircleShape)
428− .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)),
429− )
430− }
431− }
432− }
433− }
434−}
435−
436@Composable
220@Composable
437private fun ReconnectingBanner() {
221private fun ReconnectingBanner() {
438 Surface(
222 Surface(
@@ -458,109 +242,35 @@ private fun ReconnectingBanner() {
458 }
242 }
459}
243}
460
244
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−
490@Composable
245@Composable
491private fun ChatInputBar(
246private fun ChatInputBar(
492 draft: String,
247 draft: String,
493 generating: Boolean,
248 generating: Boolean,
494− loading: Boolean,
495 onDraftChange: (String) -> Unit,
249 onDraftChange: (String) -> Unit,
496 onSend: () -> Unit,
250 onSend: () -> Unit,
497 onStop: () -> Unit,
251 onStop: () -> Unit,
498) {
252) {
499 val haptic = LocalHapticFeedback.current
253 val haptic = LocalHapticFeedback.current
500− val clipboardManager = LocalClipboardManager.current
501 Surface(tonalElevation = 3.dp) {
254 Surface(tonalElevation = 3.dp) {
502− Column(
503− modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504− ) {
505 Row(
255 Row(
506− modifier = Modifier.fillMaxWidth(),
256+ modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
507 verticalAlignment = Alignment.Bottom,
257 verticalAlignment = Alignment.Bottom,
508 horizontalArrangement = Arrangement.spacedBy(8.dp),
258 horizontalArrangement = Arrangement.spacedBy(8.dp),
509 ) {
259 ) {
510 OutlinedTextField(
260 OutlinedTextField(
511 value = draft,
261 value = draft,
512 onValueChange = onDraftChange,
262 onValueChange = onDraftChange,
513− modifier = Modifier.weight(1f).heightIn(min = 48.dp),
263+ modifier = Modifier.weight(1f),
514− enabled = !loading,
515 placeholder = { Text("Message opencode…") },
264 placeholder = { Text("Message opencode…") },
516 maxLines = 5,
265 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),
266 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
551 keyboardActions = KeyboardActions(onSend = {
267 keyboardActions = KeyboardActions(onSend = {
552− if (!generating && !loading && draft.isNotBlank()) onSend()
268+ if (!generating && draft.isNotBlank()) onSend()
553 }),
269 }),
554 )
270 )
555 if (generating) {
271 if (generating) {
556− FilledTonalButton(onClick = onStop) {
272+ FilledIconButton(onClick = onStop) {
557− Icon(
558− Icons.Filled.Stop,
559− contentDescription = null,
273+ Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
560− modifier = Modifier.size(18.dp),
561− )
562− Spacer(Modifier.size(6.dp))
563− Text("Stop")
564 }
274 }
565 } else {
275 } else {
566 FilledIconButton(
276 FilledIconButton(
@@ -568,23 +278,11 @@ private fun ChatInputBar(
568 haptic.performHapticFeedback(HapticFeedbackType.LongPress)
278 haptic.performHapticFeedback(HapticFeedbackType.LongPress)
569 onSend()
279 onSend()
570 },
280 },
571− enabled = draft.isNotBlank() && !loading,
281+ enabled = draft.isNotBlank(),
572 ) {
282 ) {
573 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
283 Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send")
574 }
284 }
575 }
285 }
576 }
286 }
577− // With nothing typed yet, offer a one-tap way to drop in clipboard contents.
578− if (draft.isEmpty() && !generating && !loading) {
579− TextButton(
580− onClick = {
581− clipboardManager.getText()?.text?.let { onDraftChange(it) }
582− },
583− contentPadding = PaddingValues(0.dp),
584− ) {
585− Text("Paste")
586− }
587− }
588− }
589 }
287 }
590}
288}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+2−49
@@ -101,30 +101,6 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
101 enabled = !state.loading,
101 enabled = !state.loading,
102 )
102 )
103
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−
128 if (state.authRequired) {
104 if (state.authRequired) {
129 Spacer(Modifier.height(12.dp))
105 Spacer(Modifier.height(12.dp))
130 OutlinedTextField(
106 OutlinedTextField(
@@ -155,15 +131,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
155 },
131 },
156 modifier = Modifier.fillMaxWidth(),
132 modifier = Modifier.fillMaxWidth(),
157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
133 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
158− keyboardActions = KeyboardActions(onGo = {
134+ keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
159− // Mirror the connect button's enabled condition so the keyboard's
160− // Go action can't fire a request the form isn't ready for.
161− if (!state.loading && state.serverUrl.isNotBlank() &&
162− (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank())
163− ) {
164− dispatch(Event.Connect)
165− }
166− }),
167 enabled = !state.loading,
135 enabled = !state.loading,
168 )
136 )
169 Spacer(Modifier.height(4.dp))
137 Spacer(Modifier.height(4.dp))
@@ -178,10 +146,7 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
178
146
179 Button(
147 Button(
180 onClick = { dispatch(Event.Connect) },
148 onClick = { dispatch(Event.Connect) },
181− // When auth is required, keep the button disabled until at least one
182− // credential is entered — otherwise it just triggers a validation error.
183− enabled = !state.loading && state.serverUrl.isNotBlank() &&
149+ enabled = !state.loading && state.serverUrl.isNotBlank(),
184− (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
185 modifier = Modifier.fillMaxWidth(),
150 modifier = Modifier.fillMaxWidth(),
186 ) {
151 ) {
187 if (state.loading) {
152 if (state.loading) {
@@ -195,18 +160,6 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
195 }
160 }
196 }
161 }
197
162
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
163 // Surface the error inline as well, so it stays visible while the user
211 // corrects the form (the snackbar is transient).
164 // corrects the form (the snackbar is transient).
212 if (state.error != null && !state.loading) {
165 if (state.error != null && !state.loading) {
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+34−146
@@ -1,13 +1,7 @@
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
8import androidx.compose.foundation.background
3import androidx.compose.foundation.background
9import androidx.compose.foundation.clickable
4import androidx.compose.foundation.clickable
10−import androidx.compose.foundation.combinedClickable
11import androidx.compose.foundation.layout.Arrangement
5import androidx.compose.foundation.layout.Arrangement
12import androidx.compose.foundation.layout.Box
6import androidx.compose.foundation.layout.Box
13import androidx.compose.foundation.layout.Column
7import androidx.compose.foundation.layout.Column
@@ -21,17 +15,13 @@ import androidx.compose.foundation.layout.padding
21import androidx.compose.foundation.layout.size
15import androidx.compose.foundation.layout.size
22import androidx.compose.foundation.lazy.LazyColumn
16import androidx.compose.foundation.lazy.LazyColumn
23import androidx.compose.foundation.lazy.items
17import androidx.compose.foundation.lazy.items
24−import androidx.compose.foundation.lazy.rememberLazyListState
25−import androidx.compose.foundation.shape.CircleShape
26import androidx.compose.material.icons.Icons
18import androidx.compose.material.icons.Icons
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
19import androidx.compose.material.icons.automirrored.filled.ArrowBack
28import androidx.compose.material.icons.filled.Add
20import androidx.compose.material.icons.filled.Add
29import androidx.compose.material.icons.filled.ChatBubbleOutline
21import androidx.compose.material.icons.filled.ChatBubbleOutline
30−import androidx.compose.material.icons.filled.ChevronRight
31import androidx.compose.material.icons.filled.DeleteOutline
22import androidx.compose.material.icons.filled.DeleteOutline
32import androidx.compose.material.icons.filled.Refresh
23import androidx.compose.material.icons.filled.Refresh
33import androidx.compose.material3.AlertDialog
24import androidx.compose.material3.AlertDialog
34−import androidx.compose.material3.CircularProgressIndicator
35import androidx.compose.material3.ExperimentalMaterial3Api
25import androidx.compose.material3.ExperimentalMaterial3Api
36import androidx.compose.material3.ExtendedFloatingActionButton
26import androidx.compose.material3.ExtendedFloatingActionButton
37import androidx.compose.material3.HorizontalDivider
27import androidx.compose.material3.HorizontalDivider
@@ -41,7 +31,6 @@ import androidx.compose.material3.LinearProgressIndicator
41import androidx.compose.material3.MaterialTheme
31import androidx.compose.material3.MaterialTheme
42import androidx.compose.material3.OutlinedTextField
32import androidx.compose.material3.OutlinedTextField
43import androidx.compose.material3.Scaffold
33import androidx.compose.material3.Scaffold
44−import androidx.compose.material3.Surface
45import androidx.compose.material3.SwipeToDismissBox
34import androidx.compose.material3.SwipeToDismissBox
46import androidx.compose.material3.SwipeToDismissBoxValue
35import androidx.compose.material3.SwipeToDismissBoxValue
47import androidx.compose.material3.Text
36import androidx.compose.material3.Text
@@ -58,12 +47,8 @@ import androidx.compose.runtime.remember
58import androidx.compose.runtime.setValue
47import androidx.compose.runtime.setValue
59import androidx.compose.ui.Alignment
48import androidx.compose.ui.Alignment
60import androidx.compose.ui.Modifier
49import androidx.compose.ui.Modifier
61−import androidx.compose.ui.draw.clip
62−import androidx.compose.ui.graphics.Color
63import androidx.compose.ui.hapticfeedback.HapticFeedbackType
50import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64−import androidx.compose.ui.platform.LocalContext
65import androidx.compose.ui.platform.LocalHapticFeedback
51import androidx.compose.ui.platform.LocalHapticFeedback
66−import androidx.compose.ui.text.style.TextAlign
67import androidx.compose.ui.text.style.TextOverflow
52import androidx.compose.ui.text.style.TextOverflow
68import androidx.compose.ui.unit.dp
53import androidx.compose.ui.unit.dp
69import soy.iko.opencode.core.Event
54import soy.iko.opencode.core.Event
@@ -77,15 +62,6 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
77 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
62 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
78 var isPullRefreshing by remember { mutableStateOf(false) }
63 var isPullRefreshing by remember { mutableStateOf(false) }
79 var searchQuery by remember { mutableStateOf("") }
64 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
65
90 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
66 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
91 // every loading operation. Clear it once the underlying load completes.
67 // every loading operation. Clear it once the underlying load completes.
@@ -119,23 +95,7 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
119 Scaffold(
95 Scaffold(
120 topBar = {
96 topBar = {
121 TopAppBar(
97 TopAppBar(
122− title = {
98+ title = { Text("Sessions") },
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− },
139 navigationIcon = {
99 navigationIcon = {
140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
100 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
101 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -149,21 +109,14 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
149 )
109 )
150 },
110 },
151 floatingActionButton = {
111 floatingActionButton = {
152− // Give the search results the full width while searching — the FAB would
153− // otherwise cover the bottom rows and isn't relevant mid-search anyway.
154− if (searchQuery.isEmpty()) {
155− ExtendedFloatingActionButton(
112+ ExtendedFloatingActionButton(
156− onClick = { dispatch(Event.CreateSession) },
113+ onClick = { dispatch(Event.CreateSession) },
157− icon = { Icon(Icons.Filled.Add, contentDescription = null) },
114+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
158− text = { Text("New session") },
115+ text = { Text("New session") },
159− )
116+ )
160− }
161 },
117 },
162 ) { padding ->
118 ) { padding ->
163 Column(Modifier.fillMaxSize().padding(padding)) {
119 Column(Modifier.fillMaxSize().padding(padding)) {
164− if (!state.sseConnected) {
165− ReconnectingBanner()
166− }
167 if (state.loading && !isPullRefreshing) {
120 if (state.loading && !isPullRefreshing) {
168 LinearProgressIndicator(Modifier.fillMaxWidth())
121 LinearProgressIndicator(Modifier.fillMaxWidth())
169 }
122 }
@@ -199,37 +152,32 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
199 state = rememberPullToRefreshState(),
152 state = rememberPullToRefreshState(),
200 ) {
153 ) {
201 LazyColumn(
154 LazyColumn(
202− state = sessionsListState,
203 modifier = Modifier.fillMaxSize(),
155 modifier = Modifier.fillMaxSize(),
204 contentPadding = PaddingValues(bottom = 88.dp),
156 contentPadding = PaddingValues(bottom = 88.dp),
205 ) {
157 ) {
206 items(filteredSessions, key = { it.id }) { session ->
158 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(
159+ val dismissState = rememberSwipeToDismissBoxState(
211− // Only a swipe from the end (right-to-left) triggers deletion;
160+ // Only a swipe from the end (right-to-left) triggers deletion;
212− // return false so the row snaps back and the confirm dialog decides.
161+ // return false so the row snaps back and the confirm dialog decides.
213− confirmValueChange = { value ->
162+ confirmValueChange = { value ->
214− if (value == SwipeToDismissBoxValue.EndToStart) {
163+ if (value == SwipeToDismissBoxValue.EndToStart) {
215− pendingDeleteId = session.id
164+ pendingDeleteId = session.id
216− }
165+ }
217− false
166+ false
218− },
167+ },
168+ )
169+ SwipeToDismissBox(
170+ state = dismissState,
171+ enableDismissFromStartToEnd = false,
172+ backgroundContent = { SwipeDeleteBackground() },
173+ ) {
174+ SessionRow(
175+ session = session,
176+ onOpen = { dispatch(Event.SelectSession(session.id)) },
177+ onDelete = { pendingDeleteId = session.id },
219 )
178 )
220− SwipeToDismissBox(
221− state = dismissState,
222− enableDismissFromStartToEnd = false,
223− backgroundContent = { SwipeDeleteBackground() },
224− ) {
225− SessionRow(
226− session = session,
227− onOpen = { dispatch(Event.SelectSession(session.id)) },
228− onDelete = { pendingDeleteId = session.id },
229− )
230− }
231− HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
232 }
179 }
180+ HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
233 }
181 }
234 }
182 }
235 }
183 }
@@ -238,21 +186,13 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
238 }
186 }
239}
187}
240
188
241−@OptIn(ExperimentalFoundationApi::class)
242@Composable
189@Composable
243private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
190private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
244− val context = LocalContext.current
245 Row(
191 Row(
246 modifier = Modifier
192 modifier = Modifier
247 .fillMaxWidth()
193 .fillMaxWidth()
248 .background(MaterialTheme.colorScheme.surface)
194 .background(MaterialTheme.colorScheme.surface)
249− .combinedClickable(
250− onClick = onOpen,
195+ .clickable(onClick = onOpen)
251− onLongClick = {
252− copyToClipboard(context, session.id)
253− Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
254− },
255− )
256 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
196 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
257 verticalAlignment = Alignment.CenterVertically,
197 verticalAlignment = Alignment.CenterVertically,
258 ) {
198 ) {
@@ -277,23 +217,17 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
277 overflow = TextOverflow.Ellipsis,
217 overflow = TextOverflow.Ellipsis,
278 )
218 )
279 }
219 }
280− Icon(
281− Icons.Filled.ChevronRight,
282− contentDescription = null,
283− tint = MaterialTheme.colorScheme.onSurfaceVariant,
284− modifier = Modifier.padding(horizontal = 4.dp),
285− )
286 IconButton(onClick = onDelete) {
220 IconButton(onClick = onDelete) {
287 Icon(
221 Icon(
288 Icons.Filled.DeleteOutline,
222 Icons.Filled.DeleteOutline,
289 contentDescription = "Delete session",
223 contentDescription = "Delete session",
290− tint = MaterialTheme.colorScheme.error,
224+ tint = MaterialTheme.colorScheme.onSurfaceVariant,
291 )
225 )
292 }
226 }
293 }
227 }
294}
228}
295
229
296−/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
230+/** Red background with a trailing delete icon, revealed while swiping a session row away. */
297@Composable
231@Composable
298private fun SwipeDeleteBackground() {
232private fun SwipeDeleteBackground() {
299 Box(
233 Box(
@@ -303,53 +237,14 @@ private fun SwipeDeleteBackground() {
303 .padding(horizontal = 24.dp),
237 .padding(horizontal = 24.dp),
304 contentAlignment = Alignment.CenterEnd,
238 contentAlignment = Alignment.CenterEnd,
305 ) {
239 ) {
306− Row(verticalAlignment = Alignment.CenterVertically) {
307− Icon(
240+ Icon(
308− Icons.Filled.DeleteOutline,
241+ Icons.Filled.DeleteOutline,
309− contentDescription = null,
242+ contentDescription = null,
310− tint = MaterialTheme.colorScheme.onError,
243+ 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− ) {
244+ )
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 }
245 }
346}
246}
347
247
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. */
248/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
354private fun shortSessionId(id: String): String =
249private fun shortSessionId(id: String): String =
355 if (id.length > 12) id.take(8) + "…" else id
250 if (id.length > 12) id.take(8) + "…" else id
@@ -391,12 +286,5 @@ private fun EmptySessions() {
391 style = MaterialTheme.typography.bodyMedium,
286 style = MaterialTheme.typography.bodyMedium,
392 color = MaterialTheme.colorScheme.onSurfaceVariant,
287 color = MaterialTheme.colorScheme.onSurfaceVariant,
393 )
288 )
394− Spacer(Modifier.height(8.dp))
395− Text(
396− text = "Sessions you create on this server will appear here.",
397− style = MaterialTheme.typography.bodySmall,
398− color = MaterialTheme.colorScheme.onSurfaceVariant,
399− textAlign = TextAlign.Center,
400− )
401 }
289 }
402}
290}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+1−23
@@ -14,18 +14,7 @@ import androidx.compose.ui.platform.LocalContext
14private val DarkColors = darkColorScheme(
14private val DarkColors = darkColorScheme(
15 primary = Emerald,
15 primary = Emerald,
16 onPrimary = Color(0xFF0F1115),
16 onPrimary = Color(0xFF0F1115),
17− primaryContainer = Color(0xFF1A3D2A),
18− onPrimaryContainer = Color(0xFFA8E6C1),
19 secondary = EmeraldDark,
17 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),
29 background = DarkBackground,
18 background = DarkBackground,
30 surface = DarkSurface,
19 surface = DarkSurface,
31 surfaceVariant = DarkSurfaceVariant,
20 surfaceVariant = DarkSurfaceVariant,
@@ -35,18 +24,7 @@ private val DarkColors = darkColorScheme(
35
24
36private val LightColors = lightColorScheme(
25private val LightColors = lightColorScheme(
37 primary = EmeraldDark,
26 primary = EmeraldDark,
38− primaryContainer = Color(0xFFD7F5E3),
39− onPrimaryContainer = Color(0xFF0A3D22),
40 secondary = Emerald,
27 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),
50 background = LightBackground,
28 background = LightBackground,
51 surface = LightSurface,
29 surface = LightSurface,
52 surfaceVariant = LightSurfaceVariant,
30 surfaceVariant = LightSurfaceVariant,
@@ -57,7 +35,7 @@ private val LightColors = lightColorScheme(
57@Composable
35@Composable
58fun OpencodeTheme(
36fun OpencodeTheme(
59 darkTheme: Boolean = isSystemInDarkTheme(),
37 darkTheme: Boolean = isSystemInDarkTheme(),
60− dynamicColor: Boolean = false,
38+ dynamicColor: Boolean = true,
61 content: @Composable () -> Unit,
39 content: @Composable () -> Unit,
62) {
40) {
63 val context = LocalContext.current
41 val context = LocalContext.current
shared/src/app.rs−14
@@ -297,27 +297,16 @@ impl App for OpencodeApp {
297 // Store the field verbatim while typing; normalizing here would fight
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
298 // the user's edits (e.g. eat the "://" as they type it). The URL is
299 // normalized once, on Connect.
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.
302 Event::ServerUrlChanged(url) => {
300 Event::ServerUrlChanged(url) => {
303 model.server_url = url;
301 model.server_url = url;
304− if model.error.is_some() {
305− model.error = None;
306− }
307 render()
302 render()
308 }
303 }
309 Event::UsernameChanged(u) => {
304 Event::UsernameChanged(u) => {
310 model.username = u;
305 model.username = u;
311− if model.error.is_some() {
312− model.error = None;
313− }
314 render()
306 render()
315 }
307 }
316 Event::PasswordChanged(p) => {
308 Event::PasswordChanged(p) => {
317 model.password = p;
309 model.password = p;
318− if model.error.is_some() {
319− model.error = None;
320− }
321 render()
310 render()
322 }
311 }
323
312
@@ -352,9 +341,6 @@ impl App for OpencodeApp {
352 title: display_title(&s.title),
341 title: display_title(&s.title),
353 })
342 })
354 .collect();
343 .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());
358 }
344 }
359 Err(e) => model.error = Some(e),
345 Err(e) => model.error = Some(e),
360 }
346 }