git.iko.soy/opencode-android
on master help sign in
app/src/main/java/soy/iko/opencode/CoreViewModel.kt+14
since splitsnapshots
unifiedsplit
@@ -23,11 +23,23 @@ 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)) }
26
29
27 // On a fresh process after a configuration change, resume the SSE stream if
30 // On a fresh process after a configuration change, resume the SSE stream if
28 // the core is already connected (no-op otherwise — it guards on `connected`).
31 // the core is already connected (no-op otherwise — it guards on `connected`).
29 core.resumeStreamingIfConnected()
32 core.resumeStreamingIfConnected()
30
33
34+ // Returning users shouldn't have to tap Connect: if a URL was restored and we
35+ // aren't already connected, kick off the connection attempt on launch. The core
36+ // handles an empty/invalid URL, so this only fires when there's something to try.
37+ core.view.value.let { restored ->
38+ if (restored.serverUrl.isNotEmpty() && !restored.connected) {
39+ core.dispatch(Event.Connect)
40+ }
41+ }
42+
31 // Persist connection details once a connection succeeds.
43 // Persist connection details once a connection succeeds.
32 viewModelScope.launch {
44 viewModelScope.launch {
33 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
45 core.view.distinctUntilChangedBy { it.connected to it.serverUrl }.collect { state ->
@@ -35,6 +47,7 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
35 prefs.edit {
47 prefs.edit {
36 putString(KEY_URL, state.serverUrl)
48 putString(KEY_URL, state.serverUrl)
37 putString(KEY_USER, state.username)
49 putString(KEY_USER, state.username)
50+ putString(KEY_PASSWORD, state.password)
38 }
51 }
39 }
52 }
40 }
53 }
@@ -48,5 +61,6 @@ class CoreViewModel(app: Application) : AndroidViewModel(app) {
48 private companion object {
61 private companion object {
49 const val KEY_URL = "serverUrl"
62 const val KEY_URL = "serverUrl"
50 const val KEY_USER = "username"
63 const val KEY_USER = "username"
64+ const val KEY_PASSWORD = "password"
51 }
65 }
52}
66}
app/src/main/java/soy/iko/opencode/core/HttpClient.kt+1
@@ -51,6 +51,7 @@ class HttpClient(
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
51 ): Result<HttpResp> = withContext(Dispatchers.IO) {
52 runCatching {
52 runCatching {
53 val builder = Request.Builder().url(url).method()
53 val builder = Request.Builder().url(url).method()
54+ builder.header("User-Agent", "opencode-android/1.0")
54 if (auth != null) builder.header("Authorization", auth)
55 if (auth != null) builder.header("Authorization", auth)
55 await(okhttp.newCall(builder.build()))
56 await(okhttp.newCall(builder.build()))
56 }
57 }
app/src/main/java/soy/iko/opencode/core/OpencodeCore.kt+130−16
@@ -51,15 +51,41 @@ class OpencodeCore(
51 private var reconnectAttempts = 0
51 private var reconnectAttempts = 0
52 private var reconnectJob: Job? = null
52 private var reconnectJob: Job? = null
53
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+
54 // ── Event entry point ──────────────────────────────────────────────────────
78 // ── Event entry point ──────────────────────────────────────────────────────
55 fun dispatch(event: Event) {
79 fun dispatch(event: Event) {
56 when (event) {
80 when (event) {
57 // Store the field verbatim while typing; normalizing here would fight
81 // Store the field verbatim while typing; normalizing here would fight
58 // the user's edits (e.g. eat the "://" as they type it). The URL is
82 // the user's edits (e.g. eat the "://" as they type it). The URL is
59 // normalized once, on Connect.
83 // normalized once, on Connect.
84+ // Clear any prior error as soon as the user edits a field, so a stale
85+ // message (e.g. "Invalid credentials") doesn't linger while they correct it.
60− is Event.ServerUrlChanged -> { serverUrl = event.url; emit() }
86+ is Event.ServerUrlChanged -> { serverUrl = event.url; if (error != null) error = null; emit() }
61− is Event.UsernameChanged -> { username = event.value; emit() }
87+ is Event.UsernameChanged -> { username = event.value; if (error != null) error = null; emit() }
62− is Event.PasswordChanged -> { password = event.value; emit() }
88+ is Event.PasswordChanged -> { password = event.value; if (error != null) error = null; emit() }
63
89
64 Event.Connect -> {
90 Event.Connect -> {
65 serverUrl = normalizeUrl(serverUrl)
91 serverUrl = normalizeUrl(serverUrl)
@@ -70,31 +96,54 @@ class OpencodeCore(
70 // Leave authRequired as-is; probeHealth sets it from the response (true on
96 // Leave authRequired as-is; probeHealth sets it from the response (true on
71 // 401, false on success). Resetting it here just flickers the auth fields.
97 // 401, false on success). Resetting it here just flickers the auth fields.
72 loading = true; error = null; emit()
98 loading = true; error = null; emit()
99+ connectJob?.cancel()
73− scope.launch { probeHealth() }
100+ connectJob = scope.launch { probeHealth() }
74 }
101 }
75
102
103+ Event.LoadSessions -> {
104+ if (!connected) { error = "Not connected"; emit(); return }
105+ loading = true; emit()
106+ loadSessionsJob?.cancel()
76− Event.LoadSessions -> { loading = true; emit(); scope.launch { loadSessions() } }
107+ loadSessionsJob = scope.launch { loadSessions() }
108+ }
77
109
78 is Event.SelectSession -> {
110 is Event.SelectSession -> {
111+ // The session may have been deleted (e.g. via SSE) while the list was on
112+ // screen; opening it would only 404 on loadMessages. Bail with an error.
79− currentSessionTitle = sessions.firstOrNull { it.id == event.id }?.title.orEmpty()
113+ val session = sessions.firstOrNull { it.id == event.id }
114+ if (session == null) { error = "Session no longer exists"; emit(); return }
115+ currentSessionTitle = session.title
80 currentSessionId = event.id
116 currentSessionId = event.id
81 messages.clear()
117 messages.clear()
118+ removedMessageIds.clear()
82 screen = Screen.Chat
119 screen = Screen.Chat
83 loading = true
120 loading = true
84 generating = false
121 generating = false
85 error = null
122 error = null
86 emit()
123 emit()
124+ connectJob?.cancel()
125+ abortJob?.cancel()
126+ sendMessageJob?.cancel()
127+ deleteSessionJob?.cancel()
128+ loadMessagesJob?.cancel()
87− scope.launch { loadMessages(event.id) }
129+ loadMessagesJob = scope.launch { loadMessages(event.id) }
88 }
130 }
89
131
132+ Event.CreateSession -> {
133+ if (!connected) { error = "Not connected"; emit(); return }
90− Event.CreateSession -> { loading = true; error = null; emit(); scope.launch { createSession() } }
134+ loading = true; error = null; emit()
135+ createSessionJob?.cancel()
136+ createSessionJob = scope.launch { createSession() }
137+ }
91
138
92 is Event.DeleteSession -> {
139 is Event.DeleteSession -> {
140+ if (!connected) { error = "Not connected"; emit(); return }
93 val id = event.id
141 val id = event.id
94 // Delete on the server first; only drop it from the UI once that
142 // Delete on the server first; only drop it from the UI once that
95 // succeeds, so a failed request leaves the session recoverable.
143 // succeeds, so a failed request leaves the session recoverable.
96 loading = true; error = null; emit()
144 loading = true; error = null; emit()
145+ deleteSessionJob?.cancel()
97− scope.launch {
146+ deleteSessionJob = scope.launch {
98 http.delete("$serverUrl/session/$id", authHeader()).fold(
147 http.delete("$serverUrl/session/$id", authHeader()).fold(
99 onSuccess = { resp ->
148 onSuccess = { resp ->
100 if (resp.code in 200..299) {
149 if (resp.code in 200..299) {
@@ -127,17 +176,32 @@ class OpencodeCore(
127 messages.forEach { it.streaming = false }
176 messages.forEach { it.streaming = false }
128 emit()
177 emit()
129 val id = currentSessionId ?: return
178 val id = currentSessionId ?: return
179+ // Debounce rapid cancel taps: cancel any in-flight abort before firing
180+ // another so we don't stack duplicate abort requests.
181+ abortJob?.cancel()
130− scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
182+ abortJob = scope.launch { http.postJson("$serverUrl/session/$id/abort", "{}", authHeader()) }
131 }
183 }
132
184
133 Event.NavigateToSessions -> {
185 Event.NavigateToSessions -> {
134 screen = Screen.Sessions
186 screen = Screen.Sessions
135 currentSessionId = null
187 currentSessionId = null
136 messages.clear()
188 messages.clear()
189+ removedMessageIds.clear()
190+ draft = ""
137 generating = false
191 generating = false
192+ // Clear any error from the chat (e.g. a failed send) so it doesn't
193+ // linger on the sessions list after the user navigates back.
194+ error = null
138 loading = true
195 loading = true
139 emit()
196 emit()
197+ connectJob?.cancel()
198+ abortJob?.cancel()
199+ createSessionJob?.cancel()
200+ deleteSessionJob?.cancel()
201+ sendMessageJob?.cancel()
202+ loadMessagesJob?.cancel()
203+ loadSessionsJob?.cancel()
140− scope.launch { loadSessions() }
204+ loadSessionsJob = scope.launch { loadSessions() }
141 }
205 }
142
206
143 Event.NavigateToConnect -> {
207 Event.NavigateToConnect -> {
@@ -147,10 +211,18 @@ class OpencodeCore(
147 generating = false
211 generating = false
148 sessions.clear()
212 sessions.clear()
149 messages.clear()
213 messages.clear()
214+ removedMessageIds.clear()
150 currentSessionId = null
215 currentSessionId = null
216+ draft = ""
151 // Reset to the default so a late-firing close callback from the old
217 // Reset to the default so a late-firing close callback from the old
152 // SSE connection can't flash the reconnecting banner on the next connect.
218 // SSE connection can't flash the reconnecting banner on the next connect.
153 sseConnected = true
219 sseConnected = true
220+ connectJob?.cancel()
221+ abortJob?.cancel()
222+ createSessionJob?.cancel()
223+ deleteSessionJob?.cancel()
224+ sendMessageJob?.cancel()
225+ loadMessagesJob?.cancel()
154 closeSse()
226 closeSse()
155 emit()
227 emit()
156 }
228 }
@@ -164,13 +236,27 @@ class OpencodeCore(
164 if (connected && sse == null) startSse()
236 if (connected && sse == null) startSse()
165 }
237 }
166
238
167− fun shutdown() = closeSse()
239+ fun shutdown() {
240+ // Cancel every tracked coroutine before tearing down the stream so none can
241+ // emit into a cancelled scope after the ViewModel is cleared.
242+ connectJob?.cancel()
243+ loadSessionsJob?.cancel()
244+ createSessionJob?.cancel()
245+ loadMessagesJob?.cancel()
246+ deleteSessionJob?.cancel()
247+ sendMessageJob?.cancel()
248+ abortJob?.cancel()
249+ closeSse()
250+ }
168
251
169 // ── Effects ────────────────────────────────────────────────────────────────
252 // ── Effects ────────────────────────────────────────────────────────────────
170 private fun sendMessage(raw: String) {
253 private fun sendMessage(raw: String) {
171 val text = raw.trim()
254 val text = raw.trim()
172 val session = currentSessionId ?: return
255 val session = currentSessionId ?: return
173 if (text.isEmpty()) return
256 if (text.isEmpty()) return
257+ // Debounce rapid double-taps on send: a send is already in flight, so a second
258+ // tap would create a duplicate user message and fire a duplicate request.
259+ if (generating) return
174 localSeq += 1
260 localSeq += 1
175 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
261 val user = MsgState("local-$localSeq", "user", System.currentTimeMillis()).apply {
176 status = MessageStatus.Pending
262 status = MessageStatus.Pending
@@ -186,7 +272,8 @@ class OpencodeCore(
186 emit()
272 emit()
187
273
188 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
274 val body = Protocol.json.encodeToString(PromptBody.serializer(), PromptBody(listOf(TextInput(text = text))))
275+ sendMessageJob?.cancel()
189− scope.launch {
276+ sendMessageJob = scope.launch {
190 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
277 val result = http.postJson("$serverUrl/session/$session/prompt_async", body, authHeader())
191 result.fold(
278 result.fold(
192 onSuccess = { resp ->
279 onSuccess = { resp ->
@@ -219,6 +306,10 @@ class OpencodeCore(
219 when {
306 when {
220 resp.code == 401 -> {
307 resp.code == 401 -> {
221 loading = false
308 loading = false
309+ // A prior connection may have succeeded (connected = true); a
310+ // re-probe returning 401 (e.g. expired credentials) means we're
311+ // no longer authenticated, so drop the connected flag.
312+ connected = false
222 // Always reveal the auth fields so the user can see/edit
313 // Always reveal the auth fields so the user can see/edit
223 // their credentials — even when the ones supplied were wrong.
314 // their credentials — even when the ones supplied were wrong.
224 authRequired = true
315 authRequired = true
@@ -233,10 +324,14 @@ class OpencodeCore(
233 loading = true
324 loading = true
234 emit()
325 emit()
235 startSse()
326 startSse()
327+ // Route through loadSessionsJob so a prior in-flight loadSessions
328+ // (e.g. from a rapid double-connect) is cancelled first.
329+ loadSessionsJob?.cancel()
236− loadSessions()
330+ loadSessionsJob = scope.launch { loadSessions() }
237 }
331 }
238 else -> {
332 else -> {
239 loading = false
333 loading = false
334+ connected = false
240 error = "Server returned status ${resp.code}"
335 error = "Server returned status ${resp.code}"
241 emit()
336 emit()
242 }
337 }
@@ -244,6 +339,7 @@ class OpencodeCore(
244 },
339 },
245 onFailure = { e ->
340 onFailure = { e ->
246 loading = false
341 loading = false
342+ connected = false
247 error = "Connection failed: ${e.message}"
343 error = "Connection failed: ${e.message}"
248 emit()
344 emit()
249 },
345 },
@@ -256,6 +352,9 @@ class OpencodeCore(
256 if (resp.code in 200..299) {
352 if (resp.code in 200..299) {
257 sessions.clear()
353 sessions.clear()
258 sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
354 sessions.addAll(Protocol.parseSessions(resp.body).map { SessionView(it.id, displayTitle(it.title)) })
355+ // Impose a stable alphabetical order so the list doesn't shuffle with
356+ // whatever order the server happens to return sessions in.
357+ sessions.sortBy { it.title.lowercase() }
259 } else {
358 } else {
260 error = "Server returned status ${resp.code}"
359 error = "Server returned status ${resp.code}"
261 }
360 }
@@ -273,6 +372,10 @@ class OpencodeCore(
273 if (session != null) {
372 if (session != null) {
274 if (sessions.none { it.id == session.id }) {
373 if (sessions.none { it.id == session.id }) {
275 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
374 sessions.add(0, SessionView(session.id, displayTitle(session.title)))
375+ // Restore the alphabetical order immediately (matching loadSessions /
376+ // SessionUpserted) so the new session doesn't sit out-of-order at the
377+ // top until the SSE SessionUpserted event arrives to re-sort.
378+ sessions.sortBy { it.title.lowercase() }
276 }
379 }
277 emit()
380 emit()
278 // SelectSession takes over the loading state (loads messages).
381 // SelectSession takes over the loading state (loads messages).
@@ -294,6 +397,7 @@ class OpencodeCore(
294 loading = false
397 loading = false
295 if (resp.code in 200..299) {
398 if (resp.code in 200..299) {
296 messages.clear()
399 messages.clear()
400+ removedMessageIds.clear()
297 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
401 messages.addAll(Protocol.parseMessages(resp.body).map(::messageFromWire))
298 generating = messages.any { it.streaming }
402 generating = messages.any { it.streaming }
299 } else {
403 } else {
@@ -367,6 +471,9 @@ class OpencodeCore(
367 is Protocol.Event.MessageUpdated -> {
471 is Protocol.Event.MessageUpdated -> {
368 val info = event.info
472 val info = event.info
369 if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
473 if (info.role != "assistant" || !isCurrent(info.sessionId)) return false
474+ // A MessageRemoved may have arrived before this (late/out-of-order) update;
475+ // don't re-create a message the server has already deleted.
476+ if (info.id in removedMessageIds) return false
370 val streaming = info.time.completed == null && info.error == null
477 val streaming = info.time.completed == null && info.error == null
371 val existing = messages.firstOrNull { it.id == info.id }
478 val existing = messages.firstOrNull { it.id == info.id }
372 if (existing != null) {
479 if (existing != null) {
@@ -375,7 +482,7 @@ class OpencodeCore(
375 } else {
482 } else {
376 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
483 messages.add(MsgState(info.id, "assistant", info.time.created).apply { this.streaming = streaming })
377 }
484 }
378− info.error?.let { error = it.message(); generating = false }
485+ info.error?.let { error = it.message(); messages.forEach { m -> m.streaming = false }; generating = false }
379 return true
486 return true
380 }
487 }
381
488
@@ -408,7 +515,11 @@ class OpencodeCore(
408 return true
515 return true
409 }
516 }
410
517
518+ is Protocol.Event.MessageRemoved -> {
519+ // Remember the ID so a late MessageUpdated can't resurrect the message.
520+ removedMessageIds.add(event.messageId)
411− is Protocol.Event.MessageRemoved -> return messages.removeAll { it.id == event.messageId }
521+ return messages.removeAll { it.id == event.messageId }
522+ }
412
523
413 is Protocol.Event.SessionIdle -> {
524 is Protocol.Event.SessionIdle -> {
414 if (!isCurrent(event.sessionId)) return false
525 if (!isCurrent(event.sessionId)) return false
@@ -434,6 +545,9 @@ class OpencodeCore(
434 } else {
545 } else {
435 sessions.add(0, SessionView(event.info.id, title))
546 sessions.add(0, SessionView(event.info.id, title))
436 }
547 }
548+ // Keep the list alphabetically sorted (matching loadSessions) so an
549+ // upserted session doesn't jump to the top and break the ordering.
550+ sessions.sortBy { it.title.lowercase() }
437 if (isCurrent(event.info.id)) currentSessionTitle = title
551 if (isCurrent(event.info.id)) currentSessionTitle = title
438 return true
552 return true
439 }
553 }
app/src/main/java/soy/iko/opencode/core/SseClient.kt+1
@@ -33,6 +33,7 @@ class SseClient(
33
33
34 fun connect() {
34 fun connect() {
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
35 val builder = Request.Builder().url(url).header("Accept", "text/event-stream")
36+ builder.header("User-Agent", "opencode-android/1.0")
36 if (auth != null) builder.header("Authorization", auth)
37 if (auth != null) builder.header("Authorization", auth)
37 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
38 source = EventSources.createFactory(client).newEventSource(builder.build(), listener)
38 }
39 }
app/src/main/java/soy/iko/opencode/ui/OpencodeApp.kt+55−2
@@ -7,13 +7,19 @@ 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
10import androidx.compose.material3.Scaffold
11import androidx.compose.material3.Scaffold
11import androidx.compose.material3.SnackbarDuration
12import androidx.compose.material3.SnackbarDuration
12import androidx.compose.material3.SnackbarHost
13import androidx.compose.material3.SnackbarHost
13import androidx.compose.material3.SnackbarHostState
14import androidx.compose.material3.SnackbarHostState
15+import androidx.compose.material3.Text
16+import androidx.compose.material3.TextButton
14import androidx.compose.runtime.Composable
17import androidx.compose.runtime.Composable
15import androidx.compose.runtime.LaunchedEffect
18import androidx.compose.runtime.LaunchedEffect
19+import androidx.compose.runtime.getValue
20+import androidx.compose.runtime.mutableStateOf
16import androidx.compose.runtime.remember
21import androidx.compose.runtime.remember
22+import androidx.compose.runtime.setValue
17import androidx.compose.ui.Modifier
23import androidx.compose.ui.Modifier
18import soy.iko.opencode.core.Event
24import soy.iko.opencode.core.Event
19import soy.iko.opencode.core.Screen
25import soy.iko.opencode.core.Screen
@@ -25,6 +31,8 @@ import soy.iko.opencode.ui.screens.SessionsScreen
25@Composable
31@Composable
26fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
32fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
27 val snackbar = remember { SnackbarHostState() }
33 val snackbar = remember { SnackbarHostState() }
34+ var showStopConfirm by remember { mutableStateOf(false) }
35+ var showDisconnectConfirm by remember { mutableStateOf(false) }
28
36
29 LaunchedEffect(state.error) {
37 LaunchedEffect(state.error) {
30 state.error?.let {
38 state.error?.let {
@@ -40,12 +48,57 @@ fun OpencodeApp(state: UiState, dispatch: (Event) -> Unit) {
40
48
41 BackHandler(enabled = state.screen != Screen.Connect) {
49 BackHandler(enabled = state.screen != Screen.Connect) {
42 when (state.screen) {
50 when (state.screen) {
51+ // Leaving mid-generation would silently drop the reply, so confirm first.
43− Screen.Chat -> dispatch(Event.NavigateToSessions)
52+ Screen.Chat -> if (state.generating) showStopConfirm = true else dispatch(Event.NavigateToSessions)
44− Screen.Sessions -> dispatch(Event.NavigateToConnect)
53+ // Disconnecting drops the server session, so guard the back button.
54+ Screen.Sessions -> showDisconnectConfirm = true
45 Screen.Connect -> Unit
55 Screen.Connect -> Unit
46 }
56 }
47 }
57 }
48
58
59+ if (showStopConfirm) {
60+ AlertDialog(
61+ onDismissRequest = { showStopConfirm = false },
62+ title = { Text("Stop generation?") },
63+ text = { Text("Leaving will stop the current generation.") },
64+ confirmButton = {
65+ TextButton(onClick = {
66+ showStopConfirm = false
67+ dispatch(Event.CancelGeneration)
68+ dispatch(Event.NavigateToSessions)
69+ }) {
70+ Text("Stop and leave")
71+ }
72+ },
73+ dismissButton = {
74+ TextButton(onClick = { showStopConfirm = false }) {
75+ Text("Stay")
76+ }
77+ },
78+ )
79+ }
80+
81+ if (showDisconnectConfirm) {
82+ AlertDialog(
83+ onDismissRequest = { showDisconnectConfirm = false },
84+ title = { Text("Disconnect?") },
85+ text = { Text("You will be disconnected from the server.") },
86+ confirmButton = {
87+ TextButton(onClick = {
88+ showDisconnectConfirm = false
89+ dispatch(Event.NavigateToConnect)
90+ }) {
91+ Text("Disconnect")
92+ }
93+ },
94+ dismissButton = {
95+ TextButton(onClick = { showDisconnectConfirm = false }) {
96+ Text("Cancel")
97+ }
98+ },
99+ )
100+ }
101+
49 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
102 Scaffold(snackbarHost = { SnackbarHost(snackbar) }) { padding ->
50 AnimatedContent(
103 AnimatedContent(
51 targetState = state.screen,
104 targetState = state.screen,
app/src/main/java/soy/iko/opencode/ui/components/MessageBubble.kt+245−8
@@ -3,6 +3,8 @@ 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
6import android.widget.Toast
8import android.widget.Toast
7import androidx.compose.foundation.ExperimentalFoundationApi
9import androidx.compose.foundation.ExperimentalFoundationApi
8import androidx.compose.foundation.background
10import androidx.compose.foundation.background
@@ -13,6 +15,7 @@ import androidx.compose.foundation.layout.Column
13import androidx.compose.foundation.layout.Row
15import androidx.compose.foundation.layout.Row
14import androidx.compose.foundation.layout.fillMaxWidth
16import androidx.compose.foundation.layout.fillMaxWidth
15import androidx.compose.foundation.layout.padding
17import androidx.compose.foundation.layout.padding
18+import androidx.compose.foundation.layout.size
16import androidx.compose.foundation.layout.widthIn
19import androidx.compose.foundation.layout.widthIn
17import androidx.compose.foundation.shape.RoundedCornerShape
20import androidx.compose.foundation.shape.RoundedCornerShape
18import androidx.compose.foundation.text.selection.SelectionContainer
21import androidx.compose.foundation.text.selection.SelectionContainer
@@ -23,6 +26,9 @@ import androidx.compose.material.icons.filled.ErrorOutline
23import androidx.compose.material.icons.filled.ExpandLess
26import androidx.compose.material.icons.filled.ExpandLess
24import androidx.compose.material.icons.filled.ExpandMore
27import androidx.compose.material.icons.filled.ExpandMore
25import androidx.compose.material.icons.filled.Schedule
28import androidx.compose.material.icons.filled.Schedule
29+import androidx.compose.material.icons.filled.SmartToy
30+import androidx.compose.material3.DropdownMenu
31+import androidx.compose.material3.DropdownMenuItem
26import androidx.compose.material3.Icon
32import androidx.compose.material3.Icon
27import androidx.compose.material3.MaterialTheme
33import androidx.compose.material3.MaterialTheme
28import androidx.compose.material3.Text
34import androidx.compose.material3.Text
@@ -36,12 +42,20 @@ import androidx.compose.ui.Modifier
36import androidx.compose.ui.draw.clip
42import androidx.compose.ui.draw.clip
37import androidx.compose.ui.graphics.Color
43import androidx.compose.ui.graphics.Color
38import androidx.compose.ui.platform.LocalContext
44import androidx.compose.ui.platform.LocalContext
45+import androidx.compose.ui.text.AnnotatedString
46+import androidx.compose.ui.text.LinkAnnotation
39import androidx.compose.ui.text.SpanStyle
47import androidx.compose.ui.text.SpanStyle
48+import androidx.compose.ui.text.TextLinkStyles
40import androidx.compose.ui.text.buildAnnotatedString
49import androidx.compose.ui.text.buildAnnotatedString
50+import androidx.compose.ui.text.font.FontFamily
41import androidx.compose.ui.text.font.FontStyle
51import androidx.compose.ui.text.font.FontStyle
52+import androidx.compose.ui.text.font.FontWeight
53+import androidx.compose.ui.text.withLink
42import androidx.compose.ui.text.withStyle
54import androidx.compose.ui.text.withStyle
55+import androidx.compose.ui.text.style.TextDecoration
43import androidx.compose.ui.text.style.TextOverflow
56import androidx.compose.ui.text.style.TextOverflow
44import androidx.compose.ui.unit.dp
57import androidx.compose.ui.unit.dp
58+import androidx.compose.ui.unit.sp
45import soy.iko.opencode.core.MessageStatus
59import soy.iko.opencode.core.MessageStatus
46import soy.iko.opencode.core.MessageView
60import soy.iko.opencode.core.MessageView
47import soy.iko.opencode.core.ToolView
61import soy.iko.opencode.core.ToolView
@@ -51,7 +65,7 @@ private val timeFormat = java.time.format.DateTimeFormatter.ofPattern("HH:mm")
51
65
52@OptIn(ExperimentalFoundationApi::class)
66@OptIn(ExperimentalFoundationApi::class)
53@Composable
67@Composable
54−fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
68+fun MessageBubble(message: MessageView, modifier: Modifier = Modifier, onRetry: () -> Unit = {}, compactSpacing: Boolean = false) {
55 val isUser = message.isUser
69 val isUser = message.isUser
56 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
70 val bubbleColor = if (isUser) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant
57 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
71 val textColor = if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface
@@ -64,11 +78,20 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
64 )
78 )
65
79
66 val context = LocalContext.current
80 val context = LocalContext.current
81+ var showMenu by remember { mutableStateOf(false) }
67
82
68 Row(
83 Row(
69− modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
84+ modifier = modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = if (compactSpacing) 1.dp else 4.dp),
70 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
85 horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start,
71 ) {
86 ) {
87+ if (!isUser) {
88+ Icon(
89+ Icons.Filled.SmartToy,
90+ contentDescription = null,
91+ tint = MaterialTheme.colorScheme.primary,
92+ modifier = Modifier.align(Alignment.Top).padding(end = 6.dp, top = 2.dp).size(28.dp),
93+ )
94+ }
72 Column(
95 Column(
73 modifier = Modifier
96 modifier = Modifier
74 .fillMaxWidth(0.85f)
97 .fillMaxWidth(0.85f)
@@ -79,23 +102,63 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
79 onClick = {},
102 onClick = {},
80 onLongClick = {
103 onLongClick = {
81 if (message.text.isNotEmpty()) {
104 if (message.text.isNotEmpty()) {
82− copyToClipboard(context, message.text)
105+ showMenu = true
83− Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
84 }
106 }
85 },
107 },
86 )
108 )
87 .padding(horizontal = 14.dp, vertical = 10.dp),
109 .padding(horizontal = 14.dp, vertical = 10.dp),
88 ) {
110 ) {
111+ DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
112+ DropdownMenuItem(
113+ text = { Text("Copy") },
114+ onClick = {
115+ copyToClipboard(context, message.text)
116+ Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
117+ showMenu = false
118+ },
119+ )
120+ DropdownMenuItem(
121+ text = { Text("Share") },
122+ onClick = {
123+ shareText(context, message.text)
124+ showMenu = false
125+ },
126+ )
127+ }
128+
89 message.reasoning?.let { ReasoningBlock(it, context) }
129 message.reasoning?.let { ReasoningBlock(it, context) }
90
130
131+ // Give a quick overview of how many tools ran before listing them.
132+ if (message.tools.size > 1) {
133+ Text(
134+ text = "${message.tools.size} tool calls",
135+ style = MaterialTheme.typography.labelSmall,
136+ color = MaterialTheme.colorScheme.onSurfaceVariant,
137+ modifier = Modifier.padding(bottom = 4.dp),
138+ )
139+ }
140+
91 message.tools.forEach { ToolRow(it) }
141 message.tools.forEach { ToolRow(it) }
92
142
93 SelectionContainer {
143 SelectionContainer {
94 if (message.text.isNotEmpty()) {
144 if (message.text.isNotEmpty()) {
145+ val linkColor = MaterialTheme.colorScheme.primary
146+ // Tint the code background off the bubble's own foreground colour so it
147+ // contrasts on both bubble types (user bubbles use primaryContainer).
148+ val codeBackground = (if (isUser) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onSurface).copy(alpha = 0.08f)
149+ val annotatedText = remember(message.text, message.streaming, linkColor, codeBackground, context) {
150+ buildLinkedText(message.text, message.streaming, linkColor, codeBackground, context)
151+ }
95 Text(
152 Text(
96− text = message.text + if (message.streaming) " ▌" else "",
153+ text = annotatedText,
97 color = textColor,
154 color = textColor,
155+ // Give assistant replies (often long, code-heavy) extra line
156+ // spacing for readability; user bubbles keep the default.
157+ style = if (isUser) {
98− style = MaterialTheme.typography.bodyLarge,
158+ MaterialTheme.typography.bodyLarge
159+ } else {
160+ MaterialTheme.typography.bodyLarge.copy(lineHeight = 22.sp)
161+ },
99 )
162 )
100 } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
163 } else if (message.streaming && message.tools.isEmpty() && message.reasoning == null) {
101 Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
164 Text("▌", color = textColor, style = MaterialTheme.typography.bodyLarge)
@@ -112,7 +175,7 @@ fun MessageBubble(message: MessageView, modifier: Modifier = Modifier) {
112 }
175 }
113
176
114 if (isUser && message.status != MessageStatus.Sent) {
177 if (isUser && message.status != MessageStatus.Sent) {
115− StatusLine(message.status)
178+ StatusLine(message.status, onRetry = onRetry)
116 }
179 }
117 }
180 }
118 }
181 }
@@ -123,6 +186,170 @@ private fun copyToClipboard(context: Context, text: String) {
123 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
186 clipboard.setPrimaryClip(ClipData.newPlainText("message", text))
124}
187}
125
188
189+private val urlRegex = Regex("""https?://[^\s]+""")
190+
191+/**
192+ * Render [text] as an AnnotatedString. Triple-backtick fences split the text into
193+ * prose and code segments: code segments are rendered monospace on a tinted
194+ * [codeBackground] (fences dropped), while prose has each http(s) URL turned into a
195+ * clickable link. The streaming cursor (" ▌") is appended outside any annotation.
196+ */
197+private fun buildLinkedText(
198+ text: String,
199+ streaming: Boolean,
200+ linkColor: Color,
201+ codeBackground: Color,
202+ context: Context,
203+): AnnotatedString = buildAnnotatedString {
204+ // Odd-indexed segments sit between a pair of ``` fences, so they're code. An
205+ // unclosed fence leaves the trailing segment styled as code, mirroring markdown.
206+ val segments = text.split("```")
207+ segments.forEachIndexed { index, segment ->
208+ if (index % 2 == 1) {
209+ withStyle(SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground)) {
210+ append(segment)
211+ }
212+ } else {
213+ appendLinkedText(segment, linkColor, codeBackground, context)
214+ }
215+ }
216+ if (streaming) append(" ▌")
217+}
218+
219+/**
220+ * Append [text] to the builder. Double-asterisk pairs are rendered bold; within each
221+ * segment, single-backtick pairs are rendered as inline code (monospace, backticks
222+ * dropped), and the remaining prose has each http(s) URL turned into a clickable link.
223+ * Triple-backtick fences are already stripped upstream in [buildLinkedText], so only
224+ * inline spans reach here.
225+ */
226+private fun AnnotatedString.Builder.appendLinkedText(
227+ text: String,
228+ linkColor: Color,
229+ codeBackground: Color,
230+ context: Context,
231+) {
232+ // Bold is the outermost inline layer: split on ** first so a bold span can wrap
233+ // inline code and links inside it. Odd-indexed segments sit between a pair of **
234+ // markers, so they're bold (markers dropped); even segments are ordinary prose.
235+ // Only the non-bold (even) segments get single-* italic handling — splitting a bold
236+ // segment on "*" would misfire on the leftover asterisks from the ** markers.
237+ val segments = text.split("**")
238+ // An even segment count means an odd number of ** markers, so the final ** is unclosed:
239+ // its trailing segment isn't bold. Restore the literal ** and render it as ordinary prose.
240+ val unclosed = segments.size % 2 == 0
241+ segments.forEachIndexed { index, segment ->
242+ val isUnclosedTail = unclosed && index == segments.size - 1
243+ if (index % 2 == 1 && !isUnclosedTail) {
244+ withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
245+ appendInlineCode(segment, linkColor, codeBackground, context)
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+
126@Composable
353@Composable
127private fun ReasoningBlock(text: String, context: Context) {
354private fun ReasoningBlock(text: String, context: Context) {
128 var expanded by remember { mutableStateOf(false) }
355 var expanded by remember { mutableStateOf(false) }
@@ -220,7 +447,7 @@ private fun ToolRow(tool: ToolView) {
220}
447}
221
448
222@Composable
449@Composable
223−private fun StatusLine(status: MessageStatus) {
450+private fun StatusLine(status: MessageStatus, onRetry: () -> Unit) {
224 val (icon, label, tint) = when (status) {
451 val (icon, label, tint) = when (status) {
225 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
452 MessageStatus.Pending -> Triple(Icons.Filled.Schedule, "Sending…", MaterialTheme.colorScheme.onPrimaryContainer)
226 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
453 MessageStatus.Failed -> Triple(Icons.Filled.ErrorOutline, "Failed to send", MaterialTheme.colorScheme.error)
@@ -238,5 +465,15 @@ private fun StatusLine(status: MessageStatus) {
238 color = tint,
465 color = tint,
239 modifier = Modifier.padding(start = 4.dp),
466 modifier = Modifier.padding(start = 4.dp),
240 )
467 )
468+ if (status == MessageStatus.Failed) {
469+ Text(
470+ text = "Retry",
471+ style = MaterialTheme.typography.labelSmall,
472+ color = MaterialTheme.colorScheme.primary,
473+ modifier = Modifier
474+ .padding(start = 12.dp)
475+ .clickable { onRetry() },
476+ )
477+ }
241 }
478 }
242}
479}
app/src/main/java/soy/iko/opencode/ui/screens/ChatScreen.kt+280−17
@@ -1,38 +1,57 @@
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
3import androidx.compose.animation.AnimatedVisibility
7import 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
4import androidx.compose.animation.fadeIn
13import androidx.compose.animation.fadeIn
5import androidx.compose.animation.fadeOut
14import androidx.compose.animation.fadeOut
6import androidx.compose.animation.scaleIn
15import androidx.compose.animation.scaleIn
7import androidx.compose.animation.scaleOut
16import androidx.compose.animation.scaleOut
17+import androidx.compose.foundation.ExperimentalFoundationApi
8import androidx.compose.foundation.background
18import androidx.compose.foundation.background
9import androidx.compose.foundation.clickable
19import androidx.compose.foundation.clickable
20+import androidx.compose.foundation.combinedClickable
10import androidx.compose.foundation.layout.Arrangement
21import androidx.compose.foundation.layout.Arrangement
11import androidx.compose.foundation.layout.Box
22import androidx.compose.foundation.layout.Box
12import androidx.compose.foundation.layout.BoxScope
23import androidx.compose.foundation.layout.BoxScope
13import androidx.compose.foundation.layout.Column
24import androidx.compose.foundation.layout.Column
14import androidx.compose.foundation.layout.Row
25import androidx.compose.foundation.layout.Row
26+import androidx.compose.foundation.layout.Spacer
15import androidx.compose.foundation.layout.fillMaxSize
27import androidx.compose.foundation.layout.fillMaxSize
16import androidx.compose.foundation.layout.fillMaxWidth
28import androidx.compose.foundation.layout.fillMaxWidth
29+import androidx.compose.foundation.layout.heightIn
17import androidx.compose.foundation.layout.PaddingValues
30import androidx.compose.foundation.layout.PaddingValues
31+import androidx.compose.foundation.layout.WindowInsets
32+import androidx.compose.foundation.layout.ime
18import androidx.compose.foundation.layout.imePadding
33import androidx.compose.foundation.layout.imePadding
19import androidx.compose.foundation.layout.padding
34import androidx.compose.foundation.layout.padding
20import androidx.compose.foundation.layout.size
35import androidx.compose.foundation.layout.size
21import androidx.compose.foundation.lazy.LazyColumn
36import androidx.compose.foundation.lazy.LazyColumn
22−import androidx.compose.foundation.lazy.items
37+import androidx.compose.foundation.lazy.itemsIndexed
23import androidx.compose.foundation.lazy.rememberLazyListState
38import androidx.compose.foundation.lazy.rememberLazyListState
24import androidx.compose.foundation.shape.CircleShape
39import androidx.compose.foundation.shape.CircleShape
40+import androidx.compose.foundation.shape.RoundedCornerShape
25import androidx.compose.foundation.text.KeyboardActions
41import androidx.compose.foundation.text.KeyboardActions
26import androidx.compose.foundation.text.KeyboardOptions
42import androidx.compose.foundation.text.KeyboardOptions
27import androidx.compose.material.icons.Icons
43import androidx.compose.material.icons.Icons
28import androidx.compose.material.icons.automirrored.filled.ArrowBack
44import androidx.compose.material.icons.automirrored.filled.ArrowBack
29import androidx.compose.material.icons.automirrored.filled.Send
45import androidx.compose.material.icons.automirrored.filled.Send
46+import androidx.compose.material.icons.filled.ChatBubbleOutline
30import androidx.compose.material.icons.filled.Close
47import androidx.compose.material.icons.filled.Close
31import androidx.compose.material.icons.filled.KeyboardArrowDown
48import androidx.compose.material.icons.filled.KeyboardArrowDown
49+import androidx.compose.material.icons.filled.KeyboardArrowUp
32import androidx.compose.material.icons.filled.Stop
50import androidx.compose.material.icons.filled.Stop
33import androidx.compose.material3.CircularProgressIndicator
51import androidx.compose.material3.CircularProgressIndicator
34import androidx.compose.material3.ExperimentalMaterial3Api
52import androidx.compose.material3.ExperimentalMaterial3Api
35import androidx.compose.material3.FilledIconButton
53import androidx.compose.material3.FilledIconButton
54+import androidx.compose.material3.FilledTonalButton
36import androidx.compose.material3.FloatingActionButton
55import androidx.compose.material3.FloatingActionButton
37import androidx.compose.material3.Icon
56import androidx.compose.material3.Icon
38import androidx.compose.material3.IconButton
57import androidx.compose.material3.IconButton
@@ -42,6 +61,7 @@ import androidx.compose.material3.OutlinedTextField
42import androidx.compose.material3.Scaffold
61import androidx.compose.material3.Scaffold
43import androidx.compose.material3.Surface
62import androidx.compose.material3.Surface
44import androidx.compose.material3.Text
63import androidx.compose.material3.Text
64+import androidx.compose.material3.TextButton
45import androidx.compose.material3.TopAppBar
65import androidx.compose.material3.TopAppBar
46import androidx.compose.runtime.Composable
66import androidx.compose.runtime.Composable
47import androidx.compose.runtime.LaunchedEffect
67import androidx.compose.runtime.LaunchedEffect
@@ -55,8 +75,13 @@ import androidx.compose.ui.Alignment
55import androidx.compose.ui.Modifier
75import androidx.compose.ui.Modifier
56import androidx.compose.ui.draw.clip
76import androidx.compose.ui.draw.clip
57import androidx.compose.ui.hapticfeedback.HapticFeedbackType
77import 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
58import androidx.compose.ui.platform.LocalHapticFeedback
81import androidx.compose.ui.platform.LocalHapticFeedback
82+import androidx.compose.ui.text.font.FontStyle
59import androidx.compose.ui.text.input.ImeAction
83import androidx.compose.ui.text.input.ImeAction
84+import androidx.compose.ui.text.style.TextAlign
60import androidx.compose.ui.text.style.TextOverflow
85import androidx.compose.ui.text.style.TextOverflow
61import androidx.compose.ui.unit.dp
86import androidx.compose.ui.unit.dp
62import kotlinx.coroutines.launch
87import kotlinx.coroutines.launch
@@ -64,11 +89,17 @@ import soy.iko.opencode.core.Event
64import soy.iko.opencode.core.UiState
89import soy.iko.opencode.core.UiState
65import soy.iko.opencode.ui.components.MessageBubble
90import soy.iko.opencode.ui.components.MessageBubble
66
91
67−@OptIn(ExperimentalMaterial3Api::class)
92+@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
68@Composable
93@Composable
69fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
94fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
70 val listState = rememberLazyListState()
95 val listState = rememberLazyListState()
71 val coroutineScope = rememberCoroutineScope()
96 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
72
103
73 // Show a jump-to-bottom button once the user scrolls up away from the latest
104 // Show a jump-to-bottom button once the user scrolls up away from the latest
74 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
105 // message. derivedStateOf keeps this from recomposing on every pixel of scroll —
@@ -82,6 +113,12 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
82 }
113 }
83 }
114 }
84
115
116+ // Offer a jump-to-top shortcut once the conversation is long and the user has
117+ // scrolled a few messages down — saves flick-scrolling back through history.
118+ val showScrollTop by remember {
119+ derivedStateOf { state.messages.size > 10 && listState.firstVisibleItemIndex > 3 }
120+ }
121+
85 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
122 // Track how many messages the user has "seen" (i.e. was at the bottom for). While
86 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
123 // they're scrolled up, any messages beyond that count are unseen — flag the FAB.
87 var lastSeenCount by remember { mutableStateOf(0) }
124 var lastSeenCount by remember { mutableStateOf(0) }
@@ -111,11 +148,20 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
111 topBar = {
148 topBar = {
112 TopAppBar(
149 TopAppBar(
113 title = {
150 title = {
151+ val title = state.currentSessionTitle.ifEmpty { "Chat" }
114 Text(
152 Text(
115− text = state.currentSessionTitle.ifEmpty { "Chat" },
153+ text = if (state.messages.isNotEmpty()) "$title (${state.messages.size})" else title,
116 maxLines = 1,
154 maxLines = 1,
117 overflow = TextOverflow.Ellipsis,
155 overflow = TextOverflow.Ellipsis,
156+ modifier = Modifier.combinedClickable(
118− modifier = Modifier.clickable { dispatch(Event.NavigateToSessions) },
157+ onClick = { dispatch(Event.NavigateToSessions) },
158+ onLongClick = {
159+ state.currentSessionId?.let { id ->
160+ copyToClipboard(context, id)
161+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
162+ }
163+ },
164+ ),
119 )
165 )
120 },
166 },
121 navigationIcon = {
167 navigationIcon = {
@@ -159,33 +205,78 @@ fun ChatScreen(state: UiState, dispatch: (Event) -> Unit) {
159 }
205 }
160 Box(Modifier.fillMaxWidth().weight(1f)) {
206 Box(Modifier.fillMaxWidth().weight(1f)) {
161 if (state.messages.isEmpty() && !state.loading) {
207 if (state.messages.isEmpty() && !state.loading) {
162− Text(
208+ Column(
163− text = "Send a message to start the conversation.",
164− style = MaterialTheme.typography.bodyMedium,
165− color = MaterialTheme.colorScheme.onSurfaceVariant,
166 modifier = Modifier.align(Alignment.Center).padding(32.dp),
209 modifier = Modifier.align(Alignment.Center).padding(32.dp),
210+ horizontalAlignment = Alignment.CenterHorizontally,
167− )
211+ ) {
212+ Icon(
213+ Icons.Filled.ChatBubbleOutline,
214+ contentDescription = null,
215+ modifier = Modifier.size(48.dp),
216+ tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
217+ )
218+ Spacer(Modifier.size(16.dp))
219+ Text(
220+ text = "Send a message to start the conversation.",
221+ style = MaterialTheme.typography.bodyMedium,
222+ color = MaterialTheme.colorScheme.onSurfaceVariant,
223+ textAlign = TextAlign.Center,
224+ )
225+ }
168 }
226 }
169 LazyColumn(
227 LazyColumn(
170 state = listState,
228 state = listState,
171 modifier = Modifier.fillMaxSize(),
229 modifier = Modifier.fillMaxSize(),
172 contentPadding = PaddingValues(vertical = 8.dp),
230 contentPadding = PaddingValues(vertical = 8.dp),
173 ) {
231 ) {
174− items(state.messages, key = { it.id }) { message ->
232+ itemsIndexed(state.messages, key = { _, message -> message.id }) { index, message ->
233+ // Insert a date separator whenever a message falls on a different
234+ // calendar day than the one before it (and above the first message).
235+ val previous = state.messages.getOrNull(index - 1)
236+ if (shouldShowDateSeparator(previous, message)) {
237+ DateSeparator(message.time)
238+ }
239+ val sameSenderAsPrevious = index > 0 && state.messages[index - 1].isUser == message.isUser
175− MessageBubble(message)
240+ MessageBubble(
241+ message,
242+ onRetry = { dispatch(Event.SendMessage(message.text)) },
243+ compactSpacing = sameSenderAsPrevious,
244+ )
245+ }
246+ // While the assistant is spinning up but hasn't emitted a streaming
247+ // message yet (only the user's message is present), show a typing
248+ // indicator so the wait doesn't look like a stall.
249+ if (state.generating && state.messages.none { it.streaming }) {
250+ item(key = "typing-indicator") {
251+ TypingIndicator()
252+ }
176 }
253 }
177 }
254 }
178 ScrollToBottomButton(
255 ScrollToBottomButton(
179− visible = showScrollButton,
256+ visible = showScrollButton && !isImeVisible,
180 showBadge = hasUnseenMessages,
257 showBadge = hasUnseenMessages,
181 onClick = {
258 onClick = {
182 coroutineScope.launch {
259 coroutineScope.launch {
183 if (state.messages.isNotEmpty()) {
260 if (state.messages.isNotEmpty()) {
261+ // When the typing indicator is showing it occupies the item
262+ // just past the last message, so scroll one further to reach it.
263+ val target = if (state.generating && state.messages.none { it.streaming })
264+ state.messages.size
265+ else
184− listState.animateScrollToItem(state.messages.size - 1)
266+ state.messages.size - 1
267+ listState.animateScrollToItem(target)
185 }
268 }
186 }
269 }
187 },
270 },
188 )
271 )
272+ ScrollToTopButton(
273+ visible = showScrollTop,
274+ onClick = {
275+ coroutineScope.launch {
276+ listState.animateScrollToItem(0)
277+ }
278+ },
279+ )
189 }
280 }
190 }
281 }
191 }
282 }
@@ -225,6 +316,123 @@ private fun BoxScope.ScrollToBottomButton(visible: Boolean, showBadge: Boolean,
225 }
316 }
226}
317}
227
318
319+// Mirror of ScrollToBottomButton, pinned to the top-start corner. Same BoxScope
320+// extension trick so the top-level AnimatedVisibility overload resolves cleanly.
321+@Composable
322+private fun BoxScope.ScrollToTopButton(visible: Boolean, onClick: () -> Unit) {
323+ AnimatedVisibility(
324+ visible = visible,
325+ modifier = Modifier.align(Alignment.TopStart),
326+ enter = scaleIn() + fadeIn(),
327+ exit = scaleOut() + fadeOut(),
328+ ) {
329+ Box(Modifier.padding(16.dp)) {
330+ FloatingActionButton(
331+ onClick = onClick,
332+ modifier = Modifier.size(44.dp),
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+
228@Composable
436@Composable
229private fun ReconnectingBanner() {
437private fun ReconnectingBanner() {
230 Surface(
438 Surface(
@@ -289,27 +497,70 @@ private fun ChatInputBar(
289 onStop: () -> Unit,
497 onStop: () -> Unit,
290) {
498) {
291 val haptic = LocalHapticFeedback.current
499 val haptic = LocalHapticFeedback.current
500+ val clipboardManager = LocalClipboardManager.current
292 Surface(tonalElevation = 3.dp) {
501 Surface(tonalElevation = 3.dp) {
293− Row(
502+ Column(
294 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
503 modifier = Modifier.fillMaxWidth().imePadding().padding(horizontal = 12.dp, vertical = 8.dp),
504+ ) {
505+ Row(
506+ modifier = Modifier.fillMaxWidth(),
295 verticalAlignment = Alignment.Bottom,
507 verticalAlignment = Alignment.Bottom,
296 horizontalArrangement = Arrangement.spacedBy(8.dp),
508 horizontalArrangement = Arrangement.spacedBy(8.dp),
297 ) {
509 ) {
298 OutlinedTextField(
510 OutlinedTextField(
299 value = draft,
511 value = draft,
300 onValueChange = onDraftChange,
512 onValueChange = onDraftChange,
301− modifier = Modifier.weight(1f),
513+ modifier = Modifier.weight(1f).heightIn(min = 48.dp),
302 enabled = !loading,
514 enabled = !loading,
303 placeholder = { Text("Message opencode…") },
515 placeholder = { Text("Message opencode…") },
304 maxLines = 5,
516 maxLines = 5,
517+ // Offer a quick way to wipe the draft once there's something to clear
518+ // and we're not mid-generation (where the field is a poor place to fuss).
519+ trailingIcon = if (draft.isNotEmpty() && !generating) {
520+ {
521+ IconButton(
522+ onClick = { onDraftChange("") },
523+ modifier = Modifier.size(20.dp),
524+ ) {
525+ Icon(
526+ Icons.Filled.Close,
527+ contentDescription = "Clear draft",
528+ modifier = Modifier.size(16.dp),
529+ )
530+ }
531+ }
532+ } else {
533+ null
534+ },
535+ // Surface a running count once the draft gets long, so the user has a
536+ // sense of scale before sending a wall of text.
537+ supportingText = if (draft.length > 500) {
538+ {
539+ Text(
540+ text = "${draft.length} characters",
541+ style = MaterialTheme.typography.labelSmall,
542+ color = MaterialTheme.colorScheme.onSurfaceVariant,
543+ textAlign = TextAlign.End,
544+ modifier = Modifier.fillMaxWidth(),
545+ )
546+ }
547+ } else {
548+ null
549+ },
305 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
550 keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
306 keyboardActions = KeyboardActions(onSend = {
551 keyboardActions = KeyboardActions(onSend = {
307 if (!generating && !loading && draft.isNotBlank()) onSend()
552 if (!generating && !loading && draft.isNotBlank()) onSend()
308 }),
553 }),
309 )
554 )
310 if (generating) {
555 if (generating) {
311− FilledIconButton(onClick = onStop) {
556+ FilledTonalButton(onClick = onStop) {
557+ Icon(
558+ Icons.Filled.Stop,
312− Icon(Icons.Filled.Stop, contentDescription = "Stop generating")
559+ contentDescription = null,
560+ modifier = Modifier.size(18.dp),
561+ )
562+ Spacer(Modifier.size(6.dp))
563+ Text("Stop")
313 }
564 }
314 } else {
565 } else {
315 FilledIconButton(
566 FilledIconButton(
@@ -323,5 +574,17 @@ private fun ChatInputBar(
323 }
574 }
324 }
575 }
325 }
576 }
577+ // With nothing typed yet, offer a one-tap way to drop in clipboard contents.
578+ if (draft.isEmpty() && !generating && !loading) {
579+ TextButton(
580+ onClick = {
581+ clipboardManager.getText()?.text?.let { onDraftChange(it) }
582+ },
583+ contentPadding = PaddingValues(0.dp),
584+ ) {
585+ Text("Paste")
586+ }
587+ }
588+ }
326 }
589 }
327}
590}
app/src/main/java/soy/iko/opencode/ui/screens/ConnectScreen.kt+49−2
@@ -101,6 +101,30 @@ 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+
104 if (state.authRequired) {
128 if (state.authRequired) {
105 Spacer(Modifier.height(12.dp))
129 Spacer(Modifier.height(12.dp))
106 OutlinedTextField(
130 OutlinedTextField(
@@ -131,7 +155,15 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
131 },
155 },
132 modifier = Modifier.fillMaxWidth(),
156 modifier = Modifier.fillMaxWidth(),
133 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
157 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Go),
134− keyboardActions = KeyboardActions(onGo = { dispatch(Event.Connect) }),
158+ keyboardActions = KeyboardActions(onGo = {
159+ // Mirror the connect button's enabled condition so the keyboard's
160+ // Go action can't fire a request the form isn't ready for.
161+ if (!state.loading && state.serverUrl.isNotBlank() &&
162+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank())
163+ ) {
164+ dispatch(Event.Connect)
165+ }
166+ }),
135 enabled = !state.loading,
167 enabled = !state.loading,
136 )
168 )
137 Spacer(Modifier.height(4.dp))
169 Spacer(Modifier.height(4.dp))
@@ -146,7 +178,10 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
146
178
147 Button(
179 Button(
148 onClick = { dispatch(Event.Connect) },
180 onClick = { dispatch(Event.Connect) },
181+ // When auth is required, keep the button disabled until at least one
182+ // credential is entered — otherwise it just triggers a validation error.
149− enabled = !state.loading && state.serverUrl.isNotBlank(),
183+ enabled = !state.loading && state.serverUrl.isNotBlank() &&
184+ (!state.authRequired || state.username.isNotBlank() || state.password.isNotBlank()),
150 modifier = Modifier.fillMaxWidth(),
185 modifier = Modifier.fillMaxWidth(),
151 ) {
186 ) {
152 if (state.loading) {
187 if (state.loading) {
@@ -160,6 +195,18 @@ fun ConnectScreen(state: UiState, dispatch: (Event) -> Unit) {
160 }
195 }
161 }
196 }
162
197
198+ // While connecting (including auto-connect on launch), echo the target URL
199+ // so the user knows what the spinner is waiting on.
200+ if (state.loading) {
201+ Spacer(Modifier.height(8.dp))
202+ Text(
203+ text = "Connecting to ${state.serverUrl}...",
204+ style = MaterialTheme.typography.bodySmall,
205+ color = MaterialTheme.colorScheme.onSurfaceVariant,
206+ textAlign = TextAlign.Center,
207+ )
208+ }
209+
163 // Surface the error inline as well, so it stays visible while the user
210 // Surface the error inline as well, so it stays visible while the user
164 // corrects the form (the snackbar is transient).
211 // corrects the form (the snackbar is transient).
165 if (state.error != null && !state.loading) {
212 if (state.error != null && !state.loading) {
app/src/main/java/soy/iko/opencode/ui/screens/SessionsScreen.kt+108−34
@@ -1,7 +1,13 @@
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
3import androidx.compose.foundation.background
8import androidx.compose.foundation.background
4import androidx.compose.foundation.clickable
9import androidx.compose.foundation.clickable
10+import androidx.compose.foundation.combinedClickable
5import androidx.compose.foundation.layout.Arrangement
11import androidx.compose.foundation.layout.Arrangement
6import androidx.compose.foundation.layout.Box
12import androidx.compose.foundation.layout.Box
7import androidx.compose.foundation.layout.Column
13import androidx.compose.foundation.layout.Column
@@ -15,6 +21,8 @@ import androidx.compose.foundation.layout.padding
15import androidx.compose.foundation.layout.size
21import androidx.compose.foundation.layout.size
16import androidx.compose.foundation.lazy.LazyColumn
22import androidx.compose.foundation.lazy.LazyColumn
17import androidx.compose.foundation.lazy.items
23import androidx.compose.foundation.lazy.items
24+import androidx.compose.foundation.lazy.rememberLazyListState
25+import androidx.compose.foundation.shape.CircleShape
18import androidx.compose.material.icons.Icons
26import androidx.compose.material.icons.Icons
19import androidx.compose.material.icons.automirrored.filled.ArrowBack
27import androidx.compose.material.icons.automirrored.filled.ArrowBack
20import androidx.compose.material.icons.filled.Add
28import androidx.compose.material.icons.filled.Add
@@ -50,8 +58,12 @@ import androidx.compose.runtime.remember
50import androidx.compose.runtime.setValue
58import androidx.compose.runtime.setValue
51import androidx.compose.ui.Alignment
59import androidx.compose.ui.Alignment
52import androidx.compose.ui.Modifier
60import androidx.compose.ui.Modifier
61+import androidx.compose.ui.draw.clip
62+import androidx.compose.ui.graphics.Color
53import androidx.compose.ui.hapticfeedback.HapticFeedbackType
63import androidx.compose.ui.hapticfeedback.HapticFeedbackType
64+import androidx.compose.ui.platform.LocalContext
54import androidx.compose.ui.platform.LocalHapticFeedback
65import androidx.compose.ui.platform.LocalHapticFeedback
66+import androidx.compose.ui.text.style.TextAlign
55import androidx.compose.ui.text.style.TextOverflow
67import androidx.compose.ui.text.style.TextOverflow
56import androidx.compose.ui.unit.dp
68import androidx.compose.ui.unit.dp
57import soy.iko.opencode.core.Event
69import soy.iko.opencode.core.Event
@@ -65,6 +77,15 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
65 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
77 var pendingDeleteId by remember { mutableStateOf<String?>(null) }
66 var isPullRefreshing by remember { mutableStateOf(false) }
78 var isPullRefreshing by remember { mutableStateOf(false) }
67 var searchQuery by remember { mutableStateOf("") }
79 var searchQuery by remember { mutableStateOf("") }
80+ val sessionsListState = rememberLazyListState()
81+
82+ // Bring a newly created session (which lands at the top of the list) into view.
83+ // Only scroll when the list actually grows, not on every reload of the same sessions.
84+ var prevSize by remember { mutableStateOf(state.sessions.size) }
85+ LaunchedEffect(state.sessions.size) {
86+ if (state.sessions.size > prevSize) sessionsListState.animateScrollToItem(0)
87+ prevSize = state.sessions.size
88+ }
68
89
69 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
90 // The pull-to-refresh spinner should only reflect a user-initiated pull, not
70 // every loading operation. Clear it once the underlying load completes.
91 // every loading operation. Clear it once the underlying load completes.
@@ -98,7 +119,23 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
98 Scaffold(
119 Scaffold(
99 topBar = {
120 topBar = {
100 TopAppBar(
121 TopAppBar(
101− title = { Text("Sessions") },
122+ title = {
123+ Row(verticalAlignment = Alignment.CenterVertically) {
124+ // A quick at-a-glance health dot for the SSE stream: green when
125+ // connected, error-tinted when the stream is down (updates stall).
126+ Box(
127+ modifier = Modifier
128+ .size(8.dp)
129+ .clip(CircleShape)
130+ .background(
131+ if (state.sseConnected) Color(0xFF4CAF50)
132+ else MaterialTheme.colorScheme.error,
133+ ),
134+ )
135+ Spacer(Modifier.size(8.dp))
136+ Text(if (state.sessions.isNotEmpty()) "Sessions (${state.sessions.size})" else "Sessions")
137+ }
138+ },
102 navigationIcon = {
139 navigationIcon = {
103 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
140 IconButton(onClick = { dispatch(Event.NavigateToConnect) }) {
104 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
141 Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Disconnect")
@@ -112,11 +149,15 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
112 )
149 )
113 },
150 },
114 floatingActionButton = {
151 floatingActionButton = {
152+ // Give the search results the full width while searching — the FAB would
153+ // otherwise cover the bottom rows and isn't relevant mid-search anyway.
154+ if (searchQuery.isEmpty()) {
115− ExtendedFloatingActionButton(
155+ ExtendedFloatingActionButton(
116− onClick = { dispatch(Event.CreateSession) },
156+ onClick = { dispatch(Event.CreateSession) },
117− icon = { Icon(Icons.Filled.Add, contentDescription = null) },
157+ icon = { Icon(Icons.Filled.Add, contentDescription = null) },
118− text = { Text("New session") },
158+ text = { Text("New session") },
119− )
159+ )
160+ }
120 },
161 },
121 ) { padding ->
162 ) { padding ->
122 Column(Modifier.fillMaxSize().padding(padding)) {
163 Column(Modifier.fillMaxSize().padding(padding)) {
@@ -158,32 +199,37 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
158 state = rememberPullToRefreshState(),
199 state = rememberPullToRefreshState(),
159 ) {
200 ) {
160 LazyColumn(
201 LazyColumn(
202+ state = sessionsListState,
161 modifier = Modifier.fillMaxSize(),
203 modifier = Modifier.fillMaxSize(),
162 contentPadding = PaddingValues(bottom = 88.dp),
204 contentPadding = PaddingValues(bottom = 88.dp),
163 ) {
205 ) {
164 items(filteredSessions, key = { it.id }) { session ->
206 items(filteredSessions, key = { it.id }) { session ->
207+ // animateItem() slides the remaining rows into place when one is
208+ // deleted (and fades new rows in) instead of snapping instantly.
209+ Column(modifier = Modifier.animateItem()) {
165− val dismissState = rememberSwipeToDismissBoxState(
210+ val dismissState = rememberSwipeToDismissBoxState(
166− // Only a swipe from the end (right-to-left) triggers deletion;
211+ // Only a swipe from the end (right-to-left) triggers deletion;
167− // return false so the row snaps back and the confirm dialog decides.
212+ // return false so the row snaps back and the confirm dialog decides.
168− confirmValueChange = { value ->
213+ confirmValueChange = { value ->
169− if (value == SwipeToDismissBoxValue.EndToStart) {
214+ if (value == SwipeToDismissBoxValue.EndToStart) {
170− pendingDeleteId = session.id
215+ pendingDeleteId = session.id
171− }
172− false
173− },
216+ }
174− )
217+ false
175− SwipeToDismissBox(
218+ },
176− state = dismissState,
177− enableDismissFromStartToEnd = false,
178− backgroundContent = { SwipeDeleteBackground() },
179− ) {
180− SessionRow(
181− session = session,
182− onOpen = { dispatch(Event.SelectSession(session.id)) },
183− onDelete = { pendingDeleteId = session.id },
184 )
219 )
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))
185 }
232 }
186− HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f))
187 }
233 }
188 }
234 }
189 }
235 }
@@ -192,13 +238,21 @@ fun SessionsScreen(state: UiState, dispatch: (Event) -> Unit) {
192 }
238 }
193}
239}
194
240
241+@OptIn(ExperimentalFoundationApi::class)
195@Composable
242@Composable
196private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
243private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () -> Unit) {
244+ val context = LocalContext.current
197 Row(
245 Row(
198 modifier = Modifier
246 modifier = Modifier
199 .fillMaxWidth()
247 .fillMaxWidth()
200 .background(MaterialTheme.colorScheme.surface)
248 .background(MaterialTheme.colorScheme.surface)
249+ .combinedClickable(
201− .clickable(onClick = onOpen)
250+ onClick = onOpen,
251+ onLongClick = {
252+ copyToClipboard(context, session.id)
253+ Toast.makeText(context, "Session ID copied", Toast.LENGTH_SHORT).show()
254+ },
255+ )
202 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
256 .padding(start = 20.dp, end = 8.dp, top = 14.dp, bottom = 14.dp),
203 verticalAlignment = Alignment.CenterVertically,
257 verticalAlignment = Alignment.CenterVertically,
204 ) {
258 ) {
@@ -233,13 +287,13 @@ private fun SessionRow(session: SessionView, onOpen: () -> Unit, onDelete: () ->
233 Icon(
287 Icon(
234 Icons.Filled.DeleteOutline,
288 Icons.Filled.DeleteOutline,
235 contentDescription = "Delete session",
289 contentDescription = "Delete session",
236− tint = MaterialTheme.colorScheme.onSurfaceVariant,
290+ tint = MaterialTheme.colorScheme.error,
237 )
291 )
238 }
292 }
239 }
293 }
240}
294}
241
295
242−/** Red background with a trailing delete icon, revealed while swiping a session row away. */
296+/** Red background with a trailing delete icon and label, revealed while swiping a session row away. */
243@Composable
297@Composable
244private fun SwipeDeleteBackground() {
298private fun SwipeDeleteBackground() {
245 Box(
299 Box(
@@ -249,11 +303,19 @@ private fun SwipeDeleteBackground() {
249 .padding(horizontal = 24.dp),
303 .padding(horizontal = 24.dp),
250 contentAlignment = Alignment.CenterEnd,
304 contentAlignment = Alignment.CenterEnd,
251 ) {
305 ) {
306+ Row(verticalAlignment = Alignment.CenterVertically) {
252− Icon(
307+ Icon(
253− Icons.Filled.DeleteOutline,
308+ Icons.Filled.DeleteOutline,
254− contentDescription = null,
309+ contentDescription = null,
255− tint = MaterialTheme.colorScheme.onError,
310+ tint = MaterialTheme.colorScheme.onError,
256− )
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+ }
257 }
319 }
258}
320}
259
321
@@ -283,6 +345,11 @@ private fun ReconnectingBanner() {
283 }
345 }
284}
346}
285
347
348+private fun copyToClipboard(context: Context, text: String) {
349+ val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
350+ clipboard.setPrimaryClip(ClipData.newPlainText("session", text))
351+}
352+
286/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
353/** Shorten a session ID for display: "abc12345…" instead of the full UUID. */
287private fun shortSessionId(id: String): String =
354private fun shortSessionId(id: String): String =
288 if (id.length > 12) id.take(8) + "…" else id
355 if (id.length > 12) id.take(8) + "…" else id
@@ -324,5 +391,12 @@ private fun EmptySessions() {
324 style = MaterialTheme.typography.bodyMedium,
391 style = MaterialTheme.typography.bodyMedium,
325 color = MaterialTheme.colorScheme.onSurfaceVariant,
392 color = MaterialTheme.colorScheme.onSurfaceVariant,
326 )
393 )
394+ Spacer(Modifier.height(8.dp))
395+ Text(
396+ text = "Sessions you create on this server will appear here.",
397+ style = MaterialTheme.typography.bodySmall,
398+ color = MaterialTheme.colorScheme.onSurfaceVariant,
399+ textAlign = TextAlign.Center,
400+ )
327 }
401 }
328}
402}
app/src/main/java/soy/iko/opencode/ui/theme/Theme.kt+23−1
@@ -14,7 +14,18 @@ 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),
17 secondary = EmeraldDark,
19 secondary = EmeraldDark,
20+ onSecondary = Color(0xFFE6E9EF),
21+ secondaryContainer = Color(0xFF1A2A3D),
22+ onSecondaryContainer = Color(0xFFA8C5E6),
23+ tertiary = Color(0xFF6B7280),
24+ onTertiary = Color(0xFFE6E9EF),
25+ tertiaryContainer = Color(0xFF2A2A3D),
26+ onTertiaryContainer = Color(0xFFC5C5E6),
27+ errorContainer = Color(0xFF4D2626),
28+ onErrorContainer = Color(0xFFFFB4B4),
18 background = DarkBackground,
29 background = DarkBackground,
19 surface = DarkSurface,
30 surface = DarkSurface,
20 surfaceVariant = DarkSurfaceVariant,
31 surfaceVariant = DarkSurfaceVariant,
@@ -24,7 +35,18 @@ private val DarkColors = darkColorScheme(
24
35
25private val LightColors = lightColorScheme(
36private val LightColors = lightColorScheme(
26 primary = EmeraldDark,
37 primary = EmeraldDark,
38+ primaryContainer = Color(0xFFD7F5E3),
39+ onPrimaryContainer = Color(0xFF0A3D22),
27 secondary = Emerald,
40 secondary = Emerald,
41+ onSecondary = Color(0xFF1A1C1F),
42+ secondaryContainer = Color(0xFFD7E8F5),
43+ onSecondaryContainer = Color(0xFF0A2A4D),
44+ tertiary = Color(0xFF6B7280),
45+ onTertiary = Color(0xFFFFFFFF),
46+ tertiaryContainer = Color(0xFFE8E8F5),
47+ onTertiaryContainer = Color(0xFF2A2A4D),
48+ errorContainer = Color(0xFFFFE0E0),
49+ onErrorContainer = Color(0xFF660000),
28 background = LightBackground,
50 background = LightBackground,
29 surface = LightSurface,
51 surface = LightSurface,
30 surfaceVariant = LightSurfaceVariant,
52 surfaceVariant = LightSurfaceVariant,
@@ -35,7 +57,7 @@ private val LightColors = lightColorScheme(
35@Composable
57@Composable
36fun OpencodeTheme(
58fun OpencodeTheme(
37 darkTheme: Boolean = isSystemInDarkTheme(),
59 darkTheme: Boolean = isSystemInDarkTheme(),
38− dynamicColor: Boolean = true,
60+ dynamicColor: Boolean = false,
39 content: @Composable () -> Unit,
61 content: @Composable () -> Unit,
40) {
62) {
41 val context = LocalContext.current
63 val context = LocalContext.current
shared/src/app.rs+14
@@ -297,16 +297,27 @@ 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.
300 Event::ServerUrlChanged(url) => {
302 Event::ServerUrlChanged(url) => {
301 model.server_url = url;
303 model.server_url = url;
304+ if model.error.is_some() {
305+ model.error = None;
306+ }
302 render()
307 render()
303 }
308 }
304 Event::UsernameChanged(u) => {
309 Event::UsernameChanged(u) => {
305 model.username = u;
310 model.username = u;
311+ if model.error.is_some() {
312+ model.error = None;
313+ }
306 render()
314 render()
307 }
315 }
308 Event::PasswordChanged(p) => {
316 Event::PasswordChanged(p) => {
309 model.password = p;
317 model.password = p;
318+ if model.error.is_some() {
319+ model.error = None;
320+ }
310 render()
321 render()
311 }
322 }
312
323
@@ -341,6 +352,9 @@ impl App for OpencodeApp {
341 title: display_title(&s.title),
352 title: display_title(&s.title),
342 })
353 })
343 .collect();
354 .collect();
355+ // Impose a stable alphabetical order so the list doesn't shuffle
356+ // with whatever order the server happens to return sessions in.
357+ model.sessions.sort_by_key(|s| s.title.to_lowercase());
344 }
358 }
345 Err(e) => model.error = Some(e),
359 Err(e) => model.error = Some(e),
346 }
360 }