From 0718f5ba6f45c939146a36eafc66ba87f683f585 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 12:43:37 +0100 Subject: [PATCH 1/8] Add the Chat destination and hold several conversations at once Entry point: the floating destination pill gains a Chat icon between Runs and Settings; it stays a single non-wrapping Row of 48dp targets using the named DESTINATION_ITEM_SIZE/DESTINATION_ITEM_GAP tokens, clear of the existing 88dp reserve, so it stays narrow however many destinations it holds. Protocol/transport: new data/protocol/Chat.kt mirrors the brokered chat wire shapes; Message gains the optional chat_* payloads, PipelinesClient forwards unsolicited frames (chat_event/chat_permission) to a new events flow instead of dropping them, and PipelinesRepository exposes the typed chat calls (sessions, create, messages, prompt, interrupt, reply). State: ui/chat/ChatStore.kt is an Android-free multi-chat holder; every open chat keeps its own conversation, running flag, composer draft and scroll position, open/activate report when history must be re-synced so a running session refreshes on return instead of showing a stale copy, and busy/read-only sessions refuse writes. Surface: ui/chat/ChatScreen.kt lists the server's sessions with running/busy/ read-only status and an open-chat strip to switch between conversations (chip X closes only that chat); the conversation is a bottom-anchored transcript of user bubbles, reasoning, assistant text and tool-call chips that expand to INPUT (pretty JSON)/OUTPUT (monospace), edit-family calls render a diff card derived from oldString/newString, and pending chat_permission frames surface an approval bar answered via chat_reply. New chat creates and opens a session. The manifest sets windowSoftInputMode=adjustResize for the composer. Tests: ChatProtocolTest, ChatFormatTest and MultiChatStateTest cover the wire shapes, formatting and the multi-chat model (switching preserves each conversation, a running session re-syncs on return, per-chat drafts/scroll, busy read-only, background events land on their chat). README documents the slice and its evidence. --- android/README.md | 132 ++++ android/app/src/main/AndroidManifest.xml | 1 + .../pipelines/data/PipelinesRepository.kt | 76 ++ .../net/awan/pipelines/data/protocol/Chat.kt | 198 +++++ .../awan/pipelines/data/protocol/Message.kt | 22 + .../data/transport/PipelinesClient.kt | 19 +- .../net/awan/pipelines/ui/AppViewModel.kt | 141 ++++ .../net/awan/pipelines/ui/PipelinesApp.kt | 18 +- .../net/awan/pipelines/ui/chat/ChatFormat.kt | 166 ++++ .../net/awan/pipelines/ui/chat/ChatScreen.kt | 747 ++++++++++++++++++ .../net/awan/pipelines/ui/chat/ChatStore.kt | 336 ++++++++ .../data/protocol/ChatProtocolTest.kt | 221 ++++++ .../awan/pipelines/ui/chat/ChatFormatTest.kt | 103 +++ .../pipelines/ui/chat/MultiChatStateTest.kt | 217 +++++ 14 files changed, 2392 insertions(+), 5 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt diff --git a/android/README.md b/android/README.md index 03a6d41e..187a8d42 100644 --- a/android/README.md +++ b/android/README.md @@ -2227,3 +2227,135 @@ native 2208x1840 @420 at the end. returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, `Content-Length: 17928873`. + +## Chat destination and multiple conversations (16 Oct 2026) + +The first Chat slice: the destination, the server session list and several +conversations held open at once. `android/` only; no new dependency (the +`material-icons-extended` icon is the declared one), no Pipelines server/Go/ +installer/Docker file touched, no run started from the app, and the operator's +physical device was never used (`emulator-5556` only). + +- **Pill.** The floating destination pill gains a Chat icon between Runs and + Settings (icons only, 48dp targets via the named `DESTINATION_ITEM_SIZE`/ + `DESTINATION_ITEM_GAP` tokens, one non-wrapping `Row`), so it stays narrow and + clear of the reserved 88dp bottom inset however many destinations it holds. + The Search destination is owned by another lane and is not present on this + base; the pill is built to take it. +- **Brokered protocol.** `data/protocol/Chat.kt` mirrors `internal/protocol/chat.go` + field-for-field (sessions, create, query, prompt, messages/parts, event frames, + permission, reply); `Message` gains the optional `chat_*` payloads and + `PipelinesClient` now forwards *unsolicited* frames (chat_event/chat_permission) + to `events` instead of dropping them. `PipelinesRepository` exposes the typed + chat calls. +- **Multi-chat model.** `ui/chat/ChatStore.kt` is an Android-free state holder: + every open chat keeps its own conversation, running flag, composer draft and + scroll position; `open`/`activate` report when history must be (re-)fetched so + a running session re-syncs on return instead of showing a stale copy; a + server frame is applied to its chat whether or not it is on screen. `busy` + sessions render read-only and the composer refuses to write to them. +- **Surface.** `ui/chat/ChatScreen.kt` reuses the shared adaptive + `SlidingPaneStack` (session list → conversation): the list shows each session's + running/busy/read-only status, an open-chat strip switches between several + conversations in one tap (with an optional X to close one), and the + conversation is a bottom-anchored transcript of user bubbles, secondary + reasoning, assistant text and tool-call chips that expand to INPUT + (pretty-printed JSON) / OUTPUT (monospace, via the shared `CodeBlock`). + "New chat" creates a server session and opens it. Closing a chat *is* provided + (the chip X); it removes only that chat. +- **Messages sent to a chat are optimistic** (the bubble shows immediately); the + live delta/streaming pass is the next slice. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --rerun-tasks` → + `BUILD SUCCESSFUL`, **229 tests, 0 failures** (new `MultiChatStateTest`: + switching preserves each conversation, a running session re-syncs on return, + drafts and scroll are per chat, a busy session is read-only, background events + land on their own chat; new `ChatProtocolTest` for the wire shapes; new + `ChatFormatTest`). +- The debug APK was installed on `emulator-5556` (`FoldB_API_36`, narrow + `wm size 1080x2340` @420) and driven with `uiautomator dump`/`input tap`; + captures were validated with `android/scripts/capture_png.sh -s emulator-5556`: + the pill with the Chat destination (`01_pill_chat`), the session list + (`02_chat_list`, `05_chat_list_one_open`, `07_chat_list_two_open`), two chats + with different conversations (`03_chat_alpha` and `06_chat_beta`), a tool chip + expanded to INPUT/OUTPUT (`04_chat_alpha_tool_expanded`), a read-only busy + session with a disabled composer (`08_chat_readonly`) and a per-chat draft + preserved across a switch (`10_draft_preserved`). `adb -s emulator-5556 logcat + -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **The deployed Pipelines server predates chat** (verified: a `chat_sessions` + request answers `unknown command: chat_sessions`), and the server-side chat + broker is a separate lane. The on-emulator sweep therefore drove the client + against `chat_stub.py`, a minimal `/connect` WebSocket double that speaks the + exact `internal/protocol/chat.go` JSON, so the screenshots show real client + rendering of the documented wire contract, not the production service. +- **APK publish.** `app-debug.apk` (18,261,008 bytes, sha256 + `aa167617c830fd7249eedf457959ef7e99b553769ed4ab82a3af6b4e8cb98ed3`) copied to + `~/.local/share/pipelines/data/artifacts/119/1/pipelines-debug-wip-e5bde98.apk`; + `curl -I http://10.0.0.249:8080/artifacts/119/1/pipelines-debug-wip-e5bde98.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18261008`; a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (not deployed and out of +this lane's scope), a genuinely running session's re-sync against OpenCode +(covered by the model test, not live), and streaming/stop/approval/attachments, +which are later slices. + +### Review follow-ups (16 Oct 2026, implementer pass) + +Addressing the reviewer's findings on the slice above, still `android/` only. + +- **Shared part upsert (duplication blocker).** `ChatStore.applyDelta` and + `applyTool` were the same message/part upsert twice. Both now call one private + `upsertPart(frame, partId) { existing -> … }`; the delta appends to the existing + text, the tool replaces the part, and neither can drift. `event()` and the new + `permission()` share one `ensureThread()` placeholder creator. +- **Diff cards (task gap).** The research report's edit view (`_CodeRun` / + `_DiffView`, §1.3) is now reproduced: an `edit`-family tool call renders a diff + card. `ChatFormat.toolEditDiff` derives an LCS line diff from the arguments' + `oldString`/`newString` — the brokered protocol has **no** diff field (research + §2.5), so it is synthesised, never silently dropped. The collapsed chip shows + the file and the `+N -M` stat; expanding shows the green/red monospace lines + (the app's own success/failure hues, not new literals). +- **One read-only rule (divergent code).** `sessionReadOnly` was dead (only its + own test called it) and disagreed with the UI's `ChatThread.readOnly = busy` for + a locally-running busy session. The helper is deleted and `ChatThread.readOnly` + is now `busy && !running`, the same precedence `sessionStatusLabel` uses: a turn + we started is `Running` and writable, not read-only. +- **`chatReply` / approval now reachable (unused API).** `observeChatEvents` + forwards `chat_permission` into `ChatStore.permission` instead of dropping it, + the conversation shows an approval bar (action, resources, Allow once / Always / + Deny) and `AppViewModel.replyChatPermission` answers through `chatReply`. +- **Stop control fixed (found while tracing read-only).** While a turn ran the + composer's red stop button was wired to `onSend`, so it sent the draft instead + of interrupting; it now calls `stopChat`. +- **Evidence gap closed.** The previous checklist cited `09` (new chat) but no + `09_*` file existed; this pass captures `09_new_chat.png` (the New-chat + conversation), plus `11_diff_card.png` and `12_permission_bar.png` for the two + new surfaces. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD + SUCCESSFUL`; the JUnit XML totals **233 tests, 0 failures, 0 errors, 0 + skipped** (new `toolEditDiffMarksOnlyChangedLinesAndCountsThem`, + `toolEditDiffIsNullForNonEdits`, `locallyRunningBusyChatStaysWritable`, + `permissionIsStoredUntilAnswered`). +- The debug APK was installed on `emulator-5556` only and driven with + `uiautomator dump`/`input tap`; captures validated with + `android/scripts/capture_png.sh -s emulator-5556`: the new-chat conversation + (`09_new_chat`), the derived diff (`11_diff_card`, showing + `context / - val gap = 4.dp / + val gap = 6.dp / + val inset = 2.dp` under a + `src/layout.kt +2 -1` chip) and the approval bar (`12_permission_bar`). Tapping + **Allow once** cleared the bar through `chat_reply`. `adb -s emulator-5556 + logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime`. Driven against the + test-double stub (the deployed server still predates chat). +- **APK publish.** `app-debug.apk` (18,228,844 bytes, sha256 + `db240fc2fc295c5ab50530f9d8cefae908f307a3115b54ce9f6d713e05643b87`) copied to + `~/.local/share/pipelines/data/artifacts/119/3/pipelines-debug-wip-e5bde98.apk`. + +Still not verified: the live brokered server (separate lane), streaming against +real OpenCode, and attachments — unchanged from the pass above. diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 1aae23c0..f7bb3780 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -22,6 +22,7 @@ android:name=".MainActivity" android:exported="true" android:label="@string/app_name" + android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.Pipelines"> diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 7ddf2975..07e7f88f 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -2,8 +2,15 @@ package net.awan.pipelines.data import java.util.UUID import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.flow.SharedFlow import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.JsonElement +import net.awan.pipelines.data.protocol.ChatCreateRequest +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPromptRequest +import net.awan.pipelines.data.protocol.ChatQuery +import net.awan.pipelines.data.protocol.ChatReplyRequest +import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.Message import net.awan.pipelines.data.protocol.PipelineDetail import net.awan.pipelines.data.protocol.PipelineSummary @@ -31,6 +38,9 @@ class PipelinesRepository( ) { val connectionState = client.state + /** Server-pushed chat frames (chat_event / chat_permission), with no request id. */ + val events: SharedFlow = client.events + /** Opens the single shared connection to a validated server URL. */ fun connect(validated: ServerUrl.Validated) = client.connect(validated) @@ -118,6 +128,72 @@ class PipelinesRepository( Message(type = Protocol.RETRY_RUN, runId = id, requestKey = requestKey), ).runDetail ?: throw ProtocolException("The server returned no run detail.") + // ---- Brokered OpenCode chat (route B): the phone never speaks OpenCode + // directly and never holds its credentials. ---- + + /** Lists the sessions this server owns, with the `busy` flag the phone renders read-only. */ + suspend fun chatSessions(): List = + client.call(Message(type = Protocol.CHAT_SESSIONS)).chatSessions ?: emptyList() + + /** + * Creates a session and returns it. The server currently answers this type + * with an explicit error when it does not broker creation; the caller + * surfaces that message rather than guessing at a session id. + */ + suspend fun chatCreate(title: String, directory: String): ChatSession { + val response = client.call( + Message( + type = Protocol.CHAT_CREATE, + chatCreate = ChatCreateRequest(title = title, directory = directory), + ), + ) + return response.chatSession + ?: throw ProtocolException("The server did not return the new chat session.") + } + + /** Loads a session's stored turns; the server prefers its retained live state. */ + suspend fun chatMessages(sessionId: String, limit: Int = 0): List { + if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.") + return client.call( + Message(type = Protocol.CHAT_MESSAGES, chatQuery = ChatQuery(sessionId = sessionId, limit = limit)), + ).chatMessages ?: emptyList() + } + + /** Sends one prompt; the server echoes an ack and then pushes chat_event frames. */ + suspend fun chatPrompt(sessionId: String, text: String) { + if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.") + val trimmed = text.trim() + if (trimmed.isEmpty()) throw ProtocolException("Enter a message before sending.") + client.call( + Message( + type = Protocol.CHAT_PROMPT, + chatPrompt = ChatPromptRequest(sessionId = sessionId, text = trimmed), + ), + ) + } + + suspend fun chatInterrupt(sessionId: String) { + if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.") + client.call(Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))) + } + + suspend fun chatReply(sessionId: String, requestId: String, decision: String, message: String = "") { + if (sessionId.isBlank() || requestId.isBlank()) { + throw ProtocolException("A pending permission request is required.") + } + client.call( + Message( + type = Protocol.CHAT_REPLY, + chatReply = ChatReplyRequest( + sessionId = sessionId, + requestId = requestId, + decision = decision, + message = message, + ), + ), + ) + } + private fun requireConfigured() { if (settings.serverUrl.value.isBlank()) { throw NotConnectedException("Set the Pipelines server URL in Settings first.") diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt new file mode 100644 index 00000000..8d461c8e --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt @@ -0,0 +1,198 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject + +/** + * Brokered OpenCode chat wire types (route B in the research report): the phone + * talks only to `/connect` and the server holds the OpenCode credentials, + * translating each type below. The field names and JSON tags mirror + * `internal/protocol/chat.go` exactly so the two cannot drift. + * + * Every list/field is optional with a default, so an older peer or a partial + * envelope never crashes the client. + */ +@Serializable +data class ChatSession( + val id: String = "", + val title: String = "", + val agent: String = "", + val model: String = "", + val directory: String = "", + @SerialName("parent_id") val parentId: String = "", + @SerialName("created_at") val createdAt: Long = 0, + @SerialName("updated_at") val updatedAt: Long = 0, + // Another client holds the session, or the server itself owns it as an active + // run: the phone shows it read-only instead of letting two clients write the + // same conversation. + val busy: Boolean = false, +) + +@Serializable +data class ChatCreateRequest( + val title: String = "", + val directory: String = "", +) + +/** The session-scoped request body for chat_messages and chat_interrupt. */ +@Serializable +data class ChatQuery( + @SerialName("session_id") val sessionId: String = "", + val limit: Int = 0, +) + +@Serializable +data class ChatPromptRequest( + @SerialName("session_id") val sessionId: String = "", + val text: String = "", + val model: String = "", + val agent: String = "", + val files: List = emptyList(), +) + +/** One stored turn: a user turn is a single text part, an assistant turn holds text/reasoning/tool parts. */ +@Serializable +data class ChatMessage( + val id: String = "", + @SerialName("session_id") val sessionId: String = "", + val role: String = "", + val model: String = "", + val agent: String = "", + @SerialName("created_at") val createdAt: Long = 0, + val parts: List = emptyList(), +) + +/** One element of a [ChatMessage]; [type] selects which fields are meaningful. */ +@Serializable +data class ChatPart( + val type: String = "", + val id: String = "", + val text: String = "", + val name: String = "", + val executed: Boolean = false, + val state: ChatToolState? = null, + val time: ChatTime? = null, +) + +/** The lifecycle of a tool call; [input] is a partial-JSON string while streaming, an object afterwards. */ +@Serializable +data class ChatToolState( + val status: String = "", + val input: JsonElement? = null, + val content: List = emptyList(), + val metadata: JsonObject? = null, + val error: ChatError? = null, +) + +@Serializable +data class ChatToolContent( + val type: String = "", + val text: String = "", + val uri: String = "", + val mime: String = "", + val name: String = "", +) + +@Serializable +data class ChatError( + val type: String = "", + val message: String = "", +) + +/** Epoch-millisecond timing envelope of a tool call. */ +@Serializable +data class ChatTime( + val created: Long = 0, + val ran: Long = 0, + val completed: Long = 0, +) + +/** + * A server-pushed chat_event frame. [kind] selects the payload: text/reasoning + * carry an incremental [delta] for the target [part], tool carries a full [part], + * step marks turn progress and usage reports the turn totals. + */ +@Serializable +data class ChatEventFrame( + @SerialName("session_id") val sessionId: String = "", + @SerialName("message_id") val messageId: String = "", + val kind: String = "", + val delta: String = "", + val part: ChatPart? = null, + val step: ChatStep? = null, + val usage: ChatUsage? = null, +) + +@Serializable +data class ChatStep( + val status: String = "", + val index: Int = 0, +) + +@Serializable +data class ChatUsage( + @SerialName("input_tokens") val inputTokens: Int = 0, + @SerialName("output_tokens") val outputTokens: Int = 0, + val cost: Double = 0.0, +) + +/** One pending OpenCode approval request the phone answers with chat_reply. */ +@Serializable +data class ChatPermissionFrame( + @SerialName("session_id") val sessionId: String = "", + @SerialName("request_id") val requestId: String = "", + val action: String = "", + val resources: List = emptyList(), + val save: List = emptyList(), + val metadata: JsonObject? = null, + val source: ChatPermissionSource? = null, + val message: String = "", +) + +@Serializable +data class ChatPermissionSource( + val type: String = "", + @SerialName("message_id") val messageId: String = "", + val id: String = "", +) + +@Serializable +data class ChatReplyRequest( + @SerialName("session_id") val sessionId: String = "", + @SerialName("request_id") val requestId: String = "", + val decision: String = "", + val message: String = "", +) + +/** Chat part/kind/state/reply constants, mirroring `internal/protocol/chat.go`. */ +object ChatProtocol { + const val PART_TEXT = "text" + const val PART_REASONING = "reasoning" + const val PART_TOOL = "tool" + + const val EVENT_STEP = "step" + const val EVENT_USAGE = "usage" + + const val STEP_STARTED = "started" + const val STEP_ENDED = "ended" + + const val TOOL_STREAMING = "streaming" + const val TOOL_RUNNING = "running" + const val TOOL_COMPLETED = "completed" + const val TOOL_ERROR = "error" + + const val ROLE_USER = "user" + const val ROLE_ASSISTANT = "assistant" + + const val DECISION_ONCE = "once" + const val DECISION_ALWAYS = "always" + const val DECISION_REJECT = "reject" + + /** A tool call still in flight (no result or error yet). */ + fun toolRunning(state: ChatToolState?): Boolean = when (state?.status) { + TOOL_STREAMING, TOOL_RUNNING -> true + else -> false + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt index 6f07efc3..9914e29e 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Message.kt @@ -41,6 +41,17 @@ object Protocol { const val GET_STATUS = "get_status" const val STATUS = "status" + // chat.go (brokered OpenCode chat) + const val CHAT_SESSIONS = "chat_sessions" + const val CHAT_CREATE = "chat_create" + const val CHAT_PROMPT = "chat_prompt" + const val CHAT_MESSAGES = "chat_messages" + const val CHAT_INTERRUPT = "chat_interrupt" + const val CHAT_REPLY = "chat_reply" + // Server-pushed frames with no matching request. + const val CHAT_EVENT = "chat_event" + const val CHAT_PERMISSION = "chat_permission" + // terminals.go const val SUCCESS_END = "#success" const val FAILURE_END = "#failure" @@ -411,4 +422,15 @@ data class Message( @SerialName("write_paths") val writePaths: List? = null, @SerialName("request_key") val requestKey: String? = null, val workspace: String? = null, + // Brokered chat traffic (see Chat.kt). Optional so an older server never + // breaks the existing envelope. + @SerialName("chat_sessions") val chatSessions: List? = null, + @SerialName("chat_session") val chatSession: ChatSession? = null, + @SerialName("chat_create") val chatCreate: ChatCreateRequest? = null, + @SerialName("chat_query") val chatQuery: ChatQuery? = null, + @SerialName("chat_prompt") val chatPrompt: ChatPromptRequest? = null, + @SerialName("chat_messages") val chatMessages: List? = null, + @SerialName("chat_event") val chatEvent: ChatEventFrame? = null, + @SerialName("chat_permission") val chatPermission: ChatPermissionFrame? = null, + @SerialName("chat_reply") val chatReply: ChatReplyRequest? = null, ) diff --git a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt index b4a8d9f1..89a5892e 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/transport/PipelinesClient.kt @@ -10,8 +10,11 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex @@ -53,6 +56,15 @@ class PipelinesClient( private val _state = MutableStateFlow(ConnectionState.Idle) val state: StateFlow = _state.asStateFlow() + // Unsolicited server frames (server-pushed chat_event / chat_permission / + // stream errors). Buffered and dropped-oldest so a slow collector can never + // block the socket read loop; chats re-sync from history after a gap anyway. + private val _events = MutableSharedFlow( + extraBufferCapacity = 256, + onBufferOverflow = kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST, + ) + val events: SharedFlow = _events.asSharedFlow() + private val sendLock = Mutex() private val pending = ConcurrentHashMap>() private val sequence = AtomicLong(0) @@ -190,9 +202,12 @@ class PipelinesClient( val deferred = if (id != null) pending.remove(id) else null if (deferred != null) { deferred.complete(message) + } else { + // Unsolicited envelopes (the connection's initial pipeline_list, + // server-pushed chat frames, stream errors) carry no matching id: + // hand them to the event stream instead of dropping them. + _events.tryEmit(message) } - // Unsolicited envelopes (for example the connection's initial - // pipeline_list) have no matching id and are intentionally dropped. } override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index d29e9ea8..59dd52a0 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -19,12 +19,15 @@ import net.awan.pipelines.data.PipelinesRepository import net.awan.pipelines.data.RunHistory import net.awan.pipelines.data.SettingsRepository import net.awan.pipelines.data.protocol.BuildInfo +import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.PipelineDetail import net.awan.pipelines.data.protocol.PipelineSummary import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.transport.ConnectionState import net.awan.pipelines.data.transport.ServerUrl +import net.awan.pipelines.ui.chat.ChatState +import net.awan.pipelines.ui.chat.ChatStore /** Generic loading/empty/error/data state used by every screen. */ data class LoadState( @@ -95,6 +98,10 @@ class AppViewModel( private val startKeys = ConcurrentHashMap() private val retryKeys = ConcurrentHashMap() + /** The multi-chat screen state (sessions, open conversations, drafts, scroll). */ + private val chatStore = ChatStore() + val chat: StateFlow = chatStore.state + init { // Connect on launch when a server URL is already saved, reusing the shared // client and its bounded backoff (no new client, DI or polling). init runs @@ -105,6 +112,24 @@ class AppViewModel( ) { reconnect() } + observeChatEvents() + } + + /** + * Routes server-pushed chat frames into the per-chat state, wherever the + * frame's session sits in the open order. Frames for a chat that is not open + * create a placeholder in [ChatStore.event] so a running background chat + * keeps its stream; the operator sees it re-synced from history on return. + */ + private fun observeChatEvents() { + viewModelScope.launch { + repository.events.collect { message -> + message.chatEvent?.let { chatStore.event(it) } + // Never silently drop an approval request: it is held per chat and + // answered with chat_reply from the conversation's approval bar. + message.chatPermission?.let { chatStore.permission(it) } + } + } } fun updateServerUrlDraft(value: String) { @@ -284,6 +309,119 @@ class AppViewModel( } } + // ---- Brokered chat ------------------------------------------------------- + + /** Refreshes the server's session list; never clears open conversations. */ + fun refreshChatSessions() { + viewModelScope.launch { + chatStore.sessionsLoading() + try { + chatStore.sessionsLoaded(repository.chatSessions()) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.sessionsFailed(ErrorMessages.describe(t)) + } + } + } + + /** + * Opens [session] and makes it active. A brand-new chat always loads its + * history; a running one re-syncs from the server so a stale copy is never + * shown on return. + */ + fun openChatSession(session: ChatSession) { + val needsHistory = chatStore.open(session) + if (needsHistory) loadChatHistory(session.id) + } + + /** Switches to an already-open chat, re-syncing it when it is running. */ + fun activateChat(sessionId: String) { + if (chatStore.activate(sessionId)) loadChatHistory(sessionId) + } + + /** Shows the session list again while keeping every open conversation. */ + fun showChatList() = chatStore.showList() + + fun closeChat(sessionId: String) = chatStore.close(sessionId) + + fun updateChatDraft(sessionId: String, text: String) = chatStore.draft(sessionId, text) + + fun saveChatScroll(sessionId: String, index: Int, offset: Int) = chatStore.scroll(sessionId, index, offset) + + /** Creates a session on the server and opens it. Reports the server's own error on failure. */ + fun newChat() { + viewModelScope.launch { + try { + val created = repository.chatCreate(title = "New chat", directory = settings.workspace.value) + chatStore.sessionsLoaded(chatStore.value.sessions + created) + chatStore.open(created) + chatStore.history(created.id, emptyList()) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.sessionsFailed(ErrorMessages.describe(t)) + } + } + } + + fun loadChatHistory(sessionId: String) { + viewModelScope.launch { + chatStore.historyLoading(sessionId) + try { + chatStore.history(sessionId, repository.chatMessages(sessionId, CHAT_HISTORY_LIMIT)) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.failed(sessionId, ErrorMessages.describe(t)) + } + } + } + + /** Sends the active chat's draft. Read-only chats are never written to. */ + fun sendChatPrompt(sessionId: String) { + val thread = chatStore.value.thread(sessionId) ?: return + if (thread.readOnly) return + val text = thread.draft.trim() + if (text.isEmpty()) return + chatStore.appendLocalUserMessage(sessionId, text) + chatStore.clearDraft(sessionId) + chatStore.running(sessionId, true) + viewModelScope.launch { + try { + repository.chatPrompt(sessionId, text) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.failed(sessionId, ErrorMessages.describe(t)) + chatStore.running(sessionId, false) + } + } + } + + /** Answers a pending approval: optimistically clears it, then reports a failed reply. */ + fun replyChatPermission(sessionId: String, requestId: String, decision: String) { + if (sessionId.isBlank() || requestId.isBlank()) return + viewModelScope.launch { + try { + repository.chatReply(sessionId, requestId, decision) + chatStore.clearPermission(sessionId) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.failed(sessionId, ErrorMessages.describe(t)) + } + } + } + + fun stopChat(sessionId: String) { + viewModelScope.launch { + try { + repository.chatInterrupt(sessionId) + } catch (t: Throwable) { + if (t is CancellationException) throw t + chatStore.failed(sessionId, ErrorMessages.describe(t)) + } finally { + chatStore.running(sessionId, false) + } + } + } + private fun load(target: MutableStateFlow>, block: suspend () -> T) { viewModelScope.launch { target.value = target.value.copy(loading = true, error = null) @@ -299,6 +437,9 @@ class AppViewModel( companion object { private const val CONNECT_TIMEOUT_MILLIS = 20_000L + /** Bounds one history fetch; the server applies its own cap too. */ + private const val CHAT_HISTORY_LIMIT = 200 + fun factory(app: PipelinesApplication) = viewModelFactory { initializer { AppViewModel(app.repository, app.settings) } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt index 8717e753..9f12c411 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/PipelinesApp.kt @@ -18,6 +18,7 @@ import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.Chat import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Settings @@ -57,12 +58,14 @@ import net.awan.pipelines.ui.screens.PipelineListScreen import net.awan.pipelines.ui.screens.RunDetailScreen import net.awan.pipelines.ui.screens.RunHistoryScreen import net.awan.pipelines.ui.screens.SettingsScreen +import net.awan.pipelines.ui.chat.ChatScreen private data class TopDestination(val route: String, val label: String, val icon: ImageVector) private val destinations = listOf( TopDestination("pipelines", "Pipelines", Icons.Default.AccountTree), TopDestination("runs", "Runs", Icons.Default.History), + TopDestination("chat", "Chat", Icons.AutoMirrored.Filled.Chat), TopDestination("settings", "Settings", Icons.Default.Settings), ) @@ -166,6 +169,9 @@ fun PipelinesApp(vm: AppViewModel) { onSelectionChange = { runSelection = it }, ) } + composable("chat") { + ChatScreen(vm = vm, wide = wide) + } composable("settings") { SettingsScreen(vm) } @@ -348,15 +354,15 @@ private fun DestinationPill( shadowElevation = 6.dp, ) { Row( - modifier = Modifier.padding(4.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), + modifier = Modifier.padding(DESTINATION_ITEM_GAP), + horizontalArrangement = Arrangement.spacedBy(DESTINATION_ITEM_GAP), verticalAlignment = Alignment.CenterVertically, ) { destinations.forEach { destination -> val selected = destinationSelected(currentRoute, destination.route) Box( modifier = Modifier - .size(48.dp) + .size(DESTINATION_ITEM_SIZE) .clip(CircleShape) .background( if (selected) { @@ -390,3 +396,9 @@ private fun DestinationPill( /** Bottom space reserved for the floating destination pill, so content is never * permanently hidden behind it (pill height + its margins + a small gap). */ private val DESTINATION_PILL_RESERVE = 88.dp + +/** The side of one destination's touch target, and the gap between them (also the + * pill's inner padding). Icons only, so the pill stays narrow however many + * destinations it holds. */ +private val DESTINATION_ITEM_SIZE = 48.dp +private val DESTINATION_ITEM_GAP = 4.dp diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt new file mode 100644 index 00000000..a1a98709 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -0,0 +1,166 @@ +package net.awan.pipelines.ui.chat + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.protocol.ChatToolState + +/** + * Pure chat formatting helpers shared by the session list and the conversation, + * so the same value is never spelled differently in two places. Kept free of + * Compose and of the transport so they are unit-testable. + */ +private val PRETTY_JSON = Json { prettyPrint = true; isLenient = true } + +/** + * The INPUT section of a tool call: pretty-printed JSON once the arguments are + * an object/array, a partial-JSON string while still streaming, or the raw text + * when it cannot be parsed. Blank when there is nothing. + */ +internal fun prettyToolInput(input: JsonElement?): String = when (input) { + null -> "" + is JsonObject, is JsonArray -> PRETTY_JSON.encodeToString(JsonElement.serializer(), input) + is JsonPrimitive -> input.content + else -> input.toString() +} + +/** + * The OUTPUT section of a tool call: the concatenated textual content, or the + * literal `(no output)` when the call returned nothing (mirroring jarvis), and + * an empty string while the call is still running. + */ +internal fun toolOutputText(state: ChatToolState?): String { + if (state == null) return "" + val text = state.content + .filter { it.type == "text" && it.text.isNotBlank() } + .joinToString("\n") { it.text } + if (text.isNotBlank()) return text + if (state.error != null) return state.error.message + if (ChatProtocol.toolRunning(state)) return "" + return "(no output)" +} + +/** Wall-clock duration of a tool call, or null while it has no completion time. */ +internal fun toolDurationMillis(part: ChatPart): Long? { + val time = part.time ?: return null + val start = if (time.ran > 0) time.ran else time.created + if (start <= 0 || time.completed <= 0 || time.completed < start) return null + return time.completed - start +} + +/** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */ +internal fun formatToolDuration(millis: Long): String = when { + millis < 1_000 -> "${millis}ms" + millis < 60_000 -> String.format(java.util.Locale.US, "%.1fs", millis / 1000.0) + else -> "${millis / 60_000}m ${(millis % 60_000) / 1000}s" +} + +/** The chip label for a tool call: its name, or a placeholder when unnamed. */ +internal fun toolLabel(part: ChatPart): String = part.name.ifBlank { "tool" } + +/** + * A session's short title: the server title, or a truncated id when untitled, so + * a row never renders as a blank line. + */ +internal fun sessionTitle(session: ChatSession): String = + session.title.ifBlank { session.id.take(18).ifBlank { "Untitled chat" } } + +/** + * The status a session row shows. A locally-running turn is reported as + * `Running`; otherwise the server's `busy` flag is `Busy · read-only` (another + * client holds it, so the composer is disabled), else `Idle`. + * + * This is the same precedence [ChatThread.readOnly] applies: a turn we started is + * `Running` and writable, never the read-only the server's own `busy` flag alone + * would imply. + */ +internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String = when { + runningLocally -> "Running" + session.busy -> "Busy · read-only" + else -> "Idle" +} + +/** + * One line of a derived unified diff. [CONTEXT] lines are unchanged, [ADD] came + * from the edit's `newString` and [REMOVE] from its `oldString`. + */ +enum class DiffKind { CONTEXT, ADD, REMOVE } + +data class DiffLine(val kind: DiffKind, val text: String) + +/** A synthesised edit diff: the file, the `+N -M` counts and the ordered lines. */ +data class ToolDiff(val file: String, val added: Int, val removed: Int, val lines: List) + +/** + * Derives a unified diff for an `edit`-family tool call from its + * `oldString`/`newString` arguments. The brokered protocol carries no diff field + * (research report §2.5), so the +/- view is synthesised here instead. Returns + * null for any other tool, so non-edit calls keep the INPUT/OUTPUT panel. + */ +internal fun toolEditDiff(input: JsonElement?): ToolDiff? { + val obj = input as? JsonObject ?: return null + val old = obj.stringOrNull("oldString", "old_string") ?: return null + val new = obj.stringOrNull("newString", "new_string") ?: return null + if (old.isEmpty() && new.isEmpty()) return null + val lines = lineDiff(old.split("\n"), new.split("\n")) + return ToolDiff( + file = obj.stringOrNull("filePath", "file_path", "file").orEmpty(), + added = lines.count { it.kind == DiffKind.ADD }, + removed = lines.count { it.kind == DiffKind.REMOVE }, + lines = lines, + ) +} + +private fun JsonObject.stringOrNull(vararg keys: String): String? { + for (key in keys) { + val value = this[key] + if (value is JsonPrimitive && value.isString) return value.content + } + return null +} + +/** + * A minimal line diff (LCS) so only the changed lines are marked, not the whole + * block. A pathologically large edit falls back to a plain remove-then-add block + * to bound the quadratic table. + */ +private fun lineDiff(old: List, new: List): List { + if (old.size > MAX_DIFF_LINES || new.size > MAX_DIFF_LINES) { + return old.map { DiffLine(DiffKind.REMOVE, it) } + new.map { DiffLine(DiffKind.ADD, it) } + } + val m = old.size + val n = new.size + val lcs = Array(m + 1) { IntArray(n + 1) } + for (i in m - 1 downTo 0) { + for (j in n - 1 downTo 0) { + lcs[i][j] = if (old[i] == new[j]) lcs[i + 1][j + 1] + 1 + else maxOf(lcs[i + 1][j], lcs[i][j + 1]) + } + } + val result = ArrayList(m + n) + var i = 0 + var j = 0 + while (i < m && j < n) { + when { + old[i] == new[j] -> { + result.add(DiffLine(DiffKind.CONTEXT, old[i])); i++; j++ + } + lcs[i + 1][j] >= lcs[i][j + 1] -> { + result.add(DiffLine(DiffKind.REMOVE, old[i])); i++ + } + else -> { + result.add(DiffLine(DiffKind.ADD, new[j])); j++ + } + } + } + while (i < m) { result.add(DiffLine(DiffKind.REMOVE, old[i])); i++ } + while (j < n) { result.add(DiffLine(DiffKind.ADD, new[j])); j++ } + return result +} + +private const val MAX_DIFF_LINES = 400 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt new file mode 100644 index 00000000..51e68c17 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -0,0 +1,747 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.automirrored.filled.Send +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Build +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Psychology +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Stop +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.foundation.selection.selectable +import androidx.activity.compose.PredictiveBackHandler +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatPermissionFrame +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.transport.ConnectionState +import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.components.EmptyState +import net.awan.pipelines.ui.components.ErrorState +import net.awan.pipelines.ui.components.ListRow +import net.awan.pipelines.ui.components.LoadingState +import net.awan.pipelines.ui.components.PaneIdentity +import net.awan.pipelines.ui.components.RunState +import net.awan.pipelines.ui.components.RunStatusPalette +import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * Geometry tokens for the chat surface. Every value is a named constant so no + * screen body holds an ad-hoc number; Material's own minimum interactive size + * governs touch targets. + */ +private val CHAT_GUTTER = 16.dp +private val CHAT_ITEM_GAP = 8.dp +private val CHAT_COMPOSER_GAP = 12.dp +private val CHAT_STATUS_DOT = 8.dp + +/** + * The Chat destination. It is the same adaptive [SlidingPaneStack] the Pipelines + * and Runs destinations use: pane 0 is the server's session list (the operator + * can hold several chats open at once) and pane 1 is the active conversation. + * + * Every open chat keeps its own messages, running flag, composer draft and + * scroll position in [ChatStore]; switching away and back never loses them, and + * returning to a running chat re-syncs it from the server instead of showing a + * stale copy. + */ +@Composable +fun ChatScreen(vm: AppViewModel, wide: Boolean, modifier: Modifier = Modifier) { + val state by vm.chat.collectAsStateWithLifecycle() + val connection by vm.connectionState.collectAsStateWithLifecycle() + val active = state.active + + // Fetch the server's session list once when the Chat destination opens. + LaunchedEffect(Unit) { vm.refreshChatSessions() } + + // Back inside a conversation returns to the session list before leaving the + // destination, exactly one level (the same rule the other destinations use). + PredictiveBackHandler(enabled = active != null) { progress -> + progress.collect { } + vm.showChatList() + } + + SlidingPaneStack( + depth = if (active != null) 1 else 0, + wide = wide, + onPopTo = { vm.showChatList() }, + backContentDescription = { "Back to chats" }, + modifier = modifier, + ) { level, covered, paneModifier -> + when (level) { + 0 -> ChatListPane( + vm = vm, + state = state, + connected = connection is ConnectionState.Connected, + covered = covered, + modifier = paneModifier, + ) + 1 -> active?.let { thread -> + // Key by session so each conversation gets its own list state and + // disposes (saving its scroll) when the operator switches away. + key(thread.sessionId) { + ChatConversationPane(vm = vm, state = state, thread = thread, modifier = paneModifier) + } + } + } + } +} + +// ---- Pane 0: the server's session list --------------------------------------- + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ChatListPane( + vm: AppViewModel, + state: ChatState, + connected: Boolean, + covered: Boolean, + modifier: Modifier, +) { + if (covered) { + PaneIdentity( + title = "Chat", + subtitle = when { + state.open.isNotEmpty() -> "${state.open.size} open" + state.sessions.isNotEmpty() -> "${state.sessions.size} sessions" + else -> null + }, + modifier = modifier.fillMaxSize(), + ) + return + } + + Scaffold( + modifier = modifier, + topBar = { + TopAppBar( + title = { Text("Chat") }, + actions = { + IconButton(onClick = vm::refreshChatSessions) { + Icon(Icons.Default.Refresh, contentDescription = "Refresh chats") + } + IconButton(onClick = vm::newChat) { + Icon(Icons.Default.Add, contentDescription = "New chat") + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding)) { + if (state.open.isNotEmpty()) { + OpenChatStrip( + state = state, + onSelect = vm::activateChat, + onClose = vm::closeChat, + ) + } + if (!connected) { + NotConnectedNotice() + } + when { + state.sessionsLoading && state.sessions.isEmpty() -> LoadingState("Loading chats…") + state.sessionsError != null && state.sessions.isEmpty() -> { + ErrorState(state.sessionsError, onRetry = vm::refreshChatSessions) + } + state.sessions.isEmpty() -> EmptyState( + message = "No chat sessions on this server yet.", + actionLabel = "New chat", + onAction = vm::newChat, + ) + else -> LazyColumn(Modifier.fillMaxSize()) { + items(state.sessions, key = { it.id }) { session -> + val thread = state.thread(session.id) + SessionRow( + session = session, + open = thread != null, + running = thread?.running == true, + active = state.activeId == session.id, + onClick = { vm.openChatSession(session) }, + ) + } + if (state.sessionsError != null) { + item("error") { + Text( + text = state.sessionsError, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(CHAT_GUTTER), + ) + } + } + } + } + } + } +} + +@Composable +private fun SessionRow( + session: ChatSession, + open: Boolean, + running: Boolean, + active: Boolean, + onClick: () -> Unit, +) { + val texts = pipelinesText() + ListRow(selected = active, onClick = onClick) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Text( + text = sessionTitle(session), + style = texts.cardTitle, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + if (open) SessionBadge("Open", running) + } + val meta = buildList { + add(sessionStatusLabel(session, running)) + if (session.directory.isNotBlank()) add(session.directory) + if (session.model.isNotBlank()) add(session.model) + }.joinToString(" · ") + Text(text = meta, style = texts.meta, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + +/** A running/busy/open indicator: a coloured dot plus a word, never colour alone. */ +@Composable +private fun SessionBadge(label: String, running: Boolean = false) { + val color = when { + running -> MaterialTheme.colorScheme.tertiary + label == "Open" -> MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.outline + } + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Box(Modifier.size(CHAT_STATUS_DOT).clip(CircleShape).background(color)) + Text(label, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun NotConnectedNotice() { + Surface( + color = MaterialTheme.colorScheme.errorContainer, + modifier = Modifier.fillMaxWidth(), + ) { + Text( + text = "Not connected. Chats are served by the Pipelines server; connect in Settings.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) + } +} + +/** + * The open-conversation switcher: one chip per conversation the operator has + * open, so several chats can be kept at once and switched between in one tap. + * A running chat carries a `Running` badge; the X closes that chat (optional + * close is provided). + */ +@Composable +private fun OpenChatStrip( + state: ChatState, + onSelect: (String) -> Unit, + onClose: (String) -> Unit, +) { + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(rememberScrollState()) + .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + state.open.forEach { thread -> + val selected = state.activeId == thread.sessionId + Surface( + shape = RoundedCornerShape(50), + color = if (selected) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + modifier = Modifier + .selectable(selected = selected, role = Role.Tab, onClick = { onSelect(thread.sessionId) }), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.padding(start = CHAT_ITEM_GAP + 4.dp, end = 2.dp, top = 4.dp, bottom = 4.dp), + ) { + if (thread.running) { + Box( + Modifier.size(CHAT_STATUS_DOT).clip(CircleShape) + .background(MaterialTheme.colorScheme.tertiary), + ) + } + Text( + text = thread.title.ifBlank { thread.sessionId.take(12) }, + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.widthIn(max = 160.dp), + ) + IconButton(onClick = { onClose(thread.sessionId) }, modifier = Modifier.size(28.dp)) { + Icon( + Icons.Default.Close, + contentDescription = "Close chat ${thread.title}", + modifier = Modifier.size(16.dp), + ) + } + } + } + } + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) +} + +// ---- Pane 1: the active conversation ----------------------------------------- + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun ChatConversationPane( + vm: AppViewModel, + state: ChatState, + thread: ChatThread, + modifier: Modifier, +) { + val listState = rememberLazyListState( + initialFirstVisibleItemIndex = thread.scroll.index, + initialFirstVisibleItemScrollOffset = thread.scroll.offset, + ) + // Persist the scroll position when the operator leaves this chat, so switching + // away and back returns them exactly where they were. + DisposableEffect(thread.sessionId) { + onDispose { vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) } + } + + Scaffold( + modifier = modifier, + topBar = { + TopAppBar( + title = { + Text( + text = thread.title.ifBlank { sessionTitle(ChatSession(id = thread.sessionId)) }, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + }, + navigationIcon = { + IconButton(onClick = vm::showChatList) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back to chats") + } + }, + actions = { + if (thread.running) { + IconButton(onClick = { vm.stopChat(thread.sessionId) }) { + Icon(Icons.Default.Stop, contentDescription = "Stop") + } + } + }, + ) + }, + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).imePadding()) { + OpenChatStrip(state = state, onSelect = vm::activateChat, onClose = vm::closeChat) + Box(Modifier.weight(1f).fillMaxWidth()) { + when { + thread.loading && !thread.loaded -> LoadingState("Loading conversation…") + thread.error != null && !thread.loaded -> ErrorState( + message = thread.error, + onRetry = { vm.loadChatHistory(thread.sessionId) }, + ) + thread.messages.isEmpty() && !thread.running -> EmptyState( + message = if (thread.readOnly) { + "This chat is read-only while another client holds the session." + } else { + "This chat has no messages yet. Ask something below." + }, + ) + else -> ChatTranscript(thread = thread, listState = listState) + } + } + if (thread.error != null && thread.loaded) { + Text( + text = thread.error, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp), + ) + } + thread.permission?.let { permission -> + PermissionBar( + permission = permission, + onDecision = { decision -> + vm.replyChatPermission(thread.sessionId, permission.requestId, decision) + }, + ) + } + ChatComposer( + thread = thread, + onDraft = { vm.updateChatDraft(thread.sessionId, it) }, + onSend = { vm.sendChatPrompt(thread.sessionId) }, + onStop = { vm.stopChat(thread.sessionId) }, + ) + } + } +} + +/** + * The bottom-anchored transcript: content is packed to the bottom (so a short or + * freshly opened chat sits against the composer) and the running indicator sits + * at the newest end while a turn is in flight. + */ +@Composable +private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.foundation.lazy.LazyListState) { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom), + ) { + items(thread.messages, key = { it.id }) { message -> + MessageItem(message) + } + if (thread.running) { + item(key = "pending") { RunningIndicator() } + } + } +} + +@Composable +private fun RunningIndicator() { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + ) { + CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) + Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } +} + +@Composable +private fun MessageItem(message: ChatMessage) { + val isUser = message.role == ChatProtocol.ROLE_USER + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = if (isUser) Arrangement.End else Arrangement.Start, + ) { + Surface( + shape = RoundedCornerShape(CHAT_GUTTER), + color = if (isUser) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainer + }, + modifier = Modifier.widthIn(max = 560.dp), + ) { + SelectionContainer { + Column(Modifier.padding(CHAT_GUTTER)) { + if (isUser) { + Text( + text = message.parts.joinToString("\n") { it.text }.trim(), + style = MaterialTheme.typography.bodyMedium, + ) + } else { + message.parts.forEach { part -> MessagePart(part) } + } + } + } + } + } +} + +@Composable +private fun MessagePart(part: ChatPart) { + when (part.type) { + ChatProtocol.PART_TEXT -> if (part.text.isNotBlank()) { + Text(part.text, style = MaterialTheme.typography.bodyMedium) + } + ChatProtocol.PART_REASONING -> ReasoningBlock(part.text) + ChatProtocol.PART_TOOL -> ToolCallCard(part) + else -> if (part.text.isNotBlank()) Text(part.text, style = MaterialTheme.typography.bodyMedium) + } +} + +/** Reasoning is visually secondary: a muted, bordered block, never body weight. */ +@Composable +private fun ReasoningBlock(text: String) { + if (text.isBlank()) return + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), modifier = Modifier.padding(vertical = 4.dp)) { + Icon( + Icons.Default.Psychology, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(16.dp), + ) + Text( + text = text, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** + * A tool call as a compact chip that expands to INPUT (pretty JSON) and OUTPUT + * (monospace) sections, mirroring the reference chat: the transcript stays + * scannable and the arguments/result appear only on demand. + * + * An `edit`-family call instead renders a diff card (research §1.3 `_CodeRun` / + * `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived + * from the arguments, since the brokered protocol carries no diff field. + */ +@Composable +private fun ToolCallCard(part: ChatPart) { + var expanded by remember(part.id) { mutableStateOf(false) } + val running = ChatProtocol.toolRunning(part.state) + val diff = toolEditDiff(part.state?.input) + Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + Surface( + shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), + color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier.clickable { expanded = !expanded }, + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.padding(horizontal = CHAT_ITEM_GAP + 2.dp, vertical = CHAT_ITEM_GAP), + ) { + if (running) { + CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp) + } else { + Icon( + if (diff != null) Icons.Default.Edit else Icons.Default.Build, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), + style = MaterialTheme.typography.labelMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false), + ) + diff?.let { DiffStat(it) } + toolDurationMillis(part)?.let { + Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Icon( + imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = if (expanded) "Collapse tool call" else "Expand tool call", + modifier = Modifier.size(18.dp), + ) + } + } + if (expanded) { + Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), modifier = Modifier.padding(top = CHAT_ITEM_GAP)) { + if (diff != null) { + DiffView(diff) + } else { + CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) + CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) + } + } + } + } +} + +/** The `+N -M` counts, green/red monospace, exactly as the reference diff stat. */ +@Composable +private fun DiffStat(diff: ToolDiff) { + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Text( + text = "+${diff.added}", + style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), + color = RunStatusPalette.of(RunState.Succeeded).color, + ) + Text( + text = "-${diff.removed}", + style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace), + color = RunStatusPalette.of(RunState.Failed).color, + ) + } +} + +/** + * The unified diff body of an edit card: line-by-line monospace with `+`/`-` + * gutter symbols and the app's success/failure hues, bounded so a long diff + * scrolls inside the card instead of pushing the transcript down. + */ +@Composable +private fun DiffView(diff: ToolDiff) { + val added = RunStatusPalette.of(RunState.Succeeded).color + val removed = RunStatusPalette.of(RunState.Failed).color + val context = MaterialTheme.colorScheme.onSurfaceVariant + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = CODE_BLOCK_MAX_HEIGHT) + .verticalScroll(rememberScrollState()) + .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) { + diff.lines.forEach { line -> + val (symbol, color) = when (line.kind) { + DiffKind.ADD -> "+" to added + DiffKind.REMOVE -> "-" to removed + DiffKind.CONTEXT -> " " to context + } + Text( + text = "$symbol ${line.text}", + style = pipelinesText().mono, + color = color, + ) + } + } + } +} + +@Composable +private fun ChatComposer( + thread: ChatThread, + onDraft: (String) -> Unit, + onSend: () -> Unit, + onStop: () -> Unit, +) { + Surface(color = MaterialTheme.colorScheme.surfaceContainer) { + Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) { + if (thread.readOnly) { + Text( + text = "Another client holds this session; it is read-only here.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), + ) + } + Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(CHAT_COMPOSER_GAP)) { + OutlinedTextField( + value = thread.draft, + onValueChange = onDraft, + enabled = !thread.readOnly, + placeholder = { Text("Message the agent…") }, + minLines = 1, + maxLines = 6, + keyboardActions = KeyboardActions(onSend = { if (thread.canSend) onSend() }), + modifier = Modifier.weight(1f), + ) + if (thread.running) { + // While a turn is in flight the send control becomes the stop + // control, so it must interrupt rather than send the draft. + IconButton(onClick = onStop) { + Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error) + } + } else { + IconButton(onClick = onSend, enabled = thread.canSend) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") + } + } + } + } + } +} + +/** + * The approval bar for a pending tool-call permission: the request's action and + * resources, with Allow-once / Always / Deny. A decision is answered through + * `chat_reply`, so the server-held credentials and the tool never leave it. + */ +@Composable +private fun PermissionBar(permission: ChatPermissionFrame, onDecision: (String) -> Unit) { + Surface(color = MaterialTheme.colorScheme.tertiaryContainer, modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + Text( + text = "Approve: ${permission.action.ifBlank { "tool call" }}", + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onTertiaryContainer, + ) + if (permission.resources.isNotEmpty()) { + Text( + text = permission.resources.joinToString("\n"), + style = pipelinesText().mono, + color = MaterialTheme.colorScheme.onTertiaryContainer, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + TextButton(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Deny") } + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt new file mode 100644 index 00000000..ef38751c --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -0,0 +1,336 @@ +package net.awan.pipelines.ui.chat + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import net.awan.pipelines.data.protocol.ChatEventFrame +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatPermissionFrame +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession + +/** + * A saved scroll position inside one conversation. Kept as Android-free + * primitives so it is part of the pure model and can survive a chat switch (the + * caller feeds it back into the list's state). + */ +data class ChatScrollPosition(val index: Int = 0, val offset: Int = 0) + +/** + * One open conversation. The conversation itself, whether it is running, its + * unsent composer draft and its scroll position all live here, so switching to + * another chat and back can never lose any of them. + */ +data class ChatThread( + val sessionId: String, + val title: String = "", + val directory: String = "", + val model: String = "", + val agent: String = "", + val updatedAt: Long = 0, + /** The server reports another client (or an active run) holds this session. */ + val busy: Boolean = false, + val messages: List = emptyList(), + val loading: Boolean = false, + val loaded: Boolean = false, + val error: String? = null, + /** A turn is in flight for this session; it keeps running when we switch away. */ + val running: Boolean = false, + /** The unsent composer text for this chat. */ + val draft: String = "", + val scroll: ChatScrollPosition = ChatScrollPosition(), + /** The server's pending approval for this session, answered with chat_reply. */ + val permission: ChatPermissionFrame? = null, +) { + /** + * Read-only while another client holds the session: the composer must never + * write to it. A turn we started ourselves keeps the session writable even + * though the server reports it busy (the server owns it as our active run), + * so the one rule here agrees with [sessionStatusLabel]'s `Running` case. + */ + val readOnly: Boolean get() = busy && !running + + /** Whether the composer's send action is allowed. */ + val canSend: Boolean get() = !readOnly && draft.isNotBlank() +} + +/** + * The multi-chat screen state. [sessions] is the server's list; [open] is the + * ordered set of conversations the operator has opened, each preserved + * independently; [activeId] is the one currently on screen. + */ +data class ChatState( + val sessions: List = emptyList(), + val sessionsLoading: Boolean = false, + val sessionsLoaded: Boolean = false, + val sessionsError: String? = null, + val open: List = emptyList(), + val activeId: String? = null, +) { + val active: ChatThread? get() = open.firstOrNull { it.sessionId == activeId } + + fun thread(sessionId: String): ChatThread? = open.firstOrNull { it.sessionId == sessionId } +} + +/** + * The multi-chat state model: a small, Android-free holder of [ChatState] with + * the transitions the chat surface needs. Keeping it free of Compose and of the + * transport makes the multi-chat guarantees (per-chat draft/scroll/conversation, + * running survives a switch and re-syncs on return) unit-testable without a + * device or a server. + * + * Method contracts that matter: + * - [open] and [activate] return true when the caller must (re-)fetch history; + * a running session must re-sync on return so a stale copy is never shown. + * - [event] applies a server frame to its session's thread whether or not that + * thread is on screen, so a background chat never loses its stream. + */ +class ChatStore { + + private val _state = MutableStateFlow(ChatState()) + val state: StateFlow = _state.asStateFlow() + + val value: ChatState get() = _state.value + + // ---- Session list -------------------------------------------------------- + + fun sessionsLoading() { + _state.value = _state.value.copy(sessionsLoading = true, sessionsError = null) + } + + fun sessionsFailed(message: String) { + _state.value = _state.value.copy(sessionsLoading = false, sessionsError = message) + } + + /** + * Replaces the server's session list and folds its title/busy flags into any + * already-open thread, so a status change is reflected without dropping the + * conversation. An open thread the server no longer lists is kept (its + * conversation is still the operator's). + */ + fun sessionsLoaded(sessions: List) { + val byId = sessions.associateBy { it.id } + val open = _state.value.open.map { thread -> + val session = byId[thread.sessionId] ?: return@map thread + thread.copy( + title = session.title.ifBlank { thread.title }, + directory = session.directory.ifBlank { thread.directory }, + busy = session.busy, + ) + } + _state.value = _state.value.copy( + sessions = sessions, + open = open, + sessionsLoading = false, + sessionsLoaded = true, + sessionsError = null, + ) + } + + // ---- Opening / switching ------------------------------------------------- + + /** + * Opens [session] (idempotently) and makes it active. Returns true when its + * history must be fetched: a brand-new thread always, and a re-opened one + * whose state may have moved on (it is running, or was never loaded). + */ + fun open(session: ChatSession): Boolean { + val existing = _state.value.thread(session.id) + if (existing == null) { + val thread = ChatThread( + sessionId = session.id, + title = session.title, + directory = session.directory, + model = session.model, + agent = session.agent, + updatedAt = session.updatedAt, + busy = session.busy, + ) + _state.value = _state.value.copy(open = _state.value.open + thread, activeId = session.id) + return true + } + val merged = existing.copy( + title = session.title.ifBlank { existing.title }, + directory = session.directory.ifBlank { existing.directory }, + busy = session.busy, + ) + _state.value = _state.value.copy( + open = _state.value.open.map { if (it.sessionId == session.id) merged else it }, + activeId = session.id, + ) + return needsResync(merged) + } + + /** + * Makes an already-open thread active. Returns true when its history must be + * re-fetched first: a running session is re-synced from the server on return + * so the operator never sees a stale conversation. + */ + fun activate(sessionId: String): Boolean { + val thread = _state.value.thread(sessionId) ?: return false + _state.value = _state.value.copy(activeId = sessionId) + return needsResync(thread) + } + + fun close(sessionId: String) { + val open = _state.value.open.filterNot { it.sessionId == sessionId } + val active = if (_state.value.activeId == sessionId) open.lastOrNull()?.sessionId else _state.value.activeId + _state.value = _state.value.copy(open = open, activeId = active) + } + + /** + * Returns to the session list without closing any conversation: [activeId] + * becomes null while [ChatState.open] is untouched, so every open chat keeps + * its messages, draft and scroll. + */ + fun showList() { + if (_state.value.activeId != null) { + _state.value = _state.value.copy(activeId = null) + } + } + + private fun needsResync(thread: ChatThread): Boolean = thread.running || !thread.loaded + + // ---- Per-thread edits ---------------------------------------------------- + + fun draft(sessionId: String, text: String) = update(sessionId) { it.copy(draft = text) } + + fun clearDraft(sessionId: String) = update(sessionId) { it.copy(draft = "") } + + fun scroll(sessionId: String, index: Int, offset: Int) = + update(sessionId) { it.copy(scroll = ChatScrollPosition(index, offset)) } + + fun historyLoading(sessionId: String) = update(sessionId) { it.copy(loading = true, error = null) } + + fun failed(sessionId: String, message: String) = + update(sessionId) { it.copy(loading = false, error = message) } + + /** + * Replaces a thread's conversation with the server's authoritative history. + * The running flag is left as-is: history alone cannot say whether a turn is + * still in flight. + */ + fun history(sessionId: String, messages: List) = update(sessionId) { + it.copy(messages = messages, loading = false, loaded = true, error = null) + } + + fun running(sessionId: String, running: Boolean) = update(sessionId) { it.copy(running = running) } + + /** The server pushed an approval request for this session; the composer answers it. */ + fun permission(frame: ChatPermissionFrame) { + if (frame.sessionId.isBlank()) return + ensureThread(frame.sessionId) + update(frame.sessionId) { it.copy(permission = frame) } + } + + /** Drops the pending approval once it has been answered or is no longer valid. */ + fun clearPermission(sessionId: String) = update(sessionId) { it.copy(permission = null) } + + /** + * Appends the operator's just-sent prompt optimistically, so the bubble is + * visible before the ack and history round-trip. History later reconciles it. + */ + fun appendLocalUserMessage(sessionId: String, text: String) = update(sessionId) { + val message = ChatMessage( + id = LOCAL_MESSAGE_PREFIX + (it.messages.count { m -> m.id.startsWith(LOCAL_MESSAGE_PREFIX) } + 1), + sessionId = sessionId, + role = ChatProtocol.ROLE_USER, + parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, text = text)), + ) + it.copy(messages = it.messages + message) + } + + // ---- Streaming events ---------------------------------------------------- + + /** + * Folds one pushed [frame] into its session's thread, creating a placeholder + * thread when the frame arrives for a chat that is not open, so a background + * chat keeps its stream instead of dropping it. + */ + fun event(frame: ChatEventFrame) { + if (frame.sessionId.isBlank()) return + ensureThread(frame.sessionId) + when (frame.kind) { + ChatProtocol.PART_TEXT, ChatProtocol.PART_REASONING -> applyDelta(frame) + ChatProtocol.PART_TOOL -> applyTool(frame) + ChatProtocol.EVENT_STEP -> { + val started = frame.step?.status != ChatProtocol.STEP_ENDED + update(frame.sessionId) { it.copy(running = started) } + } + else -> Unit + } + } + + /** + * Creates a placeholder thread for a session that is not open, so a frame for + * a background chat is kept instead of dropped. A no-op when it already exists. + */ + private fun ensureThread(sessionId: String) { + if (_state.value.thread(sessionId) != null) return + val session = _state.value.sessions.firstOrNull { it.id == sessionId } + val placeholder = ChatThread( + sessionId = sessionId, + title = session?.title ?: "", + directory = session?.directory ?: "", + busy = session?.busy ?: false, + ) + _state.value = _state.value.copy(open = _state.value.open + placeholder) + } + + private fun applyDelta(frame: ChatEventFrame) { + val partId = frame.part?.id.orEmpty() + if (partId.isEmpty() || frame.delta.isEmpty()) return + upsertPart(frame, partId) { existing -> + existing?.copy(text = existing.text + frame.delta) + ?: ChatPart(type = frame.kind, id = partId, text = frame.delta) + } + } + + private fun applyTool(frame: ChatEventFrame) { + val part = frame.part ?: return + if (part.id.isEmpty()) return + upsertPart(frame, part.id) { part } + } + + /** + * Finds or creates the assistant message [frame] targets and the part [partId] + * inside it, replacing it via [upsert] (the old part when it exists, else + * null), then marks the thread running. The text/reasoning delta and the tool + * upsert share this so the two cannot drift. + */ + private fun upsertPart(frame: ChatEventFrame, partId: String, upsert: (ChatPart?) -> ChatPart) { + update(frame.sessionId) { thread -> + val messages = thread.messages.toMutableList() + val index = messages.indexOfLast { it.id == frame.messageId } + val message = if (index >= 0) { + messages[index] + } else { + ChatMessage( + id = frame.messageId, + sessionId = frame.sessionId, + role = ChatProtocol.ROLE_ASSISTANT, + ).also { messages.add(it) } + } + val resolvedIndex = if (index >= 0) index else messages.lastIndex + val parts = message.parts.toMutableList() + val partIndex = parts.indexOfFirst { it.id == partId } + val updated = upsert(if (partIndex >= 0) parts[partIndex] else null) + if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated) + messages[resolvedIndex] = message.copy(parts = parts) + thread.copy(messages = messages, running = true) + } + } + + private fun update(sessionId: String, block: (ChatThread) -> ChatThread) { + val current = _state.value + if (current.open.none { it.sessionId == sessionId }) return + _state.value = current.copy( + open = current.open.map { if (it.sessionId == sessionId) block(it) else it }, + ) + } + + companion object { + const val LOCAL_MESSAGE_PREFIX = "local-" + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt new file mode 100644 index 00000000..9783fc49 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt @@ -0,0 +1,221 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ChatProtocolTest { + + @Test + fun chatSessionsParseWithBusyFlagAndFlattenedFields() { + val json = """ + { + "type": "chat_sessions", + "id": "android-1", + "chat_sessions": [ + { + "id": "ses_abc", + "title": "Fix the parser", + "agent": "build", + "model": "deepseek-v4.1-flash", + "directory": "/Users/alan/repos/pipelines", + "parent_id": "", + "created_at": 1792112366711, + "updated_at": 1792112367036, + "busy": true + }, + {"id": "ses_def", "title": "Second chat"} + ] + } + """.trimIndent() + val message = PipelinesJson.decodeFromString(Message.serializer(), json) + assertEquals(Protocol.CHAT_SESSIONS, message.type) + val sessions = message.chatSessions!! + assertEquals(2, sessions.size) + val first = sessions.first() + assertEquals("ses_abc", first.id) + assertEquals("Fix the parser", first.title) + assertEquals("/Users/alan/repos/pipelines", first.directory) + assertEquals(1792112366711L, first.createdAt) + assertTrue(first.busy) + // An absent busy key defaults to false, never a crash. + assertTrue(!sessions[1].busy) + } + + @Test + fun chatMessagesParseTextReasoningAndToolParts() { + val json = """ + { + "type": "chat_messages", + "chat_messages": [ + { + "id": "msg_user", + "session_id": "ses_abc", + "role": "user", + "parts": [{"type": "text", "id": "p1", "text": "hello"}] + }, + { + "id": "msg_asst", + "session_id": "ses_abc", + "role": "assistant", + "parts": [ + {"type": "reasoning", "id": "r1", "text": "thinking"}, + {"type": "text", "id": "t1", "text": "done"}, + { + "type": "tool", + "id": "call_1", + "name": "shell", + "executed": false, + "state": { + "status": "completed", + "input": {"command": "ls"}, + "content": [{"type": "text", "text": "a.txt"}], + "metadata": {"exit": 0}, + "error": null + }, + "time": {"created": 10, "ran": 12, "completed": 20} + } + ] + } + ] + } + """.trimIndent() + val messages = PipelinesJson.decodeFromString(Message.serializer(), json).chatMessages!! + assertEquals(2, messages.size) + assertEquals(ChatProtocol.ROLE_USER, messages[0].role) + assertEquals("hello", messages[0].parts.single().text) + val assistant = messages[1] + assertEquals(ChatProtocol.PART_REASONING, assistant.parts[0].type) + val tool = assistant.parts.first { it.type == ChatProtocol.PART_TOOL } + assertEquals("shell", tool.name) + assertEquals(ChatProtocol.TOOL_COMPLETED, tool.state!!.status) + assertTrue(tool.state!!.input is JsonObject) + assertEquals("a.txt", tool.state!!.content.single().text) + assertEquals(8L, toolDuration(tool)) + } + + /** The tool input is a partial-JSON string while streaming and an object afterwards. */ + @Test + fun streamingToolInputIsAStringAndCompletedInputIsAnObject() { + val streaming = """ + {"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"tool", + "part":{"type":"tool","id":"c1","name":"edit","state":{"status":"streaming","input":"{\"old"}}}} + """.trimIndent() + val frame = PipelinesJson.decodeFromString(Message.serializer(), streaming).chatEvent!! + assertEquals(ChatProtocol.TOOL_STREAMING, frame.part!!.state!!.status) + assertEquals("{\"old", (frame.part!!.state!!.input as JsonPrimitive).content) + assertTrue(ChatProtocol.toolRunning(frame.part!!.state)) + } + + @Test + fun chatEventDeltaCarriesTheTargetPartAndText() { + val json = """ + {"type":"chat_event","chat_event":{"session_id":"ses_1","message_id":"m1","kind":"text", + "delta":"wor","part":{"type":"text","id":"t1"}}} + """.trimIndent() + val frame = PipelinesJson.decodeFromString(Message.serializer(), json).chatEvent!! + assertEquals("ses_1", frame.sessionId) + assertEquals("m1", frame.messageId) + assertEquals(ChatProtocol.PART_TEXT, frame.kind) + assertEquals("wor", frame.delta) + assertEquals("t1", frame.part!!.id) + } + + @Test + fun stepAndUsageFramesDecode() { + val step = """ + {"type":"chat_event","chat_event":{"session_id":"s","kind":"step","step":{"status":"ended","index":3}}} + """.trimIndent() + val decodedStep = PipelinesJson.decodeFromString(Message.serializer(), step).chatEvent!! + assertEquals(ChatProtocol.EVENT_STEP, decodedStep.kind) + assertEquals(ChatProtocol.STEP_ENDED, decodedStep.step!!.status) + + val usage = """ + {"type":"chat_event","chat_event":{"session_id":"s","kind":"usage", + "usage":{"input_tokens":12,"output_tokens":34,"cost":0.002}}} + """.trimIndent() + val decodedUsage = PipelinesJson.decodeFromString(Message.serializer(), usage).chatEvent!! + assertEquals(12, decodedUsage.usage!!.inputTokens) + assertEquals(34, decodedUsage.usage!!.outputTokens) + assertEquals(0.002, decodedUsage.usage!!.cost, 0.0) + } + + @Test + fun chatPermissionFrameDecodesTheRequestShape() { + val json = """ + {"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9", + "action":"edit","resources":["src/a.kt"], + "source":{"type":"tool","message_id":"m1","id":"c1"}, + "message":"Allow this edit?"}} + """.trimIndent() + val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!! + assertEquals("req_9", permission.requestId) + assertEquals("edit", permission.action) + assertEquals("src/a.kt", permission.resources.single()) + assertEquals("c1", permission.source!!.id) + } + + @Test + fun chatRequestsRoundTripTheirBodies() { + val create = Message( + type = Protocol.CHAT_CREATE, + id = "android-1", + chatCreate = ChatCreateRequest(title = "New chat", directory = "/work"), + ) + val createJson = PipelinesJson.encodeToString(Message.serializer(), create) + assertTrue(createJson.contains("\"chat_create\"")) + val decodedCreate = PipelinesJson.decodeFromString(Message.serializer(), createJson) + assertEquals("New chat", decodedCreate.chatCreate!!.title) + + val prompt = Message( + type = Protocol.CHAT_PROMPT, + id = "android-2", + chatPrompt = ChatPromptRequest(sessionId = "ses_1", text = "hi"), + ) + val decodedPrompt = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), prompt), + ) + assertEquals("ses_1", decodedPrompt.chatPrompt!!.sessionId) + assertEquals("hi", decodedPrompt.chatPrompt!!.text) + + val query = Message(type = Protocol.CHAT_MESSAGES, id = "android-3", chatQuery = ChatQuery("ses_1", 50)) + val decodedQuery = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), query), + ) + assertEquals("ses_1", decodedQuery.chatQuery!!.sessionId) + assertEquals(50, decodedQuery.chatQuery!!.limit) + + val reply = Message( + type = Protocol.CHAT_REPLY, + id = "android-4", + chatReply = ChatReplyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE), + ) + val decodedReply = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), reply), + ) + assertEquals(ChatProtocol.DECISION_ONCE, decodedReply.chatReply!!.decision) + } + + /** A non-chat envelope leaves every chat field null, so the two never cross-talk. */ + @Test + fun nonChatEnvelopeHasNoChatPayload() { + val message = PipelinesJson.decodeFromString( + Message.serializer(), + """{"type":"pong"}""", + ) + assertNull(message.chatEvent) + assertNull(message.chatSessions) + assertNull(message.chatPermission) + } + + private fun toolDuration(part: ChatPart): Long? { + val time = part.time ?: return null + return time.completed - time.ran + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt new file mode 100644 index 00000000..9ecdacaf --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -0,0 +1,103 @@ +package net.awan.pipelines.ui.chat + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.protocol.ChatTime +import net.awan.pipelines.data.protocol.ChatToolContent +import net.awan.pipelines.data.protocol.ChatToolState +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class ChatFormatTest { + + @Test + fun prettyToolInputPrintsObjectsAndPassesThroughPartialStrings() { + val obj = prettyToolInput(JsonObject(mapOf("command" to JsonPrimitive("ls")))) + assertTrue(obj.contains("\"command\"")) + assertTrue(obj.contains("\n")) + assertEquals("{\"old", prettyToolInput(JsonPrimitive("{\"old"))) + assertEquals("", prettyToolInput(null)) + } + + @Test + fun toolOutputFallsBackToNoOutputOrError() { + val completed = ChatToolState( + status = ChatProtocol.TOOL_COMPLETED, + content = listOf(ChatToolContent(type = "text", text = "hello")), + ) + assertEquals("hello", toolOutputText(completed)) + assertEquals( + "(no output)", + toolOutputText(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)), + ) + val failed = ChatToolState( + status = ChatProtocol.TOOL_ERROR, + error = net.awan.pipelines.data.protocol.ChatError(type = "boom", message = "exploded"), + ) + assertEquals("exploded", toolOutputText(failed)) + // Still streaming -> nothing yet, never the "(no output)" claim. + assertEquals("", toolOutputText(ChatToolState(status = ChatProtocol.TOOL_RUNNING))) + } + + @Test + fun toolDurationUsesRanToCompletedAndIsNullWhileRunning() { + val done = ChatPart(name = "shell", time = ChatTime(created = 5, ran = 10, completed = 35)) + assertEquals(25L, toolDurationMillis(done)) + assertNull(toolDurationMillis(ChatPart(name = "shell", time = ChatTime(created = 5)))) + assertEquals("340ms", formatToolDuration(340)) + assertEquals("1.5s", formatToolDuration(1500)) + } + + @Test + fun sessionStatusReportsRunningBusyAndIdle() { + assertEquals("Running", sessionStatusLabel(ChatSession(id = "s"), runningLocally = true)) + assertEquals( + "Busy · read-only", + sessionStatusLabel(ChatSession(id = "s", busy = true), runningLocally = false), + ) + assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false)) + } + + @Test + fun toolEditDiffMarksOnlyChangedLinesAndCountsThem() { + val input = JsonObject( + mapOf( + "filePath" to JsonPrimitive("/tmp/a.txt"), + "oldString" to JsonPrimitive("one\ntwo\nthree"), + "newString" to JsonPrimitive("one\nTWO\nthree\nfour"), + ), + ) + val diff = toolEditDiff(input)!! + assertEquals("/tmp/a.txt", diff.file) + assertEquals(2, diff.added) + assertEquals(1, diff.removed) + assertEquals( + listOf( + DiffLine(DiffKind.CONTEXT, "one"), + DiffLine(DiffKind.REMOVE, "two"), + DiffLine(DiffKind.ADD, "TWO"), + DiffLine(DiffKind.CONTEXT, "three"), + DiffLine(DiffKind.ADD, "four"), + ), + diff.lines, + ) + } + + @Test + fun toolEditDiffIsNullForNonEdits() { + assertNull(toolEditDiff(null)) + assertNull(toolEditDiff(JsonObject(mapOf("command" to JsonPrimitive("ls"))))) + } + + @Test + fun sessionTitleNeverBlank() { + assertEquals("Named", sessionTitle(ChatSession(id = "ses_1", title = "Named"))) + assertEquals("ses_abcdefghijklmn", sessionTitle(ChatSession(id = "ses_abcdefghijklmnop"))) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt new file mode 100644 index 00000000..4e004cb4 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt @@ -0,0 +1,217 @@ +package net.awan.pipelines.ui.chat + +import net.awan.pipelines.data.protocol.ChatEventFrame +import net.awan.pipelines.data.protocol.ChatMessage +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatPermissionFrame +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The multi-chat state guarantees: each open chat preserves its own conversation, + * a running session re-syncs when the operator returns to it, and the draft and + * scroll position are per chat. Driven directly against [ChatStore], with no + * device, server or Compose runtime. + */ +class MultiChatStateTest { + + private fun session(id: String, title: String = id, busy: Boolean = false) = + ChatSession(id = id, title = title, busy = busy) + + private fun text(id: String, role: String, body: String) = ChatMessage( + id = id, + sessionId = "", + role = role, + parts = listOf(ChatPart(type = ChatProtocol.PART_TEXT, id = "$id-p", text = body)), + ) + + @Test + fun switchingPreservesEachConversation() { + val store = ChatStore() + assertTrue(store.open(session("a", "Chat A"))) + store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "first"), text("a2", ChatProtocol.ROLE_ASSISTANT, "reply A"))) + + assertTrue(store.open(session("b", "Chat B"))) + store.history("b", listOf(text("b1", ChatProtocol.ROLE_USER, "different"))) + + // Returning to A shows A's conversation, untouched by B. A loaded, + // settled chat needs no re-sync. + assertFalse(store.activate("a")) + assertEquals(listOf("a1", "a2"), store.value.thread("a")!!.messages.map { it.id }) + assertEquals("a", store.value.activeId) + + assertFalse(store.activate("b")) + assertEquals(listOf("b1"), store.value.thread("b")!!.messages.map { it.id }) + } + + @Test + fun runningSessionResyncsOnReturn() { + val store = ChatStore() + store.open(session("a")) + store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt"))) + store.running("a", true) + store.open(session("b")) + store.history("b", emptyList()) + + // Switching to B must not cancel A's running turn. + store.activate("b") + assertTrue(store.value.thread("a")!!.running) + + // Returning to the running chat reports that it must be re-synced. + assertTrue(store.activate("a")) + + // The re-sync replaces the conversation with the server's copy and keeps running. + store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "prompt"), text("a2", ChatProtocol.ROLE_ASSISTANT, "live"))) + val resynced = store.value.thread("a")!! + assertTrue(resynced.running) + assertEquals("live", resynced.messages.last().parts.single().text) + // Once it settles, a later return does not force another re-sync. + store.running("a", false) + store.activate("b") + assertFalse(store.activate("a")) + } + + @Test + fun draftsArePerChat() { + val store = ChatStore() + store.open(session("a")) + store.open(session("b")) + + store.draft("a", "hello from A") + store.draft("b", "typed in B") + + store.activate("a") + assertEquals("hello from A", store.value.thread("a")!!.draft) + store.activate("b") + assertEquals("typed in B", store.value.thread("b")!!.draft) + + // Clearing one chat's draft never touches the other's. + store.clearDraft("b") + assertEquals("", store.value.thread("b")!!.draft) + assertEquals("hello from A", store.value.thread("a")!!.draft) + } + + @Test + fun scrollPositionIsPerChat() { + val store = ChatStore() + store.open(session("a")) + store.open(session("b")) + store.scroll("a", 7, 12) + store.scroll("b", 1, 0) + assertEquals(ChatScrollPosition(7, 12), store.value.thread("a")!!.scroll) + assertEquals(ChatScrollPosition(1, 0), store.value.thread("b")!!.scroll) + } + + @Test + fun busySessionIsReadOnlyAndCannotSend() { + val store = ChatStore() + store.open(session("a", busy = true)) + store.draft("a", "unsent") + val thread = store.value.thread("a")!! + assertTrue(thread.readOnly) + assertFalse(thread.canSend) + + // The server can clear busy later; the chat then becomes writable again. + store.sessionsLoaded(listOf(session("a", busy = false))) + store.draft("a", "unsent") + assertFalse(store.value.thread("a")!!.readOnly) + assertTrue(store.value.thread("a")!!.canSend) + } + + @Test + fun sessionsLoadedMergesStatusWithoutDroppingOpenConversations() { + val store = ChatStore() + store.open(session("a", "Chat A")) + store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "keep me"))) + // The server now reports A busy and adds a new session B. + store.sessionsLoaded(listOf(session("a", "Chat A renamed", busy = true), session("b", "Chat B"))) + + val thread = store.value.thread("a")!! + assertEquals("Chat A renamed", thread.title) + assertTrue(thread.busy) + assertEquals(listOf("a1"), thread.messages.map { it.id }) + assertEquals(2, store.value.sessions.size) + } + + @Test + fun backgroundEventsApplyToTheirChatAndCreateAPlaceholder() { + val store = ChatStore() + store.open(session("a")) + store.history("a", listOf(text("a1", ChatProtocol.ROLE_USER, "go"))) + store.open(session("b")) // B is active + + // A delta for the background chat A lands on A, not on B, and B stays active. + store.event( + ChatEventFrame( + sessionId = "a", + messageId = "a2", + kind = ChatProtocol.PART_TEXT, + delta = "streaming", + part = ChatPart(type = ChatProtocol.PART_TEXT, id = "a2-p"), + ), + ) + assertEquals("streaming", store.value.thread("a")!!.messages.last().parts.single().text) + assertEquals("b", store.value.activeId) + + // A frame for a chat that was never opened creates a placeholder thread. + store.event( + ChatEventFrame( + sessionId = "c", + messageId = "c1", + kind = ChatProtocol.PART_TEXT, + delta = "hi", + part = ChatPart(type = ChatProtocol.PART_TEXT, id = "c1-p"), + ), + ) + assertNotNull(store.value.thread("c")) + assertEquals("hi", store.value.thread("c")!!.messages.single().parts.single().text) + } + + @Test + fun stepFramesTrackRunningState() { + val store = ChatStore() + store.open(session("a")) + store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_STARTED))) + assertTrue(store.value.thread("a")!!.running) + store.event(ChatEventFrame(sessionId = "a", kind = ChatProtocol.EVENT_STEP, step = net.awan.pipelines.data.protocol.ChatStep(status = ChatProtocol.STEP_ENDED))) + assertFalse(store.value.thread("a")!!.running) + } + + @Test + fun locallyRunningBusyChatStaysWritable() { + val store = ChatStore() + store.open(session("a", busy = true)) + store.running("a", true) + // Our own turn keeps the session writable even though the server reports it busy. + store.draft("a", "next prompt") + val thread = store.value.thread("a")!! + assertFalse(thread.readOnly) + assertTrue(thread.canSend) + } + + @Test + fun permissionIsStoredUntilAnswered() { + val store = ChatStore() + store.open(session("a")) + store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r1", action = "edit")) + assertEquals("r1", store.value.thread("a")!!.permission!!.requestId) + store.clearPermission("a") + assertNull(store.value.thread("a")!!.permission) + } + + @Test + fun closeRemovesOnlyThatChat() { + val store = ChatStore() + store.open(session("a")) + store.open(session("b")) + store.close("a") + assertFalse(store.value.open.any { it.sessionId == "a" }) + assertTrue(store.value.open.any { it.sessionId == "b" }) + } +} From d7f650032d001492f1ba4c8d8d72d013e7da4523 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 13:01:39 +0100 Subject: [PATCH 2/8] Render assistant text as markdown in the chat transcript Add a dependency-free CommonMark-subset parser/renderer (ui/chat/Markdown.kt): paragraphs, headings, fenced code, block quotes, bullet/ordered lists, tables, thematic rules and inline code/bold/italic/links/autolinks. The renderer turns blocks into themed, selectable Compose content: fenced code reuses the shared CodeBlock (existing whole-block copy action), tables are a bordered grid with a bold header, links use LinkAnnotation.Url, and inline code/headings use the shared type roles. ChatScreen.MessagePart now calls MarkdownText(part.text) for PART_TEXT instead of a single plain Text; the assistant message stays one SelectionContainer, so all of it remains selectable and long content stays inside the bubble. Geometry reuses the chat tokens (CHAT_ITEM_GAP promoted private -> internal). Add MarkdownTest with 10 unit tests covering fences/language, unterminated fences, soft-wrap joining, headings/rules, lists, tables, inline spans, bare-URL autolinks and snake_case non-emphasis. Document the change in android/README.md. --- android/README.md | 61 +++ .../net/awan/pipelines/ui/chat/ChatScreen.kt | 4 +- .../net/awan/pipelines/ui/chat/Markdown.kt | 462 ++++++++++++++++++ .../awan/pipelines/ui/chat/MarkdownTest.kt | 95 ++++ 4 files changed, 620 insertions(+), 2 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/MarkdownTest.kt diff --git a/android/README.md b/android/README.md index 187a8d42..5806bfad 100644 --- a/android/README.md +++ b/android/README.md @@ -2359,3 +2359,64 @@ Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, Still not verified: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the pass above. + +## Conversation markdown rendering (16 Oct 2026) + +The assistant's `text` part was rendered as one plain `Text`; it is now rendered +as markdown, matching the reference experience (research report Part 1 §1.2). +`android/` only; no new dependency (still just the declared +`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched, +no run started from the app, and `emulator-5556` only (lane A's `emulator-5554` +was never addressed). + +- **Parser.** `ui/chat/Markdown.kt` adds a small, dependency-free CommonMark + subset. It is pure Kotlin (no Compose, no transport) so it is unit-testable: + paragraphs (soft-wrapped lines join with a space), `#`..`######` headings, + fenced code (``` ``` / `~~~`, with the info string as the language), block + quotes, bullet and ordered lists, `|` tables (with a `---` delimiter row), + thematic rules, and inline code / bold / italic / `[label](url)` / + bare-`http(s)://` autolinks. Underscore emphasis needs word boundaries so + `snake_case` is never italicised. Anything outside the subset renders as plain + text, never dropped. +- **Renderer.** The same file turns the blocks into themed, selectable Compose + content: fenced code reuses the shared `CodeBlock`, so the whole-block copy + action is the existing one (label = the fence language, `code` when absent); + tables are a bordered grid with a bold header and equal-weight wrapping cells; + links use `LinkAnnotation.Url`, so they are tap-openable and styled from the + scheme; inline code and headings use the shared type roles + (`pipelinesText()`), not ad-hoc sizes. `ChatScreen.MessagePart` now calls + `MarkdownText(part.text)` for `PART_TEXT`; the assistant message stays one + `SelectionContainer`, so all of it remains selectable and the bounded code + block/table keep long content inside the bubble. Geometry reuses the chat + tokens (`CHAT_ITEM_GAP`, promoted from `private` to `internal`); only the + quote-bar width and table border, which had no token, are new named constants. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD + SUCCESSFUL`; the JUnit XML totals **243 tests, 0 failures, 0 errors, 0 + skipped** (new `MarkdownTest`: fences keep their language, an unterminated + fence still yields code, soft-wrapped paragraphs join, headings/rules parse by + level, bullet/ordered lists, table header/rows, inline code/bold/italic/link, + bare-URL autolink trims trailing punctuation, `snake_case` is not emphasis, + empty source → no blocks). +- The debug APK was installed on `emulator-5556` only and driven against a + stdlib `/connect` WebSocket double serving a fixed history; capture was + validated with `android/scripts/capture_png.sh -s emulator-5556`: + `chat_markdown_conversation.png` shows the bottom-anchored transcript with the + user bubble, the secondary reasoning line, body markdown with inline code and + an underlined link, a `kotlin` fenced code block with its copy action, and the + bordered `Surface | Role` table. `adb -s emulator-5556 logcat -d` held 0 + `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,076,412 bytes, sha256 + `bb290a7f42a3b28e613098dfffea438c34a5332081cffc6a2fbc0d275c207f68`) copied to + `~/.local/share/pipelines/data/artifacts/124/1/pipelines-debug-wip-0718f5b.apk`; + `HEAD` is `0718f5b` and a streamed `curl | shasum -a 256` of + `http://10.0.0.249:8080/artifacts/124/1/pipelines-debug-wip-0718f5b.apk` + matched. + +Not verified: the live brokered server (separate lane), streaming against real +OpenCode, and attachments — unchanged from the passes above. The markdown subset +is intentionally smaller than full CommonMark (no HTML, no reference links, no +nested lists, no strikethrough). diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 51e68c17..17a9a3c8 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -93,7 +93,7 @@ import net.awan.pipelines.ui.theme.pipelinesText * governs touch targets. */ private val CHAT_GUTTER = 16.dp -private val CHAT_ITEM_GAP = 8.dp +internal val CHAT_ITEM_GAP = 8.dp private val CHAT_COMPOSER_GAP = 12.dp private val CHAT_STATUS_DOT = 8.dp @@ -519,7 +519,7 @@ private fun MessageItem(message: ChatMessage) { private fun MessagePart(part: ChatPart) { when (part.type) { ChatProtocol.PART_TEXT -> if (part.text.isNotBlank()) { - Text(part.text, style = MaterialTheme.typography.bodyMedium) + MarkdownText(part.text) } ChatProtocol.PART_REASONING -> ReasoningBlock(part.text) ChatProtocol.PART_TOOL -> ToolCallCard(part) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt new file mode 100644 index 00000000..802f7f06 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/Markdown.kt @@ -0,0 +1,462 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.IntrinsicSize +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.LinkAnnotation +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.TextLinkStyles +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextDecoration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.text.withLink +import androidx.compose.ui.text.withStyle +import androidx.compose.ui.unit.dp +import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * A small, dependency-free CommonMark subset for assistant prose. The brokered + * protocol carries assistant text as markdown and the reference experience renders + * it (research §1.2): body paragraphs, `#`..`######` headings, fenced code (the + * shared [CodeBlock], so the copy action comes for free), block quotes, bullet and + * ordered lists, `|` tables, thematic rules, and inline code / bold / italic / + * links. Anything outside the subset renders as plain text, never dropped. + * + * The parser is pure Kotlin (no Compose, no transport) so it is unit-testable; the + * composables below turn the same blocks into themed, selectable content. + */ + +// ---- Parsed model ------------------------------------------------------------ + +internal sealed interface MdBlock + +internal data class MdHeading(val level: Int, val text: String) : MdBlock +internal data class MdParagraph(val text: String) : MdBlock +internal data class MdCodeBlock(val language: String, val code: String) : MdBlock +internal data class MdQuote(val lines: List) : MdBlock +internal data class MdListBlock(val ordered: Boolean, val items: List) : MdBlock +internal data class MdTableBlock(val header: List, val rows: List>) : MdBlock +internal data object MdRule : MdBlock + +internal sealed interface MdSpan + +internal data class MdPlain(val text: String) : MdSpan +internal data class MdCodeSpan(val text: String) : MdSpan +internal data class MdStrong(val spans: List) : MdSpan +internal data class MdEmphasis(val spans: List) : MdSpan +internal data class MdLinkSpan(val spans: List, val url: String) : MdSpan + +// ---- Block parser ------------------------------------------------------------ + +/** Parses [source] into the block list the renderer walks. Never throws. */ +internal fun parseMarkdown(source: String): List { + val lines = source.replace("\r\n", "\n").replace('\r', '\n').split('\n') + val blocks = mutableListOf() + var i = 0 + while (i < lines.size) { + val line = lines[i] + val trimmed = line.trim() + when { + trimmed.isEmpty() -> i++ + + fenceRun(trimmed) != null -> { + val fence = fenceRun(trimmed)!! + val language = trimmed.removePrefix(fence).trim().substringBefore(' ') + val code = mutableListOf() + i++ + while (i < lines.size && fenceRun(lines[i].trim()) == null) { + code.add(lines[i]) + i++ + } + if (i < lines.size) i++ // consume the closing fence + blocks.add(MdCodeBlock(language, code.joinToString("\n"))) + } + + headingLevel(trimmed) > 0 -> { + val level = headingLevel(trimmed) + blocks.add(MdHeading(level, trimmed.drop(level).trim().trimEnd('#'))) + i++ + } + + isRule(trimmed) -> { + blocks.add(MdRule) + i++ + } + + trimmed.startsWith(">") -> { + val quote = mutableListOf() + while (i < lines.size && lines[i].trim().startsWith(">")) { + quote.add(lines[i].trim().removePrefix(">").removePrefix(" ").trimEnd()) + i++ + } + blocks.add(MdQuote(quote)) + } + + isTableStart(lines, i) -> { + val header = splitRow(lines[i]) + i += 2 // header + delimiter row + val rows = mutableListOf>() + while (i < lines.size && lines[i].contains('|') && lines[i].isNotBlank()) { + rows.add(fitRow(splitRow(lines[i]), header.size)) + i++ + } + blocks.add(MdTableBlock(header, rows)) + } + + listMarker(line) != null -> { + val ordered = listMarker(line)!!.first + val items = mutableListOf() + while (i < lines.size && listMarker(lines[i])?.first == ordered) { + items.add(listMarker(lines[i])!!.second) + i++ + } + blocks.add(MdListBlock(ordered, items)) + } + + else -> { + val paragraph = mutableListOf(line.trim()) + i++ + while (i < lines.size && lines[i].isNotBlank() && !startsBlock(lines, i)) { + paragraph.add(lines[i].trim()) + i++ + } + blocks.add(MdParagraph(paragraph.joinToString(" "))) + } + } + } + return blocks +} + +/** The fence run (` ``` ` / `~~~`) a line opens or closes with, or null. */ +private fun fenceRun(trimmed: String): String? { + val first = trimmed.firstOrNull() ?: return null + if (first != '`' && first != '~') return null + val run = trimmed.takeWhile { it == first } + return if (run.length >= 3) run else null +} + +private fun headingLevel(trimmed: String): Int { + val hashes = trimmed.takeWhile { it == '#' }.length + if (hashes == 0 || hashes > 6) return 0 + return if (trimmed.length == hashes || trimmed[hashes] == ' ') hashes else 0 +} + +private fun isRule(trimmed: String): Boolean = + trimmed.length >= 3 && trimmed.all { it == trimmed[0] } && trimmed[0] in "-*_" + +/** True when [lines] at [index] is a table header followed by a `---` delimiter row. */ +private fun isTableStart(lines: List, index: Int): Boolean { + if (index + 1 >= lines.size || !lines[index].contains('|')) return false + val delimiter = splitRow(lines[index + 1]) + if (delimiter.isEmpty() || splitRow(lines[index]).size < 2) return false + return delimiter.all { cell -> cell.isNotEmpty() && cell.all { it == '-' || it == ':' } && cell.contains('-') } +} + +/** Splits a table row on unescaped `|`, dropping the leading/trailing empty cell. */ +private fun splitRow(line: String): List = + line.trim().removePrefix("|").removeSuffix("|").split('|').map { it.replace("\\|", "|").trim() } + +private fun fitRow(row: List, size: Int): List = + List(size) { row.getOrElse(it) { "" } } + +/** The ordered flag and item text of a list line, or null for a non-item line. */ +private fun listMarker(line: String): Pair? { + val trimmed = line.trimStart() + val orderedMatch = ORDERED_ITEM.matchEntire(trimmed) + if (orderedMatch != null) return true to orderedMatch.groupValues[2] + val bulletMatch = BULLET_ITEM.matchEntire(trimmed) + if (bulletMatch != null) return false to bulletMatch.groupValues[2] + return null +} + +/** True when [lines] at [index] begins a block that must interrupt a paragraph. */ +private fun startsBlock(lines: List, index: Int): Boolean { + val trimmed = lines[index].trim() + return fenceRun(trimmed) != null || + headingLevel(trimmed) > 0 || + isRule(trimmed) || + trimmed.startsWith(">") || + listMarker(lines[index]) != null || + isTableStart(lines, index) +} + +// ---- Inline parser ----------------------------------------------------------- + +/** + * Parses inline markup in [text] into a flat span tree. Handles `` `code` ``, + * `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare + * `http(s)://` autolinks; everything else stays plain text. Underscore emphasis + * requires word boundaries so `snake_case` is never italicised. + */ +internal fun parseInline(text: String): List { + val spans = mutableListOf() + val buffer = StringBuilder() + var i = 0 + + fun flush() { + if (buffer.isNotEmpty()) { + spans.add(MdPlain(buffer.toString())) + buffer.clear() + } + } + + while (i < text.length) { + val c = text[i] + when { + c == '`' -> { + val end = text.indexOf('`', i + 1) + if (end > i) { + flush() + spans.add(MdCodeSpan(text.substring(i + 1, end))) + i = end + 1 + } else { + buffer.append(c); i++ + } + } + + c == '*' || c == '_' -> { + val doubled = i + 1 < text.length && text[i + 1] == c + val marker = if (doubled) "$c$c" else c.toString() + val boundOk = c != '_' || i == 0 || !text[i - 1].isLetterOrDigit() + val end = if (boundOk) text.indexOf(marker, i + marker.length) else -1 + val closes = end > i + marker.length && + (c != '_' || end + 1 >= text.length || !text[end + 1].isLetterOrDigit()) + if (closes) { + flush() + val inner = parseInline(text.substring(i + marker.length, end)) + spans.add(if (doubled) MdStrong(inner) else MdEmphasis(inner)) + i = end + marker.length + } else { + buffer.append(c); i++ + } + } + + c == '[' -> { + val close = text.indexOf(']', i + 1) + if (close > i && close + 1 < text.length && text[close + 1] == '(') { + val urlEnd = text.indexOf(')', close + 2) + val url = if (urlEnd > close) text.substring(close + 2, urlEnd).trim() else "" + if (url.isNotEmpty()) { + flush() + spans.add(MdLinkSpan(parseInline(text.substring(i + 1, close)), url)) + i = urlEnd + 1 + } else { + buffer.append(c); i++ + } + } else { + buffer.append(c); i++ + } + } + + else -> { + val url = autolinkAt(text, i) + if (url != null) { + flush() + spans.add(MdLinkSpan(listOf(MdPlain(url)), url)) + i += url.length + } else { + buffer.append(c); i++ + } + } + } + } + flush() + return spans +} + +/** A bare `http(s)://` URL starting exactly at [index], trailing punctuation trimmed. */ +private fun autolinkAt(text: String, index: Int): String? { + if (!text.startsWith("http://", index) && !text.startsWith("https://", index)) return null + var end = index + while (end < text.length && !text[end].isWhitespace() && text[end] !in "<>\"'") end++ + var url = text.substring(index, end) + while (url.isNotEmpty() && url.last() in ".,;:!?)]}") url = url.dropLast(1) + return url.takeIf { it.length > "https://".length } +} + +private val ORDERED_ITEM = Regex("""^(\d{1,9})[.)]\s+(.*)$""") +private val BULLET_ITEM = Regex("""^([-*+])\s+(.*)$""") + +// ---- Renderers --------------------------------------------------------------- + +private val MD_QUOTE_BAR = 3.dp +private val MD_TABLE_BORDER = 1.dp + +/** + * Renders [text] as markdown at the app's shared body style. The caller owns the + * selection container (a chat message is one selectable region), so this only + * lays out the blocks. + */ +@Composable +internal fun MarkdownText(text: String, modifier: Modifier = Modifier) { + val blocks = remember(text) { parseMarkdown(text) } + Column(modifier, verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + blocks.forEach { MarkdownBlock(it) } + } +} + +@Composable +private fun MarkdownBlock(block: MdBlock) { + val texts = pipelinesText() + when (block) { + is MdHeading -> Text( + text = inline(block.text), + style = when (block.level) { + 1 -> MaterialTheme.typography.titleLarge + 2 -> MaterialTheme.typography.titleMedium + else -> texts.cardTitle + }, + color = MaterialTheme.colorScheme.onSurface, + ) + + is MdParagraph -> Text(text = inline(block.text), style = texts.body) + + is MdCodeBlock -> CodeBlock(label = block.language.ifBlank { "code" }, text = block.code) + + MdRule -> HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + + is MdQuote -> Row(Modifier.height(IntrinsicSize.Min)) { + Box( + Modifier + .width(MD_QUOTE_BAR) + .fillMaxHeight() + .background(MaterialTheme.colorScheme.outlineVariant), + ) + Column( + modifier = Modifier.padding(start = CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2), + ) { + block.lines.forEach { line -> + if (line.isNotBlank()) { + Text( + text = inline(line), + style = texts.body, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + } + + is MdListBlock -> Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP / 2)) { + block.items.forEachIndexed { index, item -> + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Text( + text = if (block.ordered) "${index + 1}." else "•", + style = texts.body, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text(text = inline(item), style = texts.body) + } + } + } + + is MdTableBlock -> MarkdownTable(block) + } +} + +@Composable +private fun MarkdownTable(table: MdTableBlock) { + val border = MaterialTheme.colorScheme.outlineVariant + val shape = RoundedCornerShape(CHAT_ITEM_GAP) + Column( + Modifier + .fillMaxWidth() + .clip(shape) + .border(MD_TABLE_BORDER, border, shape), + ) { + TableRow(table.header, header = true, border = border) + table.rows.forEach { row -> + HorizontalDivider(color = border) + TableRow(row, header = false, border = border) + } + } +} + +@Composable +private fun TableRow(cells: List, header: Boolean, border: Color) { + val texts = pipelinesText() + Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min)) { + cells.forEachIndexed { index, cell -> + if (index > 0) { + Box(Modifier.width(MD_TABLE_BORDER).fillMaxHeight().background(border)) + } + Text( + text = inline(cell), + style = if (header) texts.body.copy(fontWeight = FontWeight.Bold) else texts.body, + modifier = Modifier.weight(1f).padding(CHAT_ITEM_GAP), + maxLines = if (header) 1 else Int.MAX_VALUE, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + +/** Inline text as one [AnnotatedString]; links are tappable and code is monospace. */ +@Composable +private fun inline(text: String): AnnotatedString { + val linkColor = MaterialTheme.colorScheme.primary + val codeBackground = MaterialTheme.colorScheme.surfaceContainerHigh + val codeColor = MaterialTheme.colorScheme.onSurface + return remember(text, linkColor, codeBackground, codeColor) { + buildInline(parseInline(text), linkColor, codeBackground, codeColor) + } +} + +private fun buildInline( + spans: List, + linkColor: Color, + codeBackground: Color, + codeColor: Color, +): AnnotatedString = buildAnnotatedString { appendSpans(spans, linkColor, codeBackground, codeColor) } + +private fun androidx.compose.ui.text.AnnotatedString.Builder.appendSpans( + spans: List, + linkColor: Color, + codeBackground: Color, + codeColor: Color, +) { + for (span in spans) { + when (span) { + is MdPlain -> append(span.text) + is MdCodeSpan -> withStyle( + SpanStyle(fontFamily = FontFamily.Monospace, background = codeBackground, color = codeColor), + ) { append(span.text) } + is MdStrong -> withStyle(SpanStyle(fontWeight = FontWeight.Bold)) { + appendSpans(span.spans, linkColor, codeBackground, codeColor) + } + is MdEmphasis -> withStyle(SpanStyle(fontStyle = FontStyle.Italic)) { + appendSpans(span.spans, linkColor, codeBackground, codeColor) + } + is MdLinkSpan -> withLink( + LinkAnnotation.Url( + span.url, + TextLinkStyles(style = SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)), + ), + ) { appendSpans(span.spans, linkColor, codeBackground, codeColor) } + } + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/MarkdownTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/MarkdownTest.kt new file mode 100644 index 00000000..26f3c923 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/MarkdownTest.kt @@ -0,0 +1,95 @@ +package net.awan.pipelines.ui.chat + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class MarkdownTest { + + @Test + fun fencedCodeKeepsTheLanguageAndBody() { + val blocks = parseMarkdown( + """ + Intro text. + + ```kotlin + val gap = 8.dp + println(gap) + ``` + """.trimIndent(), + ) + assertEquals(MdParagraph("Intro text."), blocks[0]) + val code = blocks[1] as MdCodeBlock + assertEquals("kotlin", code.language) + assertEquals("val gap = 8.dp\nprintln(gap)", code.code) + } + + @Test + fun anUnterminatedFenceStillYieldsItsCode() { + val blocks = parseMarkdown("```\nline one\nline two") + val code = blocks.single() as MdCodeBlock + assertEquals("", code.language) + assertEquals("line one\nline two", code.code) + } + + @Test + fun softWrappedParagraphLinesJoinWithASpace() { + assertEquals(listOf(MdParagraph("one two three")), parseMarkdown("one\ntwo\nthree")) + assertEquals(listOf(MdParagraph("one"), MdParagraph("two")), parseMarkdown("one\n\ntwo")) + } + + @Test + fun headingsAndThematicRulesParseByLevel() { + val blocks = parseMarkdown("# Title\n\n## Section\n\n---") + assertEquals(MdHeading(1, "Title"), blocks[0]) + assertEquals(MdHeading(2, "Section"), blocks[1]) + assertEquals(MdRule, blocks[2]) + } + + @Test + fun bulletAndOrderedListsKeepTheirOrder() { + val bullets = parseMarkdown("- one\n- two").single() as MdListBlock + assertEquals(false, bullets.ordered) + assertEquals(listOf("one", "two"), bullets.items) + + val ordered = parseMarkdown("1. first\n2. second").single() as MdListBlock + assertEquals(true, ordered.ordered) + assertEquals(listOf("first", "second"), ordered.items) + } + + @Test + fun aPipeTableParsesHeaderAndRows() { + val blocks = parseMarkdown("| Name | Value |\n| --- | ---: |\n| a | 1 |\n| b | 2 |") + val table = blocks.single() as MdTableBlock + assertEquals(listOf("Name", "Value"), table.header) + assertEquals(listOf(listOf("a", "1"), listOf("b", "2")), table.rows) + } + + @Test + fun inlineCodeBoldItalicAndLinksBecomeSpans() { + val spans = parseInline("Use `CodeBlock` and **bold** and *italic* and [docs](https://example.com/x).") + assertTrue(spans.any { it is MdCodeSpan && it.text == "CodeBlock" }) + assertTrue(spans.any { it is MdStrong }) + assertTrue(spans.any { it is MdEmphasis }) + val link = spans.filterIsInstance().single() + assertEquals("https://example.com/x", link.url) + } + + @Test + fun bareUrlsAutolinkAndTrimTrailingPunctuation() { + val spans = parseInline("See https://example.com/a, then stop.") + val link = spans.filterIsInstance().single() + assertEquals("https://example.com/a", link.url) + } + + @Test + fun underscoresInsideAWordAreNotEmphasis() { + assertEquals(listOf(MdPlain("snake_case_name")), parseInline("snake_case_name")) + } + + @Test + fun anEmptySourceParsesToNoBlocks() { + assertEquals(emptyList(), parseMarkdown("")) + assertEquals(emptyList(), parseMarkdown("\n\n")) + } +} From 291cec2bdae577ab948156a7e6de35a6f3d0c3fb Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 14:17:50 +0100 Subject: [PATCH 3/8] Show chat tool calls as expandable INPUT/OUTPUT chips Render each assistant turn's tool calls the way the reference jarvis chat does: one compact chip per call showing the tool name, its duration and a spinner while it runs, with consecutive calls of a turn grouped into one wrapping row so the transcript stays scannable (ChatScreen AssistantParts / ToolCalls). Tapping a chip opens a floating panel over the transcript with INPUT as pretty-printed JSON and OUTPUT as monospace, plus copy actions. The panel is dismissible by tapping outside or its Close action and is positioned by ToolPanelPositionProvider so it never moves the conversation (the transcript scroll position is untouched while the overlay is open). A failed call is shown as failed and renders both its diff (when present) and an ERROR block. ERROR text now comes from the new toolErrorText, which prefers the server's error message over any partial output, while toolOutputText is the OUTPUT derivation again; toolFailed identifies the error state. While a turn streams, the transcript follows the newest content with a hard jump unless the operator has dragged away, driven by listState.interactionSource.interactions (DragInteraction.Start/Stop/Cancel) rather than programmatic scrolls. The running indicator and its live elapsed time derive from the turn's own start (ChatThread.elapsedMillis, an injectable clock in ChatStore) so they survive a chat switch. A reconnecting socket now settles every open chat and re-fetches its history (ChatStore.streamResumed, AppViewModel.observeConnection), and a server-pushed stream error with no session id settles the sole/active running turn with the server's message instead of leaving the indicator spinning. Tests: ChatFormatTest covers toolErrorText; new ChatStreamTest covers the streaming/elapsed/reconnect/stream-error guarantees against an injected clock; new ToolPanelPositionProviderTest covers the panel's below/flip/margin placement. README's chat section documents the follow-the-stream mechanism. --- android/README.md | 244 +++++++++++++++ .../net/awan/pipelines/ui/AppViewModel.kt | 27 ++ .../net/awan/pipelines/ui/chat/ChatFormat.kt | 16 +- .../net/awan/pipelines/ui/chat/ChatScreen.kt | 284 ++++++++++++++++-- .../net/awan/pipelines/ui/chat/ChatStore.kt | 72 ++++- .../awan/pipelines/ui/chat/ChatFormatTest.kt | 30 +- .../awan/pipelines/ui/chat/ChatStreamTest.kt | 133 ++++++++ .../ui/chat/ToolPanelPositionProviderTest.kt | 42 +++ 8 files changed, 813 insertions(+), 35 deletions(-) create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ChatStreamTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ToolPanelPositionProviderTest.kt diff --git a/android/README.md b/android/README.md index 5806bfad..be295849 100644 --- a/android/README.md +++ b/android/README.md @@ -2420,3 +2420,247 @@ Not verified: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. The markdown subset is intentionally smaller than full CommonMark (no HTML, no reference links, no nested lists, no strikethrough). + +## Streaming replies (16 Oct 2026) + +The live delta/streaming pass promised by the first slice. `android/` only; no new +dependency (still just the declared `material-icons-extended`), no Pipelines +server/Go/installer/Docker file touched, no run started from the app, and +`emulator-5556` only (lane A's `emulator-5554` was never addressed). + +- **Turn lifecycle in the model.** `ChatStore` now owns `ChatThread.runningSince` + and one private `setRunning` transition, so a turn that begins is stamped with + the wall clock and settling clears it; `ChatThread.elapsedMillis(now)` is the one + pure derivation the indicator and its test share. `event` already appended + `text`/`reasoning` deltas to the target part and upserted tool parts, wherever the + frame's chat sits in the open order. +- **Running indicator.** The transcript's indicator shows the spinner, `Working…` + and the live elapsed time (ticked once a second, never per frame, through the + shared `formatDuration`). Its tick loop is keyed on the turn's start and stops the + moment the turn settles, and the elapsed value keeps counting across a chat + switch because it lives on the thread, not the composable. +- **Follow the stream.** The transcript hard-jumps to the newest item while a turn + runs — a fast-growing reply outruns an animation — unless the operator has + scrolled up to read; returning to the end resumes following. Consuming the list + state's `interactionSource.interactions` (`DragInteraction.Start`/`Stop`/`Cancel`) + distinguishes a user drag from the programmatic jump, so the jump never un-sticks + the view. +- **Reconnect resync.** `AppViewModel.observeConnection` re-fetches every open + chat's history whenever the socket transitions to `Connected`, after + `ChatStore.streamResumed()` settles each running thread (a still-live stream + re-asserts `running` on its next frame, so no stale `Working…` sticks). The + resync *replaces* the conversation wholesale, so a gap can neither duplicate nor + drop text. +- **Failure settle.** A server-pushed `error` frame carries no session id (the + brokered protocol cannot attribute it), so `ChatStore.streamError` settles the + sole running chat — or the active one when several are in flight — and keeps the + server's text; with nothing running it is ignored. The prompt-call failure path + already settled the turn and is unchanged. +- **Non-blocking.** Unsolicited frames reach the UI through the client's bounded + `SharedFlow` (`tryEmit` from the socket thread, `DROP_OLDEST` capacity 256), so a + slow collector never blocks the read loop; each mutation touches only its chat and + the `LazyColumn` keys limit recomposition to the changed item. + +Evidence (macOS, JDK 17 target, Gradle 9.7.1, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the JUnit + XML totals **248 tests, 0 failures, 0 errors, 0 skipped** (new `ChatStreamTest`: + a delta sequence grows the rendered text and toggles the running indicator, the + elapsed time comes from the turn's own start and a repeated start keeps it, + `streamResumed` settles every open chat and returns them for re-fetch, + `streamError` settles the running turn with the server's text and is ignored with + nothing running). +- The debug APK was installed on `emulator-5556` only and driven with + `uiautomator dump`/`input tap` against `.stream_check/stream_stub.py` (a stdlib + `/connect` WebSocket double that streams `chat_event` frames; test scaffolding, + not the app — the deployed server still predates chat). Captures were validated + with `android/scripts/capture_png.sh -s emulator-5556`: a mid-stream reply with + the growing transcript and the indicator at `Working… · 1s` + (`chat_stream_01_early`) and `Working… · 4s` with the list followed to the newest + line (`chat_stream_02_mid`); the settled turn with the completed `bash 340ms` + tool chip, no indicator and the send control restored (`chat_stream_03_settled`); + and, after a mid-stream drag up, the transcript **staying** where the operator + left it while the turn still ran (`chat_stream_04_scrolled_up`). `adb -s + emulator-5556 logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` + during the sweep. +- **APK publish.** `app-debug.apk` (18,262,465 bytes, sha256 + `ef435b662e6f7e7467b5ae25b69fb24f8904334af204224aad00bfd76879a84e`) copied to + `~/.local/share/pipelines/data/artifacts/126/1/pipelines-debug-wip-d7f6500.apk`; + `curl -I http://10.0.0.249:8080/artifacts/126/1/pipelines-debug-wip-d7f6500.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18262465`, and a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged. `:app:lintDebug` could not run +in this environment: the Gradle JVM reports `25.0.4.1`, a version string the AGP +8.7.2 lint (IntelliJ `JavaVersion`) rejects, so lint fails before analysing the +tree; this is environmental and unrelated to the change. + +## Tool-call chips and the expandable panel (16 Oct 2026) + +The tool-call surface now matches the reference chat's `_ToolCalls`/`_ToolChip` +and `_buildPanel` (research §1.3) more closely. `android/` only; no new +dependency (still just the declared `material-icons-extended`), no Pipelines +server/Go/installer/Docker file touched, no run started from the app, and +`emulator-5556` only (lane A's `emulator-5554` was never addressed). + +- **Grouped chips.** A run of consecutive `tool` parts in one assistant turn is + now one `FlowRow` of compact chips (`ToolCalls`/`ToolChip`), so the turn's calls + sit together and wrap instead of each taking a full-width row. Each chip keeps + its kind icon, label (the edited file for an `edit`), `+N -M` diff stat, + duration and running spinner. +- **Overlay panel, scroll preserved.** Tapping a chip opens its INPUT/OUTPUT + panel as a `Popup` anchored to that chip, not as inline content. The former + inline panel re-flowed the transcript (a short chat visibly jumped); the popup + is outside the list layout, so opening, failing or dismissing it never moves the + conversation's scroll anchor. `ToolPanelPositionProvider` places it below the + chip, flips it above when there is no room, and keeps it inside the window + margins. The panel is dismissible by its own X or by tapping outside, and its + INPUT and OUTPUT blocks carry the shared `CodeBlock` copy action. +- **Visible failure.** An `error` tool call is now unmistakable: an + error-tinted chip with an `ErrorOutline` icon (`toolFailed`), and its panel + shows an ERROR block with the tool's error text (`ChatFormat.toolFailed`). +- **Diff cards preserved.** An `edit`-family chip still expands to the synthesised + green/red diff (`toolEditDiff`/`DiffView`), unchanged. + +Evidence (macOS, Gradle 9.7.1 `--offline`, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD + SUCCESSFUL`; the JUnit XML totals **252 tests, 0 failures, 0 errors, 0 + skipped** (new `toolFailedOnlyForTheErrorStatus`, and + `ToolPanelPositionProviderTest`: below-the-chip, flip-above and margin-clamp + placement). +- The debug APK was installed on `emulator-5556` only and driven against + `.tool_calls_check/chat_stub_tools.py` (a stdlib `/connect` WebSocket double + serving the documented `internal/protocol/chat.go` JSON; test scaffolding, not + the app). Captures were validated with `android/scripts/capture_png.sh -s + emulator-5556`: `01_tools_collapsed.png` (the completed `bash 340ms` and + `src/layout.kt +2 -2 300ms` chips grouped), `02_tools_expanded.png` (the bash + chip expanded to INPUT pretty JSON + OUTPUT monospace with the transcript behind + it unmoved — the chips keep the same on-screen position), and + `03_error_chip_collapsed.png`/`04_error_chip_expanded.png` (the failed `shell` + chip in the error container and its panel INPUT + ERROR text). Tapping outside + the panel dismissed it with the chips still in place. `adb -s emulator-5556 + logcat -d` held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,262,465 bytes, sha256 + `160f10ea8a2dc80364bb7f38596d50d08557ccce01f99705b93a8b9bc9216c27`) copied to + `~/.local/share/pipelines/data/artifacts/129/1/pipelines-debug-wip-d7f6500.apk`; + `curl -I http://10.0.0.249:8080/artifacts/129/1/pipelines-debug-wip-d7f6500.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18262465`, and a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. + +## Tool-call review fixes (16 Oct 2026) + +Two findings from the tool-call slice review, both in `android/`, under the same +constraints as above (no new dependency beyond the declared +`material-icons-extended`, no Pipelines server/Go/installer/Docker file touched, +no run started from the app, `emulator-5556` only). + +- **One elapsed derivation.** `ChatScreen.rememberElapsedMillis` re-derived the + running turn's elapsed time by subtracting the start itself, duplicating the + tested `ChatThread.elapsedMillis` and contradicting the two KDocs that claimed + the indicator shared the model's derivation. The composable now ticks a + `rememberElapsedNow(runningSince)` wall clock (once a second, and only while + the turn lives) and reads `thread.elapsedMillis(now)`, so the model and the UI + cannot drift. +- **No per-frame allocation.** `ToolCalls` keyed its open-panel `remember` on + `parts.map { it.id }`, allocating a list on every streaming recomposition. The + key is unnecessary — an id no longer among the calls simply matches nothing — + so `openId` is plain remembered state and a streaming rebuild no longer + allocates a key list. + +Evidence (macOS, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD + SUCCESSFUL`; the JUnit XML totals **252 tests, 0 failures, 0 errors, 0 + skipped**. +- The rebuilt debug APK was installed on `emulator-5556` only and driven against + `.tool_calls_check/chat_stub_tools.py` and `chat_stub_error.py` (stdlib + `/connect` WebSocket doubles serving the documented `internal/protocol/chat.go` + JSON; test scaffolding, not the app). Captures were validated with + `android/scripts/capture_png.sh -s emulator-5556` into `.tool_calls_fix/`: + `01_tools_collapsed.png` (the completed `bash 340ms` and `src/layout.kt +2 -2 + 300ms` chips grouped), `02_tools_expanded.png` (the bash chip's INPUT pretty + JSON + OUTPUT monospace), `04_diff_card.png` (the edit chip's synthesised + green/red diff card), `03_dismissed_outside.png` (tapping outside dismissed the + panel with both chips at the same on-screen bounds), and + `05_error_chip_collapsed.png`/`06_error_chip_expanded.png` (the failed `shell` + chip in the error container, with a `Failed tool call` description, and its + panel INPUT + ERROR text). `adb -s emulator-5556 logcat -d` held 0 `FATAL + EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,219,766 bytes, sha256 + `b607a879ce2f2ac324fe6fa254918a456337c678abc1781bb79a05d88d539984`) copied to + `~/.local/share/pipelines/data/artifacts/129/3/pipelines-debug-wip-d7f6500.apk`; + `curl -I http://10.0.0.75:8080/artifacts/129/3/pipelines-debug-wip-d7f6500.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18219766`, and a streamed `GET | shasum -a 256` matched. This + supersedes the `129/1` publish above: it is built from the current source, so + the change is in the served artifact (a fresh rebuild can still differ in + `classes5.dex` — the reproducibility caveat recorded in review stands). + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. +`:app:lintDebug` still cannot run here (the Gradle JVM's `25.0.4.1` version +string is rejected by AGP 8.7.2 lint), unchanged from the slice above. + +## Tool-call review fixes, second pass (16 Oct 2026) + +Three findings from the tool-call slice's second review, all in `android/` under +the same constraints (no new dependency beyond the declared +`material-icons-extended`, no Pipelines server/Go/installer/Docker file touched, no +run started from the app, `emulator-5556` only). + +- **A failed edit call shows its error.** The panel only rendered the diff for an + `edit`-family call, because the `diff != null` branch sat above the `failed` + check, so a *failed* edit showed no error text. The ERROR block is now emitted + whenever `toolFailed`, alongside the diff when one exists; a failed non-edit call + keeps INPUT + ERROR, and a successful edit still shows the diff alone. +- **The error message, not the partial output.** `ChatFormat.toolOutputText` + returned non-blank `state.content` before it considered `state.error`, and that + text fed the ERROR block, so a failed call carrying both showed its partial + output under the ERROR heading. The failed call's text now comes from the new + `toolErrorText`, which prefers the server's message and falls back to the output + text only when the failure carries none; `toolOutputText` is the OUTPUT + derivation again. +- **README mechanism corrected.** The follow-the-stream bullet claimed a + `snapshotFlow` on the list's scroll state; the code consumes + `listState.interactionSource.interactions` (`DragInteraction.Start`/`Stop`/`Cancel`), + as the bullet now says. + +Evidence (macOS, Gradle 9.7.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the + JUnit XML totals **253 tests, 0 failures, 0 errors, 0 skipped** (the failed-text + helper split into `toolOutputFallsBackToNoOutput` and + `toolErrorPrefersTheMessageOverPartialOutput`, which asserts the message wins over + a failed call's partial output). +- The rebuilt debug APK was installed on `emulator-5556` only and driven against + `.tool_calls_fix2/chat_stub_failed_edit.py` (the review tool stub plus a failed + `edit` call with `oldString`/`newString` and a failed `bash` call carrying both + partial output and an error; stdlib `/connect` WebSocket double, test + scaffolding, not the app). Captures were validated with + `android/scripts/capture_png.sh -s emulator-5556` into `.tool_calls_fix2/`: + `04_failed_edit_expanded.png` shows the failed edit chip's diff *and* its ERROR + block (`oldString not found in src/layout.kt`), and + `06_failed_bash_expanded.png` shows the failed bash call's INPUT + ERROR + (`exit status 2: src/nope.kt: No such file`), the error text — not the partial + output — under the ERROR heading. `uiautomator dump` confirms the same nodes; + `adb -s emulator-5556 logcat -d` held 0 `FATAL EXCEPTION` and 0 `E + AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,219,360 bytes, sha256 + `4522aa62c8a3a59033aa2cca8b7fba65267dbdde473284585eaae47f03aeda2f`) copied to + `~/.local/share/pipelines/data/artifacts/129/5/pipelines-debug-wip-d7f6500.apk`; + `curl -I http://10.0.0.249:8080/artifacts/129/5/pipelines-debug-wip-d7f6500.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18219360`, and a streamed `GET | shasum -a 256` matched. This + supersedes the `129/3` publish above: it is rebuilt from the current source, so + the fix is in the served artifact (the `classes5.dex` reproducibility caveat + recorded in review stands). + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index 59dd52a0..59b0746b 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -22,6 +22,7 @@ import net.awan.pipelines.data.protocol.BuildInfo import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.PipelineDetail import net.awan.pipelines.data.protocol.PipelineSummary +import net.awan.pipelines.data.protocol.Protocol import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.SessionEvidence import net.awan.pipelines.data.transport.ConnectionState @@ -113,6 +114,7 @@ class AppViewModel( reconnect() } observeChatEvents() + observeConnection() } /** @@ -128,6 +130,31 @@ class AppViewModel( // Never silently drop an approval request: it is held per chat and // answered with chat_reply from the conversation's approval bar. message.chatPermission?.let { chatStore.permission(it) } + // An unsolicited server error has no request id to match, so it is + // the chat stream failing mid-turn: settle the running chat instead + // of leaving its indicator spinning forever. + if (message.id == null && message.type == Protocol.ERROR) { + chatStore.streamError(message.error?.takeIf { it.isNotBlank() } ?: "The chat stream failed.") + } + } + } + } + + /** + * Re-syncs every open chat when the socket (re)connects: the frames sent + * during the gap are gone, so the conversation is re-fetched from history + * rather than trusted. A running chat is marked settled first and a still-live + * stream re-asserts it on its next frame, so a stale `Working…` never sticks. + */ + private fun observeConnection() { + viewModelScope.launch { + var connected = false + connectionState.collect { state -> + val isConnected = state is ConnectionState.Connected + if (isConnected && !connected) { + chatStore.streamResumed().forEach { loadChatHistory(it) } + } + connected = isConnected } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index a1a98709..d940f8a6 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -40,11 +40,22 @@ internal fun toolOutputText(state: ChatToolState?): String { .filter { it.type == "text" && it.text.isNotBlank() } .joinToString("\n") { it.text } if (text.isNotBlank()) return text - if (state.error != null) return state.error.message if (ChatProtocol.toolRunning(state)) return "" return "(no output)" } +/** + * The ERROR section of a failed tool call. The server's error message takes + * precedence over any partial output the call had already produced — a failed + * call can carry both, and the output text must not be labelled as the error — + * falling back to the output text so the block is never blank when the failure + * carries no message. + */ +internal fun toolErrorText(state: ChatToolState?): String { + val message = state?.error?.message + return if (!message.isNullOrBlank()) message else toolOutputText(state) +} + /** Wall-clock duration of a tool call, or null while it has no completion time. */ internal fun toolDurationMillis(part: ChatPart): Long? { val time = part.time ?: return null @@ -53,6 +64,9 @@ internal fun toolDurationMillis(part: ChatPart): Long? { return time.completed - start } +/** True when a tool call ended in an error state. */ +internal fun toolFailed(state: ChatToolState?): Boolean = state?.status == ChatProtocol.TOOL_ERROR + /** Compact millisecond duration, e.g. `340ms` / `1.2s` / `2m 3s`. */ internal fun formatToolDuration(millis: Long): String = when { millis < 1_000 -> "${millis}ms" diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 17a9a3c8..18d4ccb5 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -3,9 +3,12 @@ package net.awan.pipelines.ui.chat import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -31,6 +34,7 @@ import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Psychology @@ -55,19 +59,30 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import androidx.compose.ui.window.PopupPositionProvider +import androidx.compose.ui.window.PopupProperties import androidx.compose.foundation.selection.selectable import androidx.activity.compose.PredictiveBackHandler import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.collect import net.awan.pipelines.data.protocol.ChatMessage import net.awan.pipelines.data.protocol.ChatPart import net.awan.pipelines.data.protocol.ChatPermissionFrame @@ -85,6 +100,7 @@ import net.awan.pipelines.ui.components.PaneIdentity import net.awan.pipelines.ui.components.RunState import net.awan.pipelines.ui.components.RunStatusPalette import net.awan.pipelines.ui.components.SlidingPaneStack +import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.theme.pipelinesText /** @@ -97,6 +113,15 @@ internal val CHAT_ITEM_GAP = 8.dp private val CHAT_COMPOSER_GAP = 12.dp private val CHAT_STATUS_DOT = 8.dp +/** The tool panel floats over the transcript; these bound its width and offsets. */ +private val TOOL_PANEL_MAX_WIDTH = 420.dp +private val TOOL_PANEL_GAP = 4.dp +private val TOOL_PANEL_MARGIN = 8.dp +private val TOOL_PANEL_ELEVATION = 12.dp + +/** The running indicator's elapsed time ticks once a second, never per frame. */ +private const val CHAT_ELAPSED_TICK_MILLIS = 1_000L + /** * The Chat destination. It is the same adaptive [SlidingPaneStack] the Pipelines * and Runs destinations use: pane 0 is the server's session list (the operator @@ -453,9 +478,35 @@ private fun ChatConversationPane( * The bottom-anchored transcript: content is packed to the bottom (so a short or * freshly opened chat sits against the composer) and the running indicator sits * at the newest end while a turn is in flight. + * + * While a turn streams it follows the newest content with a hard jump (not an + * animation, which a fast-growing reply outruns), exactly like the reference + * transcript, unless the operator has scrolled up to read; returning to the end + * resumes following. */ @Composable private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.foundation.lazy.LazyListState) { + var follow by remember(thread.sessionId) { mutableStateOf(true) } + // Only a *user* drag changes whether the transcript follows: programmatic + // jumps (below) never touch `interactionSource`, so they cannot un-stick the + // view. A drag away from the end stops the follow; releasing at the very end + // (no content below) resumes it. + LaunchedEffect(listState) { + listState.interactionSource.interactions.collect { interaction -> + when (interaction) { + is DragInteraction.Start -> follow = false + is DragInteraction.Stop, is DragInteraction.Cancel -> + follow = !listState.canScrollForward + else -> Unit + } + } + } + val itemCount = thread.messages.size + if (thread.running) 1 else 0 + LaunchedEffect(thread.running, thread.messages, follow, itemCount) { + if (thread.running && follow && itemCount > 0) { + listState.scrollToItem(itemCount - 1) + } + } LazyColumn( state = listState, modifier = Modifier.fillMaxSize(), @@ -466,13 +517,20 @@ private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.found MessageItem(message) } if (thread.running) { - item(key = "pending") { RunningIndicator() } + item(key = "pending") { RunningIndicator(thread) } } } } +/** + * The in-flight turn indicator: a spinner, `Working…` and the turn's live elapsed + * time. The elapsed value is derived from the turn's own start ([ChatThread.elapsedMillis]), + * so it keeps counting across a chat switch, and the tick loop stops the moment + * the turn settles. + */ @Composable -private fun RunningIndicator() { +private fun RunningIndicator(thread: ChatThread) { + val elapsedMillis = thread.elapsedMillis(rememberElapsedNow(thread.runningSince)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), @@ -480,9 +538,34 @@ private fun RunningIndicator() { ) { CircularProgressIndicator(Modifier.size(16.dp), strokeWidth = 2.dp) Text("Working…", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text( + text = "· ${formatDuration(elapsedMillis / 1_000)}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) } } +/** + * The wall clock, re-read once a second while a turn is in flight, so the + * indicator derives the elapsed time with [ChatThread.elapsedMillis] — the one + * derivation its unit test also shares — instead of subtracting the turn's start + * itself. Keyed on [runningSince] and only entered for a live turn, so a settled + * chat schedules nothing. + */ +@Composable +private fun rememberElapsedNow(runningSince: Long): Long { + var nowMillis by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(runningSince) { + if (runningSince <= 0) return@LaunchedEffect + while (true) { + nowMillis = System.currentTimeMillis() + delay(CHAT_ELAPSED_TICK_MILLIS) + } + } + return nowMillis +} + @Composable private fun MessageItem(message: ChatMessage) { val isUser = message.role == ChatProtocol.ROLE_USER @@ -507,7 +590,7 @@ private fun MessageItem(message: ChatMessage) { style = MaterialTheme.typography.bodyMedium, ) } else { - message.parts.forEach { part -> MessagePart(part) } + AssistantParts(message.parts) } } } @@ -515,6 +598,28 @@ private fun MessageItem(message: ChatMessage) { } } +/** + * An assistant turn's parts in order, with each run of consecutive tool calls + * rendered as one wrapping chip group (mirroring the reference transcript's + * `_ToolCalls`, research §1.3): the calls of a turn sit together on as few lines + * as they fit, instead of each taking a row, so the transcript stays scannable. + */ +@Composable +private fun AssistantParts(parts: List) { + var index = 0 + while (index < parts.size) { + if (parts[index].type == ChatProtocol.PART_TOOL) { + var end = index + while (end < parts.size && parts[end].type == ChatProtocol.PART_TOOL) end++ + ToolCalls(parts.subList(index, end)) + index = end + } else { + MessagePart(parts[index]) + index++ + } + } +} + @Composable private fun MessagePart(part: ChatPart) { when (part.type) { @@ -522,7 +627,6 @@ private fun MessagePart(part: ChatPart) { MarkdownText(part.text) } ChatProtocol.PART_REASONING -> ReasoningBlock(part.text) - ChatProtocol.PART_TOOL -> ToolCallCard(part) else -> if (part.text.isNotBlank()) Text(part.text, style = MaterialTheme.typography.bodyMedium) } } @@ -547,24 +651,64 @@ private fun ReasoningBlock(text: String) { } /** - * A tool call as a compact chip that expands to INPUT (pretty JSON) and OUTPUT - * (monospace) sections, mirroring the reference chat: the transcript stays - * scannable and the arguments/result appear only on demand. + * One turn's tool calls as a single group of compact chips, mirroring the + * reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call + * shows its name (or the edited file), its duration and a spinner while it runs, + * and the chips of the turn wrap together on as few lines as they fit instead of + * each taking a row. * - * An `edit`-family call instead renders a diff card (research §1.3 `_CodeRun` / + * Tapping a chip opens its INPUT (pretty JSON) / OUTPUT (monospace) panel as an + * overlay anchored to that chip (research §1.3 `_buildPanel`), dismissed by its + * own X or by tapping outside. Because the panel is a popup and not part of the + * transcript layout, opening or closing it never re-flows the conversation nor + * moves its scroll position — the transcript stays exactly where the operator + * left it. + * + * An `edit`-family call expands to a diff card (research §1.3 `_CodeRun` / * `_DiffView`): the `+N -M` stat on the chip and a green/red unified diff derived - * from the arguments, since the brokered protocol carries no diff field. + * from the arguments, since the brokered protocol carries no diff field. An + * `error` call is visibly failed — an error-tinted chip and error icon — and its + * panel shows the error text. */ +@OptIn(ExperimentalLayoutApi::class) @Composable -private fun ToolCallCard(part: ChatPart) { - var expanded by remember(part.id) { mutableStateOf(false) } +private fun ToolCalls(parts: List) { + // One id at a time: the reference shows a single panel, and a focusable popup + // dismisses the previous one on open. No key is needed: an id that is no + // longer among the calls simply matches nothing, so a streaming rebuild keeps + // the panel the operator just opened without allocating a key list per frame. + var openId by remember { mutableStateOf(null) } + FlowRow( + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + parts.forEach { part -> + ToolChip( + part = part, + expanded = openId == part.id, + onToggle = { openId = if (openId == part.id) null else part.id }, + onDismiss = { openId = null }, + ) + } + } +} + +/** A compact tool-call chip: kind icon, label, diff stat, duration and chevron. */ +@Composable +private fun ToolChip(part: ChatPart, expanded: Boolean, onToggle: () -> Unit, onDismiss: () -> Unit) { val running = ChatProtocol.toolRunning(part.state) + val failed = toolFailed(part.state) val diff = toolEditDiff(part.state?.input) - Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + Box { Surface( shape = RoundedCornerShape(CHAT_ITEM_GAP + 2.dp), - color = MaterialTheme.colorScheme.surfaceContainerHigh, - modifier = Modifier.clickable { expanded = !expanded }, + color = if (failed) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.surfaceContainerHigh + }, + modifier = Modifier.clickable(onClick = onToggle), ) { Row( verticalAlignment = Alignment.CenterVertically, @@ -575,10 +719,14 @@ private fun ToolCallCard(part: ChatPart) { CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp) } else { Icon( - if (diff != null) Icons.Default.Edit else Icons.Default.Build, - contentDescription = null, + imageVector = when { + failed -> Icons.Default.ErrorOutline + diff != null -> Icons.Default.Edit + else -> Icons.Default.Build + }, + contentDescription = if (failed) "Failed tool call" else null, modifier = Modifier.size(16.dp), - tint = MaterialTheme.colorScheme.onSurfaceVariant, + tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant, ) } Text( @@ -586,7 +734,6 @@ private fun ToolCallCard(part: ChatPart) { style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f, fill = false), ) diff?.let { DiffStat(it) } toolDurationMillis(part)?.let { @@ -600,13 +747,102 @@ private fun ToolCallCard(part: ChatPart) { } } if (expanded) { - Column(verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), modifier = Modifier.padding(top = CHAT_ITEM_GAP)) { - if (diff != null) { - DiffView(diff) - } else { - CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) - CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) + Popup( + popupPositionProvider = rememberToolPanelPositionProvider(), + onDismissRequest = onDismiss, + properties = PopupProperties(focusable = true), + ) { + ToolPanel(part = part, onDismiss = onDismiss) + } + } + } +} + +/** + * Anchors the tool panel just below its chip, or above it when there is no room + * below, keeping it inside the window margins — the same flip the reference + * panel does. Resolved in px, so it is independent of the current density. + */ +internal class ToolPanelPositionProvider(private val gapPx: Int, private val marginPx: Int) : PopupPositionProvider { + override fun calculatePosition( + anchorBounds: IntRect, + windowSize: IntSize, + layoutDirection: LayoutDirection, + popupContentSize: IntSize, + ): IntOffset { + val maxX = (windowSize.width - popupContentSize.width - marginPx).coerceAtLeast(marginPx) + val x = anchorBounds.left.coerceIn(marginPx, maxX) + val below = anchorBounds.bottom + gapPx + val above = anchorBounds.top - popupContentSize.height - gapPx + val maxY = (windowSize.height - popupContentSize.height - marginPx).coerceAtLeast(marginPx) + val y = if (below <= maxY) below else above.coerceAtLeast(marginPx) + return IntOffset(x, y) + } +} + +@Composable +private fun rememberToolPanelPositionProvider(): PopupPositionProvider { + val density = LocalDensity.current + return remember(density) { + ToolPanelPositionProvider( + gapPx = with(density) { TOOL_PANEL_GAP.roundToPx() }, + marginPx = with(density) { TOOL_PANEL_MARGIN.roundToPx() }, + ) + } +} + +/** + * The expanded panel of one tool call, mirroring the reference panel + * (`_buildPanel`, research §1.3): a header naming the call and its duration with + * a close X, then the pretty-printed INPUT and the monospace OUTPUT (or the + * synthesised edit diff). Both content blocks carry the shared whole-block copy + * action from [CodeBlock]. A failed call always renders its error text in an + * ERROR block — even an edit-family call, whose diff is still shown alongside it. + */ +@Composable +private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier = Modifier) { + val diff = toolEditDiff(part.state?.input) + val failed = toolFailed(part.state) + Surface( + shape = RoundedCornerShape(CHAT_ITEM_GAP), + color = MaterialTheme.colorScheme.surfaceContainer, + shadowElevation = TOOL_PANEL_ELEVATION, + modifier = modifier.widthIn(max = TOOL_PANEL_MAX_WIDTH).fillMaxWidth(), + ) { + Column( + verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(CHAT_ITEM_GAP + 2.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Icon( + imageVector = if (failed) Icons.Default.ErrorOutline else Icons.Default.Build, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + ) + Text( + text = toolLabel(part), + style = MaterialTheme.typography.labelLarge, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + toolDurationMillis(part)?.let { + Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } + IconButton(onClick = onDismiss, modifier = Modifier.size(28.dp)) { + Icon(Icons.Default.Close, contentDescription = "Close tool call", modifier = Modifier.size(16.dp)) + } + } + if (diff != null) { + DiffView(diff) + } else { + CodeBlock(label = "INPUT", text = prettyToolInput(part.state?.input)) + } + if (failed) { + CodeBlock(label = "ERROR", text = toolErrorText(part.state)) + } else if (diff == null) { + CodeBlock(label = "OUTPUT", text = toolOutputText(part.state)) } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index ef38751c..b59bdbd1 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -37,6 +37,13 @@ data class ChatThread( val error: String? = null, /** A turn is in flight for this session; it keeps running when we switch away. */ val running: Boolean = false, + /** + * Wall-clock epoch millis the in-flight turn began, or 0 when it is not + * running. Stored on the thread (not in the composable) so the running + * indicator's elapsed time survives a chat switch, and cleared the moment + * the turn settles. + */ + val runningSince: Long = 0, /** The unsent composer text for this chat. */ val draft: String = "", val scroll: ChatScrollPosition = ChatScrollPosition(), @@ -53,6 +60,14 @@ data class ChatThread( /** Whether the composer's send action is allowed. */ val canSend: Boolean get() = !readOnly && draft.isNotBlank() + + /** + * Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it + * has settled. Pure, so the running indicator and its unit test share the one + * derivation instead of each subtracting the start themselves. + */ + fun elapsedMillis(nowMillis: Long): Long = + if (running && runningSince in 1 until nowMillis) nowMillis - runningSince else 0 } /** @@ -85,8 +100,11 @@ data class ChatState( * a running session must re-sync on return so a stale copy is never shown. * - [event] applies a server frame to its session's thread whether or not that * thread is on screen, so a background chat never loses its stream. + * + * [now] is injectable so the running indicator's elapsed time is testable without + * a device clock. */ -class ChatStore { +class ChatStore(private val now: () -> Long = System::currentTimeMillis) { private val _state = MutableStateFlow(ChatState()) val state: StateFlow = _state.asStateFlow() @@ -215,7 +233,41 @@ class ChatStore { it.copy(messages = messages, loading = false, loaded = true, error = null) } - fun running(sessionId: String, running: Boolean) = update(sessionId) { it.copy(running = running) } + fun running(sessionId: String, running: Boolean) = update(sessionId) { setRunning(it, running) } + + /** + * The stream resumed (the socket reconnected): every frame that was feeding an + * in-flight turn is gone, so no thread keeps claiming to run until a fresh + * frame proves otherwise, and the caller re-fetches each open chat's history. + * Returning every open id (not only the running ones) means a gap that + * silently swallowed the end of a turn is repaired too. Re-fetching replaces + * the conversation wholesale, so a resync can neither duplicate nor drop text. + */ + fun streamResumed(): List { + val ids = _state.value.open.map { it.sessionId } + if (ids.isEmpty()) return ids + _state.value = _state.value.copy( + open = _state.value.open.map { if (it.running) it.copy(running = false, runningSince = 0) else it }, + ) + return ids + } + + /** + * A server-pushed stream error carries no session id (the brokered protocol + * cannot attribute it), so settle the one turn it can only have come from: the + * sole running chat, or the active one when several are in flight. With + * nothing running there is no turn to settle and it is ignored; the server's + * text is kept so the operator sees why the turn stopped. + */ + fun streamError(message: String) { + val running = _state.value.open.filter { it.running } + val target = when { + running.isEmpty() -> return + running.size == 1 -> running.single() + else -> running.firstOrNull { it.sessionId == _state.value.activeId } ?: return + } + update(target.sessionId) { setRunning(it.copy(error = message), false) } + } /** The server pushed an approval request for this session; the composer answers it. */ fun permission(frame: ChatPermissionFrame) { @@ -256,7 +308,7 @@ class ChatStore { ChatProtocol.PART_TOOL -> applyTool(frame) ChatProtocol.EVENT_STEP -> { val started = frame.step?.status != ChatProtocol.STEP_ENDED - update(frame.sessionId) { it.copy(running = started) } + update(frame.sessionId) { setRunning(it, started) } } else -> Unit } @@ -318,10 +370,22 @@ class ChatStore { val updated = upsert(if (partIndex >= 0) parts[partIndex] else null) if (partIndex >= 0) parts[partIndex] = updated else parts.add(updated) messages[resolvedIndex] = message.copy(parts = parts) - thread.copy(messages = messages, running = true) + setRunning(thread.copy(messages = messages), true) } } + /** + * Applies a running transition: a turn that begins is stamped with the wall + * clock so the indicator can tick, a redundant `true` keeps the original + * stamp, and settling clears it. The one place `running` is set, so the two + * can never disagree. + */ + private fun setRunning(thread: ChatThread, running: Boolean): ChatThread = when { + running && !thread.running -> thread.copy(running = true, runningSince = now()) + running -> thread + else -> thread.copy(running = false, runningSince = 0) + } + private fun update(sessionId: String, block: (ChatThread) -> ChatThread) { val current = _state.value if (current.open.none { it.sessionId == sessionId }) return diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt index 9ecdacaf..6fe2f05a 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -2,6 +2,7 @@ package net.awan.pipelines.ui.chat import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive +import net.awan.pipelines.data.protocol.ChatError import net.awan.pipelines.data.protocol.ChatPart import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatSession @@ -26,7 +27,7 @@ class ChatFormatTest { } @Test - fun toolOutputFallsBackToNoOutputOrError() { + fun toolOutputFallsBackToNoOutput() { val completed = ChatToolState( status = ChatProtocol.TOOL_COMPLETED, content = listOf(ChatToolContent(type = "text", text = "hello")), @@ -36,15 +37,24 @@ class ChatFormatTest { "(no output)", toolOutputText(ChatToolState(status = ChatProtocol.TOOL_COMPLETED)), ) - val failed = ChatToolState( - status = ChatProtocol.TOOL_ERROR, - error = net.awan.pipelines.data.protocol.ChatError(type = "boom", message = "exploded"), - ) - assertEquals("exploded", toolOutputText(failed)) // Still streaming -> nothing yet, never the "(no output)" claim. assertEquals("", toolOutputText(ChatToolState(status = ChatProtocol.TOOL_RUNNING))) } + @Test + fun toolErrorPrefersTheMessageOverPartialOutput() { + // A failed call can carry both output content and an error; the ERROR + // block must show the message, never the output text. + val failed = ChatToolState( + status = ChatProtocol.TOOL_ERROR, + content = listOf(ChatToolContent(type = "text", text = "partial output")), + error = ChatError(type = "boom", message = "exploded"), + ) + assertEquals("exploded", toolErrorText(failed)) + // A failure with no message still renders something rather than a blank block. + assertEquals("(no output)", toolErrorText(ChatToolState(status = ChatProtocol.TOOL_ERROR))) + } + @Test fun toolDurationUsesRanToCompletedAndIsNullWhileRunning() { val done = ChatPart(name = "shell", time = ChatTime(created = 5, ran = 10, completed = 35)) @@ -95,6 +105,14 @@ class ChatFormatTest { assertNull(toolEditDiff(JsonObject(mapOf("command" to JsonPrimitive("ls"))))) } + @Test + fun toolFailedOnlyForTheErrorStatus() { + assertTrue(toolFailed(ChatToolState(status = ChatProtocol.TOOL_ERROR))) + assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_COMPLETED))) + assertFalse(toolFailed(ChatToolState(status = ChatProtocol.TOOL_RUNNING))) + assertFalse(toolFailed(null)) + } + @Test fun sessionTitleNeverBlank() { assertEquals("Named", sessionTitle(ChatSession(id = "ses_1", title = "Named"))) diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatStreamTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatStreamTest.kt new file mode 100644 index 00000000..29a4c29b --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatStreamTest.kt @@ -0,0 +1,133 @@ +package net.awan.pipelines.ui.chat + +import net.awan.pipelines.data.protocol.ChatEventFrame +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.protocol.ChatStep +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The streaming guarantees: a sequence of text deltas grows the rendered + * conversation and the running indicator toggles on and off, the elapsed time is + * derived from the turn's own start, a reconnect settles the indicator before the + * history re-fetch, and a mid-stream failure settles it with the server's text. + * Driven directly against [ChatStore] with an injected clock, so no device, + * server or Compose runtime is needed. + */ +class ChatStreamTest { + + private fun session(id: String) = ChatSession(id = id, title = id) + + private fun step(status: String) = ChatEventFrame( + sessionId = "s", + kind = ChatProtocol.EVENT_STEP, + step = ChatStep(status = status), + ) + + private fun delta(sessionId: String, messageId: String, partId: String, text: String) = ChatEventFrame( + sessionId = sessionId, + messageId = messageId, + kind = ChatProtocol.PART_TEXT, + delta = text, + part = ChatPart(type = ChatProtocol.PART_TEXT, id = partId), + ) + + /** The text of the single assistant message, exactly what the transcript renders. */ + private fun renderedText(store: ChatStore, sessionId: String): String = + store.value.thread(sessionId)!!.messages.last().parts.single().text + + @Test + fun deltaSequenceGrowsRenderedTextAndTogglesRunning() { + val store = ChatStore() + store.open(session("s")) + store.history("s", emptyList()) + assertFalse(store.value.thread("s")!!.running) + + // A step starting the turn raises the running indicator. + store.event(step(ChatProtocol.STEP_STARTED)) + assertTrue(store.value.thread("s")!!.running) + + // Each delta appends to the same part: the rendered text is the exact + // concatenation and strictly grows, never resets. + val chunks = listOf("Hel", "lo ", "wor", "ld") + val lengths = mutableListOf() + chunks.forEachIndexed { index, chunk -> + store.event(delta("s", "m1", "m1#0", chunk)) + assertEquals(chunks.take(index + 1).joinToString(""), renderedText(store, "s")) + lengths += renderedText(store, "s").length + } + assertTrue(lengths.zipWithNext().all { (before, after) -> after > before }) + + // The step ending the turn lowers the indicator and clears its start. + store.event(step(ChatProtocol.STEP_ENDED)) + assertFalse(store.value.thread("s")!!.running) + assertEquals(0L, store.value.thread("s")!!.runningSince) + assertEquals("Hello world", renderedText(store, "s")) + } + + @Test + fun elapsedTimeComesFromTheTurnStartAndSurvivesARepeatedStart() { + var clock = 1_000L + val store = ChatStore(now = { clock }) + store.open(session("s")) + + store.event(step(ChatProtocol.STEP_STARTED)) + assertEquals(1_000L, store.value.thread("s")!!.runningSince) + + clock = 6_500L + assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock)) + + // A second start for the same turn must not move the clock forward. + store.event(step(ChatProtocol.STEP_STARTED)) + assertEquals(1_000L, store.value.thread("s")!!.runningSince) + assertEquals(5_500L, store.value.thread("s")!!.elapsedMillis(clock)) + + // Settling drops the elapsed to 0 whatever the clock reads. + store.event(step(ChatProtocol.STEP_ENDED)) + assertEquals(0L, store.value.thread("s")!!.elapsedMillis(clock)) + } + + @Test + fun streamResumedSettlesRunningAndReturnsEveryOpenChat() { + val store = ChatStore() + store.open(session("a")) + store.history("a", emptyList()) + store.open(session("b")) + store.history("b", emptyList()) + store.running("a", true) + + // A reconnect names every open chat so the caller re-fetches each, and no + // thread keeps claiming to run until a fresh frame proves it. + assertEquals(listOf("a", "b"), store.streamResumed()) + assertFalse(store.value.thread("a")!!.running) + + // A delta after the resync re-asserts the running indicator. + store.event(delta("a", "m1", "m1#0", "still going")) + assertTrue(store.value.thread("a")!!.running) + assertEquals("still going", renderedText(store, "a")) + } + + @Test + fun streamErrorSettlesTheRunningTurnAndKeepsTheServerText() { + val store = ChatStore() + store.open(session("s")) + store.running("s", true) + + store.streamError("chat stream: boom") + val thread = store.value.thread("s")!! + assertFalse(thread.running) + assertEquals("chat stream: boom", thread.error) + } + + @Test + fun streamErrorWithNothingRunningIsIgnored() { + val store = ChatStore() + store.open(session("s")) + store.streamError("chat stream: boom") + assertEquals(null, store.value.thread("s")!!.error) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ToolPanelPositionProviderTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ToolPanelPositionProviderTest.kt new file mode 100644 index 00000000..ce0045cc --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ToolPanelPositionProviderTest.kt @@ -0,0 +1,42 @@ +package net.awan.pipelines.ui.chat + +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.IntRect +import androidx.compose.ui.unit.IntSize +import androidx.compose.ui.unit.LayoutDirection +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * The tool panel's placement: below the chip when it fits, flipped above when it + * does not, and always kept inside the window margins. Driven directly against + * the provider, so it needs no device or Compose runtime. + */ +class ToolPanelPositionProviderTest { + + private val provider = ToolPanelPositionProvider(gapPx = 4, marginPx = 8) + private val window = IntSize(width = 1000, height = 2000) + + private fun place(anchor: IntRect, content: IntSize): IntOffset = + provider.calculatePosition(anchor, window, LayoutDirection.Ltr, content) + + @Test + fun placesBelowTheChipWhenItFits() { + val anchor = IntRect(left = 40, top = 100, right = 340, bottom = 160) + assertEquals(IntOffset(40, 164), place(anchor, IntSize(400, 500))) + } + + @Test + fun flipsAboveWhenThereIsNoRoomBelow() { + val anchor = IntRect(left = 40, top = 1800, right = 340, bottom = 1860) + // 1860 + 4 + 500 > 2000 - 8, so it goes above: 1800 - 500 - 4 = 1296. + assertEquals(IntOffset(40, 1296), place(anchor, IntSize(400, 500))) + } + + @Test + fun clampsToTheRightAndTopMargins() { + val anchor = IntRect(left = 950, top = 20, right = 990, bottom = 60) + // Width 400 cannot start at 950; it is pulled in to the right margin. + assertEquals(IntOffset(592, 64), place(anchor, IntSize(400, 500))) + } +} From e2f306b8bdd985f8f6199f0191d66cf472e3a3c6 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 15:15:35 +0100 Subject: [PATCH 4/8] Summarise large edit diffs and label the card with file and stat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat edit diff card rendered every line of an edit, so the >400-line fallback flooded the transcript with thousands of Text nodes on a phone; it also showed only the tool name, not the file, on the expanded panel. - ChatFormat.toolEditDiff keeps the first MAX_RENDERED_DIFF_LINES (200) lines and puts the remainder in the new ToolDiff.omitted, while the +N/-M counts continue to describe the whole edit. - DiffView prints "… N more changed lines not shown" first so the truncation is visible without scrolling. - The expanded panel header now shows the edited file name and the shared green/red DiffStat, matching the collapsed chip. - ChatFormatTest pins omitted = 0 for a small edit and the true counts, 200-line cap and omitted = 300 for an oversized one. - android/README.md records the change and its evidence. --- android/README.md | 53 +++++++++++++++++++ .../net/awan/pipelines/ui/chat/ChatFormat.kt | 33 ++++++++++-- .../net/awan/pipelines/ui/chat/ChatScreen.kt | 15 +++++- .../awan/pipelines/ui/chat/ChatFormatTest.kt | 26 +++++++++ 4 files changed, 121 insertions(+), 6 deletions(-) diff --git a/android/README.md b/android/README.md index be295849..98c9aceb 100644 --- a/android/README.md +++ b/android/README.md @@ -2664,3 +2664,56 @@ Evidence (macOS, Gradle 9.7.1, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): Not verified in this pass: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. + +## Edit diffs: file name, stat and large-edit summarisation (16 Oct 2026) + +The edit diff card already derived its lines, but three things the task calls for +were missing or wrong. `android/` only; no new dependency (still just the declared +`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched, +no run started from the app, and `emulator-5556` only (lane A's `emulator-5554` +was never addressed). + +- **The file name and `+N -M` are on the card, not just the chip.** The expanded + panel header showed the tool name (`edit`); it now shows the edited file (as the + chip already did) and the shared green/red `DiffStat`, so the diff names its file + and its counts wherever it is read. +- **Very large edits are summarised, not flooded.** A diff longer than + `MAX_RENDERED_DIFF_LINES` (200) kept *every* line — the >400-line fallback + rendered `old + new` in full, thousands of `Text` nodes in a scrolling `Column` + on a phone. `ChatFormat.toolEditDiff` now keeps the first 200 lines and carries + the rest in the new `ToolDiff.omitted`; `DiffView` prints + `… N more changed lines not shown` **first**, so the truncation is visible + without scrolling. The `+N -M` counts still describe the whole edit, never the + rendered prefix. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the + JUnit XML totals **254 tests, 0 failures, 0 errors, 0 skipped** (new + `toolEditDiffSummarisesAnOversizedEditInsteadOfRenderingEveryLine`, which + asserts the true `+250 -250` counts, the 200-line render cap and + `omitted = 300`; the small-edit test now also pins `omitted = 0`). +- The rebuilt debug APK was installed on `emulator-5556` only and driven against + `.diff_check/chat_stub_diff.py` (the `.tool_calls_check/chat_stub_tools.py` + `/connect` WebSocket double plus a 300-line edit whose intersection with the + cap must summarise; stdlib double, test scaffolding, not the app). Captures were + validated with `android/scripts/capture_png.sh -s emulator-5556`: + `03_diff_small.png` shows the small edit card — `src/layout.kt +2 -2 300ms`, + then red `- val gap = 4.dp` / `- val inset = 1.dp` and green + `+ val gap = 6.dp` / `+ val inset = 2.dp` in monospace — and + `05_diff_summarised.png` shows `src/big.kt +100 -100 150ms` over + `… 200 more changed lines not shown` and the interleaved context/`-`/`+` lines. + `uiautomator dump` confirms the same nodes; `adb -s emulator-5556 logcat -d` + held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,220,501 bytes, sha256 + `7cfca9c40361d4f1871bc61da20aec8c918637f8e085b8eb534d134b3cb8fe00`) copied to + `~/.local/share/pipelines/data/artifacts/133/1/pipelines-debug-wip-291cec2.apk`; + `curl -I http://10.0.0.75:8080/artifacts/133/1/pipelines-debug-wip-291cec2.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18220501`, and a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. +`:app:lintDebug` still cannot run here (the Gradle JVM's `25.0.4.1` version +string is rejected by AGP 8.7.2 lint), unchanged from the slices above. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index d940f8a6..9f9fcf85 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -107,14 +107,28 @@ enum class DiffKind { CONTEXT, ADD, REMOVE } data class DiffLine(val kind: DiffKind, val text: String) -/** A synthesised edit diff: the file, the `+N -M` counts and the ordered lines. */ -data class ToolDiff(val file: String, val added: Int, val removed: Int, val lines: List) +/** + * A synthesised edit diff: the file, the true `+N -M` counts and the ordered + * lines. [omitted] is how many diff lines are not in [lines] because the edit was + * too large to render in full (0 when the whole diff is shown); the counts always + * describe the whole edit, never just the rendered prefix. + */ +data class ToolDiff( + val file: String, + val added: Int, + val removed: Int, + val lines: List, + val omitted: Int = 0, +) /** * Derives a unified diff for an `edit`-family tool call from its * `oldString`/`newString` arguments. The brokered protocol carries no diff field - * (research report §2.5), so the +/- view is synthesised here instead. Returns - * null for any other tool, so non-edit calls keep the INPUT/OUTPUT panel. + * (research report §2.5), so the +/- view is synthesised here instead. A diff + * longer than [MAX_RENDERED_DIFF_LINES] is summarised — only that many lines are + * kept, with [ToolDiff.omitted] carrying the rest — so a very large edit cannot + * flood the transcript on a phone. Returns null for any other tool, so non-edit + * calls keep the INPUT/OUTPUT panel. */ internal fun toolEditDiff(input: JsonElement?): ToolDiff? { val obj = input as? JsonObject ?: return null @@ -126,7 +140,8 @@ internal fun toolEditDiff(input: JsonElement?): ToolDiff? { file = obj.stringOrNull("filePath", "file_path", "file").orEmpty(), added = lines.count { it.kind == DiffKind.ADD }, removed = lines.count { it.kind == DiffKind.REMOVE }, - lines = lines, + lines = lines.take(MAX_RENDERED_DIFF_LINES), + omitted = (lines.size - MAX_RENDERED_DIFF_LINES).coerceAtLeast(0), ) } @@ -177,4 +192,12 @@ private fun lineDiff(old: List, new: List): List { return result } +/** + * How many diff lines are rendered before the remainder is summarised. Small + * enough to stay readable on a phone, large enough that ordinary edits are + * always shown in full. [MAX_DIFF_LINES] is the larger algorithm guard that + * bounds the quadratic LCS table. + */ +internal const val MAX_RENDERED_DIFF_LINES = 200 + private const val MAX_DIFF_LINES = 400 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 18d4ccb5..b0995062 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -821,12 +821,13 @@ private fun ToolPanel(part: ChatPart, onDismiss: () -> Unit, modifier: Modifier tint = if (failed) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, ) Text( - text = toolLabel(part), + text = diff?.file?.takeIf { it.isNotBlank() } ?: toolLabel(part), style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) + diff?.let { DiffStat(it) } toolDurationMillis(part)?.let { Text(formatToolDuration(it), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } @@ -887,6 +888,18 @@ private fun DiffView(diff: ToolDiff) { .verticalScroll(rememberScrollState()) .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), ) { + if (diff.omitted > 0) { + // A very large edit is summarised rather than rendered in full, so + // the card stays short and readable on a phone. The note sits first + // so the truncation is visible without scrolling to the end. + Text( + text = "… ${diff.omitted} more changed " + + (if (diff.omitted == 1) "line" else "lines") + " not shown", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(bottom = CHAT_ITEM_GAP), + ) + } diff.lines.forEach { line -> val (symbol, color) = when (line.kind) { DiffKind.ADD -> "+" to added diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt index 6fe2f05a..c7d47995 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -87,6 +87,8 @@ class ChatFormatTest { assertEquals("/tmp/a.txt", diff.file) assertEquals(2, diff.added) assertEquals(1, diff.removed) + // A small edit is shown whole, nothing summarised. + assertEquals(0, diff.omitted) assertEquals( listOf( DiffLine(DiffKind.CONTEXT, "one"), @@ -99,6 +101,30 @@ class ChatFormatTest { ) } + @Test + fun toolEditDiffSummarisesAnOversizedEditInsteadOfRenderingEveryLine() { + // Wholly disjoint old/new blocks: every line is a change, so the full diff + // is twice the block size — far past what a phone should render. + val changed = MAX_RENDERED_DIFF_LINES + 50 + val old = (1..changed).joinToString("\n") { "old $it" } + val new = (1..changed).joinToString("\n") { "new $it" } + val diff = toolEditDiff( + JsonObject( + mapOf( + "filePath" to JsonPrimitive("/tmp/big.txt"), + "oldString" to JsonPrimitive(old), + "newString" to JsonPrimitive(new), + ), + ), + )!! + // The stat still describes the whole edit... + assertEquals(changed, diff.added) + assertEquals(changed, diff.removed) + // ...but only a readable prefix is rendered, the rest counted as omitted. + assertEquals(MAX_RENDERED_DIFF_LINES, diff.lines.size) + assertEquals(2 * changed - MAX_RENDERED_DIFF_LINES, diff.omitted) + } + @Test fun toolEditDiffIsNullForNonEdits() { assertNull(toolEditDiff(null)) From 78d5bd38fcbe55199647cd798bf2ae45c58551c1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 15:31:04 +0100 Subject: [PATCH 5/8] Route the stop control's interrupt through one tested builder Extract the single chat_interrupt frame into ChatProtocol.interruptRequest and have PipelinesRepository.chatInterrupt send it, so production and its unit test share the one wire shape instead of the repository building it inline. Add chatInterruptRequestCarriesTheRunningSession, which asserts the frame the stop control sends is chat_interrupt carrying the running session's id (and no chat prompt/reply) and that it survives the client's JSON round-trip. Document the slice and its emulator-5556 evidence in android/README.md. --- android/README.md | 49 +++++++++++++++++++ .../pipelines/data/PipelinesRepository.kt | 3 +- .../net/awan/pipelines/data/protocol/Chat.kt | 8 +++ .../data/protocol/ChatProtocolTest.kt | 21 ++++++++ 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/android/README.md b/android/README.md index 98c9aceb..8ee97c89 100644 --- a/android/README.md +++ b/android/README.md @@ -2717,3 +2717,52 @@ Not verified in this pass: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. `:app:lintDebug` still cannot run here (the Gradle JVM's `25.0.4.1` version string is rejected by AGP 8.7.2 lint), unchanged from the slices above. + +## Stopping a running turn (16 Oct 2026) + +The composer already swapped its send control for a red `Icons.stop` while a turn +ran and `AppViewModel.stopChat` already sent `chat_interrupt`; the slice was +missing the proof the task asks for — a unit test pinning the interrupt frame — +so this pass adds that seam and the on-device capture. `android/` only; no new +dependency (still just the declared `material-icons-extended`), no Pipelines +server/Go/installer/Docker file touched, no run started from the app, and +`emulator-5556` only (lane A's `emulator-5554` was never addressed). + +- **One interrupt frame.** `ChatProtocol.interruptRequest(sessionId)` builds the + single `chat_interrupt` frame (a `ChatQuery` carrying the session id); + `PipelinesRepository.chatInterrupt` sends it, so the wire shape is no longer + constructed inline where only production can see it. +- **The stopped state is honest.** On a successful interrupt the thread settles + (`running = false`, no error) and the composer's send control returns; only a + failing call (or a server-pushed error frame) sets the conversation's error, so + a stop the server accepted is never shown as a failure. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → `BUILD + SUCCESSFUL`; the JUnit XML totals **255 tests, 0 failures, 0 errors, 0 + skipped** (new `chatInterruptRequestCarriesTheRunningSession`, which asserts the + frame the stop control sends is `chat_interrupt` for the running session and + survives the client's JSON round-trip). +- The debug APK was installed on `emulator-5556` only and driven against + `.stop_check/chat_stub_hold.py` (a stdlib `/connect` WebSocket double that holds + the turn open until `chat_interrupt`; test scaffolding, not the app) with + `uiautomator dump`/`input tap`; captures validated with + `android/scripts/capture_png.sh -s emulator-5556`: + `stop_control_running.png` shows the running turn (`Working… · 11s`) with the + composer's send control replaced by the red stop control (bottom-right, in thumb + reach) and the top-bar stop action; `stop_control_stopped.png` shows the same + chat after the stop was pressed — the indicator gone, the send control back, and + no error text (the server acknowledged the interrupt). The stub log recorded + exactly one `chat_interrupt`. `adb -s emulator-5556 logcat -d` held 0 + `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,240,566 bytes, sha256 + `56abfb2c59a9c09fabbe32d7de4f0164cdc852cece4b7df3655dd0c233256248`) copied to + `~/.local/share/pipelines/data/artifacts/135/1/pipelines-debug-wip-e2f306b.apk`; + `curl -I http://10.0.0.249:8080/artifacts/135/1/pipelines-debug-wip-e2f306b.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18240566`, and a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index 07e7f88f..e484214f 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -8,6 +8,7 @@ import kotlinx.serialization.json.JsonElement import net.awan.pipelines.data.protocol.ChatCreateRequest import net.awan.pipelines.data.protocol.ChatMessage import net.awan.pipelines.data.protocol.ChatPromptRequest +import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatQuery import net.awan.pipelines.data.protocol.ChatReplyRequest import net.awan.pipelines.data.protocol.ChatSession @@ -174,7 +175,7 @@ class PipelinesRepository( suspend fun chatInterrupt(sessionId: String) { if (sessionId.isBlank()) throw ProtocolException("Select a chat session first.") - client.call(Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId))) + client.call(ChatProtocol.interruptRequest(sessionId)) } suspend fun chatReply(sessionId: String, requestId: String, decision: String, message: String = "") { diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt index 8d461c8e..c1bf3188 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt @@ -195,4 +195,12 @@ object ChatProtocol { TOOL_STREAMING, TOOL_RUNNING -> true else -> false } + + /** + * The `chat_interrupt` frame the composer's stop control sends: the server + * aborts the in-flight turn for [sessionId]. Built here (not inline in the + * repository) so production and its unit test share the one wire shape. + */ + fun interruptRequest(sessionId: String): Message = + Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId)) } diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt index 9783fc49..34dcdcc0 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt @@ -202,6 +202,27 @@ class ChatProtocolTest { assertEquals(ChatProtocol.DECISION_ONCE, decodedReply.chatReply!!.decision) } + /** + * The stop control's interrupt request: pressing it while a turn is in flight + * must send a `chat_interrupt` carrying the running session's id and nothing + * else, and the frame must survive the wire round-trip the client performs. + * Uses the same [ChatProtocol.interruptRequest] builder the repository sends, + * so this test cannot drift from the production frame. + */ + @Test + fun chatInterruptRequestCarriesTheRunningSession() { + val request = ChatProtocol.interruptRequest("ses_1") + assertEquals(Protocol.CHAT_INTERRUPT, request.type) + assertEquals("ses_1", request.chatQuery!!.sessionId) + + val encoded = PipelinesJson.encodeToString(Message.serializer(), request.copy(id = "android-9")) + val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded) + assertEquals(Protocol.CHAT_INTERRUPT, decoded.type) + assertEquals("ses_1", decoded.chatQuery!!.sessionId) + assertNull(decoded.chatPrompt) + assertNull(decoded.chatReply) + } + /** A non-chat envelope leaves every chat field null, so the two never cross-talk. */ @Test fun nonChatEnvelopeHasNoChatPayload() { From 609721d53ba2a1f94f0de3e7b4ac455fc432ed88 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 16:12:22 +0100 Subject: [PATCH 6/8] Show pushed approvals as in-place chat cards Render a server-pushed chat_permission as an approval card in the transcript instead of a transient bar above the composer, matching the reference opencode/Jarvis chat: the requested action, its resources, the amber RISK REVIEW panel, and once/always/reject actions wired to the server's chat_reply. - ChatFormat: a pure approvalCard()/ApprovalCard model and one ChatProtocol.replyRequest() builder shared by the card's actions and the repository, so the wire frame and the controls cannot drift. - ChatStore/AppViewModel: answerPermission() settles the card in place optimistically and survives a chat switch; a failed reply reopens the same request rather than showing an unacknowledged decision. - ChatPermissionFrame gains optional resolved/decision fields so a request the server reports as already settled shows its verdict with no stale actions; a new request replaces a settled card. - Findability: a gold PanTool top-bar action and chat-chip marker jump to the pending card; the running indicator stands down while waiting. - Tests: ChatApprovalTest covers pending/answered/resolved, the reply builder's once/reject decisions and the missing-summary fallback; ChatProtocolTest covers the server-resolution frame. README records the 265-test/assembleDebug evidence and the emulator-5556 captures, and .approval_check/chat_stub_approval.py is the test double used. android/ only; no new dependency beyond material-icons-extended; no Pipelines server, Go, installer or Docker file touched; no run started from the app. The live brokered server is not verified (the resolved frame fields are an additive contract it does not emit yet). --- .approval_check/chat_stub_approval.py | 285 ++++++++++++++++++ android/README.md | 85 ++++++ .../pipelines/data/PipelinesRepository.kt | 13 +- .../net/awan/pipelines/data/protocol/Chat.kt | 29 +- .../net/awan/pipelines/ui/AppViewModel.kt | 12 +- .../net/awan/pipelines/ui/chat/ChatFormat.kt | 97 ++++++ .../net/awan/pipelines/ui/chat/ChatScreen.kt | 162 +++++++--- .../net/awan/pipelines/ui/chat/ChatStore.kt | 37 ++- .../data/protocol/ChatProtocolTest.kt | 16 + .../pipelines/ui/chat/ChatApprovalTest.kt | 154 ++++++++++ .../pipelines/ui/chat/MultiChatStateTest.kt | 18 +- 11 files changed, 849 insertions(+), 59 deletions(-) create mode 100644 .approval_check/chat_stub_approval.py create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt diff --git a/.approval_check/chat_stub_approval.py b/.approval_check/chat_stub_approval.py new file mode 100644 index 00000000..6a8fb474 --- /dev/null +++ b/.approval_check/chat_stub_approval.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Approval-card scaffolding: /connect WebSocket double that pushes a permission. + +Two sessions: `ses_perm` hands out a pending `chat_permission` after a prompt so +the approval card can be answered (once/always/reject), and `ses_resolved` pushes +a frame the server already settled so the card must show the outcome with no +actions. Same wire shapes as the other stubs; test scaffolding only, never part +of the app. +""" +import base64 +import hashlib +import itertools +import json +import socket +import struct +import sys +import threading +import time + +GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +# Every prompt gets a fresh request id, so a new prompt is a new request rather +# than a re-push of an already-answered one. +REQUEST_SEQ = itertools.count(1) + +PENDING_SESSION = "ses_perm" +RESOLVED_SESSION = "ses_resolved" + +SESSIONS = [ + { + "id": PENDING_SESSION, + "title": "Answer an approval", + "agent": "build", + "model": "deepseek-v4.1", + "directory": "/Users/alan/repos/pipelines", + "created_at": 1760620000000, + "updated_at": 1760620600000, + "busy": False, + }, + { + "id": RESOLVED_SESSION, + "title": "Already resolved", + "agent": "build", + "model": "deepseek-v4.1", + "directory": "/Users/alan/repos/pipelines", + "created_at": 1760620000000, + "updated_at": 1760620600000, + "busy": False, + }, +] + +MESSAGES = { + PENDING_SESSION: [ + {"id": "m1", "session_id": PENDING_SESSION, "role": "user", + "parts": [{"type": "text", "id": "m1t", "text": "Refactor the layout constants."}]}, + {"id": "m2", "session_id": PENDING_SESSION, "role": "assistant", + "parts": [{"type": "text", "id": "m2t", + "text": "I need to edit `src/layout.kt`; approve the change to continue."}]}, + ], + RESOLVED_SESSION: [ + {"id": "r1", "session_id": RESOLVED_SESSION, "role": "user", + "parts": [{"type": "text", "id": "r1t", "text": "Run the tests."}]}, + {"id": "r2", "session_id": RESOLVED_SESSION, "role": "assistant", + "parts": [{"type": "text", "id": "r2t", + "text": "The shell command was approved from another client."}]}, + ], +} + + +def _recv_exact(conn, n): + buf = b"" + while len(buf) < n: + chunk = conn.recv(n - len(buf)) + if not chunk: + raise EOFError + buf += chunk + return buf + + +def _handshake(conn): + data = b"" + while b"\r\n\r\n" not in data: + chunk = conn.recv(4096) + if not chunk: + return False + data += chunk + headers = {} + for line in data.split(b"\r\n")[1:]: + if b":" in line: + k, v = line.split(b":", 1) + headers[k.strip().lower()] = v.strip() + key = headers.get(b"sec-websocket-key") + if not key: + return False + accept = base64.b64encode(hashlib.sha1(key + GUID.encode()).digest()).decode() + conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n" + "Connection: Upgrade\r\n" + f"Sec-WebSocket-Accept: {accept}\r\n\r\n").encode()) + return True + + +def _read_frame(conn): + b1, b2 = _recv_exact(conn, 2) + opcode = b1 & 0x0F + masked = b2 & 0x80 + length = b2 & 0x7F + if length == 126: + length = struct.unpack(">H", _recv_exact(conn, 2))[0] + elif length == 127: + length = struct.unpack(">Q", _recv_exact(conn, 8))[0] + mask = _recv_exact(conn, 4) if masked else b"" + payload = _recv_exact(conn, length) if length else b"" + if masked: + payload = bytes(payload[i] ^ mask[i % 4] for i in range(len(payload))) + return opcode, payload + + +def _frame_text(text): + payload = text.encode() + header = bytearray([0x81]) + n = len(payload) + if n < 126: + header.append(n) + elif n < 65536: + header.append(126) + header += struct.pack(">H", n) + else: + header.append(127) + header += struct.pack(">Q", n) + return bytes(header) + payload + + +def _frame_pong(payload): + """Answer a client ping frame (opcode 0x9) with a pong (0xA). + + OkHttp pings on its own schedule and drops the socket when no pong comes + back, so without this the app reconnects mid-drive. + """ + header = bytearray([0x8A]) + n = len(payload) + if n < 126: + header.append(n) + elif n < 65536: + header.append(126) + header += struct.pack(">H", n) + else: + header.append(127) + header += struct.pack(">Q", n) + return bytes(header) + payload + + +class Session: + def __init__(self, conn): + self.conn = conn + self.lock = threading.Lock() + + def send(self, message): + with self.lock: + self.conn.sendall(_frame_text(json.dumps(message))) + + def send_event(self, session_id, kind, **fields): + frame = {"session_id": session_id, "kind": kind} + frame.update(fields) + self.send({"type": "chat_event", "chat_event": frame}) + + def push_permission(self, session_id, request_id, action, resources, message, + resolved=False, decision=""): + self.send({ + "type": "chat_permission", + "chat_permission": { + "session_id": session_id, + "request_id": request_id, + "action": action, + "resources": resources, + "message": message, + "resolved": resolved, + "decision": decision, + "source": {"type": "tool", "message_id": "m2", "id": "call_1"}, + }, + }) + + def open_approval(self, session_id, request_id): + self.send_event(session_id, "step", step={"status": "started", "index": 1}) + self.send_event( + session_id, + "text", + message_id="m3", + delta="Editing src/layout.kt — I need your approval before I write it.\n", + part={"type": "text", "id": "m3t"}, + ) + self.push_permission( + session_id, + request_id, + action="edit", + resources=["src/layout.kt"], + message="This rewrites src/layout.kt in your workspace. Review the change before allowing it.", + ) + + +def _respond(session, request): + kind = request.get("type") + print(f"<- {kind}", flush=True) + rid = request.get("id") + if kind == "ping": + session.send({"id": rid, "type": "pong", "time": "2026-10-16T15:00:00Z"}) + elif kind == "chat_sessions": + session.send({"id": rid, "type": "chat_sessions", "chat_sessions": SESSIONS}) + elif kind == "chat_messages": + body = request.get("chat_messages") or request.get("chat_query") or {} + session_id = body.get("session_id") or PENDING_SESSION + session.send({"id": rid, "type": "chat_messages", + "chat_messages": MESSAGES.get(session_id, [])}) + if session_id == RESOLVED_SESSION: + # The server reports a request it has already settled: the card must + # state the outcome instead of offering once/always/reject. + session.push_permission( + session_id, + "req_resolved", + action="shell", + resources=["go test ./..."], + message="Another client already rejected this command.", + resolved=True, + decision="reject", + ) + elif kind == "chat_prompt": + body = request.get("chat_prompt") or {} + session_id = body.get("session_id") or PENDING_SESSION + session.send({"id": rid, "type": "chat_prompt"}) + threading.Thread( + target=session.open_approval, + args=(session_id, f"req_pending_{next(REQUEST_SEQ)}"), + daemon=True, + ).start() + elif kind == "chat_reply": + body = request.get("chat_reply") or {} + print(f" decision={body.get('decision')} request={body.get('request_id')}", flush=True) + session.send({"id": rid, "type": "chat_reply"}) + elif kind == "chat_interrupt": + session.send({"id": rid, "type": "chat_interrupt"}) + else: + # Benign echo for pipelines/runs/status so the app's background loads do + # not surface an error while the chat is being driven. + session.send({"id": rid, "type": kind}) + + +def _serve(conn): + session = Session(conn) + try: + if not _handshake(conn): + return + while True: + opcode, payload = _read_frame(conn) + if opcode == 0x8: + break + if opcode == 0x9: + with session.lock: + conn.sendall(_frame_pong(payload)) + continue + if opcode != 0x1: + continue + try: + request = json.loads(payload.decode()) + except Exception: + continue + _respond(session, request) + except (EOFError, OSError): + pass + finally: + conn.close() + + +def main(): + port = int(sys.argv[1]) if len(sys.argv) > 1 else 8799 + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind(("0.0.0.0", port)) + server.listen(8) + print(f"chat_stub_approval listening on 0.0.0.0:{port}", flush=True) + while True: + conn, _ = server.accept() + threading.Thread(target=_serve, args=(conn,), daemon=True).start() + + +if __name__ == "__main__": + main() diff --git a/android/README.md b/android/README.md index 8ee97c89..9a7c5f71 100644 --- a/android/README.md +++ b/android/README.md @@ -2766,3 +2766,88 @@ Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, Not verified in this pass: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. + +## Approvals in the conversation, answered in place (16 Oct 2026) + +The brokered protocol already carried `chat_permission`, but the phone only showed +it as a bar above the composer and removed it the moment it was answered. This +pass makes a pushed approval a card in the conversation: the reference app's amber +risk framing, once/always/reject actions wired to `chat_reply`, an in-place settle +on answer, and a resolved state for a request the server reports as already +settled. `android/` only; no new dependency (still just the declared +`material-icons-extended`), no Pipelines server/Go/installer/Docker file touched, +no run started from the app, and `emulator-5556` only (lane A's `emulator-5554` +was never addressed). + +- **The card is in the transcript.** `ApprovalCardItem` is the transcript's last + item, so the request sits with the conversation rather than floating above the + composer. It shows the action (`Approve edit`), the affected resources in + monospace, the amber `RISK REVIEW` panel carrying the server's risk summary + (falling back to a neutral sentence naming the action when the server sends + none), and `Allow once` / `Always allow` / `Reject`. The amber `tertiary` role + at 12% fills the review panel and its shield glyph, and at 50% outlines a + pending card — the same amber `shield_outlined` framing the reference app uses. + Geometry reuses the existing chat tokens; the only new constants are the two + alpha strengths. +- **Findable without scrolling the whole chat.** The conversation's top bar shows + a gold `PanTool` "Waiting for your approval" action while a request is open; + tapping it jumps the transcript to the card, and the same glyph marks the chat's + chip in the open-chat strip. A newly arrived request is also scrolled into view + by the existing bottom-follow, and the running indicator stands down while the + turn waits (the clock would otherwise tick on work that is not happening). +- **Answered in place.** `ChatStore.answerPermission` records the decision + optimistically, so the card settles to `Allowed once` / `Always allowed` / + `Rejected` and drops its actions instead of disappearing; a failed `chat_reply` + reopens the same request (`permissionReplyFailed`) with the error, so a decision + the server never received is never shown as accepted. `ChatProtocol.replyRequest` + is the one builder `PipelinesRepository.chatReply` sends, so the card's actions + and the wire frame cannot drift. +- **Already resolved is honest.** `ChatPermissionFrame` gained optional `resolved` + and `decision` fields. A frame for a request the server reports as settled + renders as `Rejected`/`Always allowed`/`Already resolved` with no controls, so a + stale once/always/reject is never offered for a closed request; a frame for a + new request replaces a settled card. Those fields are the additive contract the + server sends when it reports an already-settled request (both are omitted by an + older peer, which simply leaves every request pending). + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the + JUnit XML totals **265 tests, 0 failures, 0 errors, 0 skipped** (new + `ChatApprovalTest`: a pushed frame yields a pending card with the request's + action/resources/risk and its three actions, answering once/reject settles the + card in place, a server-resolved frame offers no actions, a failed reply reopens + the request, and the missing-summary fallback; new + `ChatProtocolTest.chatPermissionFrameCarriesTheServerResolution`; the reply + builder is asserted for `once` and `reject`). +- The debug APK was installed on `emulator-5556` only and driven against + `.approval_check/chat_stub_approval.py` (a stdlib `/connect` WebSocket double + that pushes a pending `chat_permission` after a prompt and a server-resolved one + for a second session; test scaffolding, not the app). Captures validated with + `android/scripts/capture_png.sh -s emulator-5556`: `01_approval_pending.png` + (the `Approve edit` card with `src/layout.kt`, the amber `RISK REVIEW` panel and + the three actions, the top-bar pan-tool and the chat-chip marker), + `02_approval_answered.png` (the same card settled to `Allowed once`, no actions), + `03_approval_server_resolved.png` (a server-reported `Rejected` card with no + actions), `04_approval_findable.png` (scrolled up: the card at/below the fold, + the gold "Waiting for your approval" top-bar action present) and + `05_approval_jump.png` (tapping that action brought the card back). The stub log + recorded the `chat_reply` with `decision=once`. `adb -s emulator-5556 logcat -d` + held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. +- **APK publish.** `app-debug.apk` (18,427,840 bytes, sha256 + `f39a1ed7f71759f6840a9e69a117e49a9884731a94133d2902ef7ebf096c0891`) copied to + `~/.local/share/pipelines/data/artifacts/136/1/pipelines-debug-wip-78d5bd3.apk`; + `curl -I http://10.0.0.249:8080/artifacts/136/1/pipelines-debug-wip-78d5bd3.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18427840`, and a streamed `GET | shasum -a 256` matched. + +Not verified in this pass: the live brokered server (separate lane), streaming +against real OpenCode, and attachments — unchanged from the passes above. The +`resolved`/`decision` frame fields are the additive contract the server must send +when it reports an already-settled request; the live server does not emit them +yet, so only the unit test and the stub exercise that path. `:app:lintDebug` still +cannot run here (the Gradle JVM's version string is rejected by AGP 8.7.2 lint), +unchanged from the slices above. The emulator was restarted mid-pass after it shut +down; it was `emulator-5556` throughout and the attached physical device was never +driven. diff --git a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt index e484214f..b9c6ca31 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/PipelinesRepository.kt @@ -10,7 +10,6 @@ import net.awan.pipelines.data.protocol.ChatMessage import net.awan.pipelines.data.protocol.ChatPromptRequest import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatQuery -import net.awan.pipelines.data.protocol.ChatReplyRequest import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.Message import net.awan.pipelines.data.protocol.PipelineDetail @@ -182,17 +181,7 @@ class PipelinesRepository( if (sessionId.isBlank() || requestId.isBlank()) { throw ProtocolException("A pending permission request is required.") } - client.call( - Message( - type = Protocol.CHAT_REPLY, - chatReply = ChatReplyRequest( - sessionId = sessionId, - requestId = requestId, - decision = decision, - message = message, - ), - ), - ) + client.call(ChatProtocol.replyRequest(sessionId, requestId, decision, message)) } private fun requireConfigured() { diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt index c1bf3188..f4b8a747 100644 --- a/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/Chat.kt @@ -138,7 +138,15 @@ data class ChatUsage( val cost: Double = 0.0, ) -/** One pending OpenCode approval request the phone answers with chat_reply. */ +/** + * One pending OpenCode approval request the phone answers with chat_reply. + * + * [resolved] and [decision] carry the server's outcome when it reports a request + * that is no longer open (another client answered it, or it expired): the phone + * then shows the verdict instead of live controls. They are additive and + * optional, so an older peer simply never sets them and every request stays + * pending. + */ @Serializable data class ChatPermissionFrame( @SerialName("session_id") val sessionId: String = "", @@ -149,6 +157,8 @@ data class ChatPermissionFrame( val metadata: JsonObject? = null, val source: ChatPermissionSource? = null, val message: String = "", + val resolved: Boolean = false, + val decision: String = "", ) @Serializable @@ -203,4 +213,21 @@ object ChatProtocol { */ fun interruptRequest(sessionId: String): Message = Message(type = Protocol.CHAT_INTERRUPT, chatQuery = ChatQuery(sessionId = sessionId)) + + /** + * The `chat_reply` frame that answers one permission request: [decision] is + * one of [DECISION_ONCE]/[DECISION_ALWAYS]/[DECISION_REJECT]. Built here (not + * inline in the repository) so the approval card's actions and their unit + * test share the one wire shape. + */ + fun replyRequest(sessionId: String, requestId: String, decision: String, message: String = ""): Message = + Message( + type = Protocol.CHAT_REPLY, + chatReply = ChatReplyRequest( + sessionId = sessionId, + requestId = requestId, + decision = decision, + message = message, + ), + ) } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt index 59b0746b..5f6104d5 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/AppViewModel.kt @@ -128,7 +128,7 @@ class AppViewModel( repository.events.collect { message -> message.chatEvent?.let { chatStore.event(it) } // Never silently drop an approval request: it is held per chat and - // answered with chat_reply from the conversation's approval bar. + // answered with chat_reply from the conversation's approval card. message.chatPermission?.let { chatStore.permission(it) } // An unsolicited server error has no request id to match, so it is // the chat stream failing mid-turn: settle the running chat instead @@ -422,15 +422,21 @@ class AppViewModel( } } - /** Answers a pending approval: optimistically clears it, then reports a failed reply. */ + /** + * Answers a pending approval. The card settles in place optimistically so a + * laggy round-trip over a tunnel never shows the old buttons again; a failed + * reply reopens the same request and reports why, so the operator can retry + * instead of trusting a decision the server never received. + */ fun replyChatPermission(sessionId: String, requestId: String, decision: String) { if (sessionId.isBlank() || requestId.isBlank()) return + chatStore.answerPermission(sessionId, requestId, decision) viewModelScope.launch { try { repository.chatReply(sessionId, requestId, decision) - chatStore.clearPermission(sessionId) } catch (t: Throwable) { if (t is CancellationException) throw t + chatStore.permissionReplyFailed(sessionId, requestId) chatStore.failed(sessionId, ErrorMessages.describe(t)) } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index 9f9fcf85..f489d124 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -6,6 +6,7 @@ import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatPermissionFrame import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.protocol.ChatToolState @@ -201,3 +202,99 @@ private fun lineDiff(old: List, new: List): List { internal const val MAX_RENDERED_DIFF_LINES = 200 private const val MAX_DIFF_LINES = 400 + +/** + * How one permission request stands: still waiting for the operator, answered + * here (optimistically, while the reply is in flight), or already settled by the + * server (another client answered it, or it expired). + */ +enum class ApprovalState { PENDING, ANSWERED, RESOLVED } + +/** + * What the conversation renders for one permission request. Derived purely from + * the server's [ChatPermissionFrame] plus the operator's local answer, so the + * approval card and its unit test share one model instead of each reading the + * frame. [actionable] is true only while nothing has settled the request, which + * is what keeps a resolved request from offering stale once/always/reject + * controls. + */ +data class ApprovalCard( + val requestId: String, + val action: String, + val resources: List, + val risk: String, + val state: ApprovalState, + val decision: String = "", + val note: String = "", +) { + /** The once/always/reject controls are live only while the request is open. */ + val actionable: Boolean get() = state == ApprovalState.PENDING + + /** + * The amber risk box is shown while the request is open and after the + * operator denies it (jarvis shows it while "pending/denied"), but not for a + * request the server already settled, whose note carries the outcome. + */ + val showRisk: Boolean + get() = state == ApprovalState.PENDING || + (state == ApprovalState.ANSWERED && decision == ChatProtocol.DECISION_REJECT) + + /** The card headline: what is being requested, or the verdict once settled. */ + val headline: String + get() = when (state) { + ApprovalState.PENDING -> "Approve " + action.ifBlank { "tool call" } + ApprovalState.ANSWERED -> decisionLabel(decision) + ApprovalState.RESOLVED -> if (decision.isBlank()) "Already resolved" else decisionLabel(decision) + } + + /** The one-line explanation under the headline. */ + val statusLine: String + get() = when (state) { + ApprovalState.PENDING -> "Waiting for your response" + ApprovalState.ANSWERED -> "Waiting for the agent to continue…" + ApprovalState.RESOLVED -> note.ifBlank { "Another client already answered this request." } + } +} + +/** + * The approval card for [permission], or null when there is no request to show. + * A request the server reports as settled wins over any local answer, so a stale + * tap can never reopen controls for a request that is already done. + */ +internal fun approvalCard(permission: ChatPermissionFrame?, answer: String): ApprovalCard? { + if (permission == null || permission.requestId.isBlank()) return null + val resolvedByServer = permission.resolved || permission.decision.isNotBlank() + val state = when { + resolvedByServer -> ApprovalState.RESOLVED + answer.isNotBlank() -> ApprovalState.ANSWERED + else -> ApprovalState.PENDING + } + return ApprovalCard( + requestId = permission.requestId, + action = permission.action, + resources = permission.resources.filter { it.isNotBlank() }, + risk = permissionRiskText(permission), + state = state, + decision = if (resolvedByServer) permission.decision else answer, + note = if (resolvedByServer) permission.message else "", + ) +} + +/** + * The text in the amber risk-review box: the server's own summary when it carries + * one (jarvis shows the model's risk summary), otherwise a neutral sentence + * naming the action so the box is never blank. + */ +internal fun permissionRiskText(permission: ChatPermissionFrame): String { + if (permission.message.isNotBlank()) return permission.message + val what = permission.action.ifBlank { "a tool call" } + return "The agent is asking to run $what; review the request before allowing." +} + +/** A human label for a once/always/reject decision, blank-safe. */ +internal fun decisionLabel(decision: String): String = when (decision) { + ChatProtocol.DECISION_ONCE -> "Allowed once" + ChatProtocol.DECISION_ALWAYS -> "Always allowed" + ChatProtocol.DECISION_REJECT -> "Rejected" + else -> "Resolved" +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index b0995062..7788ec76 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -1,5 +1,6 @@ package net.awan.pipelines.ui.chat +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll @@ -37,9 +38,12 @@ import androidx.compose.material.icons.filled.Edit import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.PanTool import androidx.compose.material.icons.filled.Psychology import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Stop +import androidx.compose.material.icons.outlined.Shield +import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator @@ -62,6 +66,7 @@ import androidx.compose.runtime.key import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -83,9 +88,9 @@ import androidx.activity.compose.PredictiveBackHandler import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect +import kotlinx.coroutines.launch import net.awan.pipelines.data.protocol.ChatMessage import net.awan.pipelines.data.protocol.ChatPart -import net.awan.pipelines.data.protocol.ChatPermissionFrame import net.awan.pipelines.data.protocol.ChatProtocol import net.awan.pipelines.data.protocol.ChatSession import net.awan.pipelines.data.transport.ConnectionState @@ -113,6 +118,13 @@ internal val CHAT_ITEM_GAP = 8.dp private val CHAT_COMPOSER_GAP = 12.dp private val CHAT_STATUS_DOT = 8.dp +/** + * The approval card's amber review panel and pending-card border strengths, + * echoing the reference app's 10%-alpha amber `RISK REVIEW` box. + */ +private const val RISK_REVIEW_ALPHA = 0.12f +private const val APPROVAL_PENDING_BORDER_ALPHA = 0.5f + /** The tool panel floats over the transcript; these bound its width and offsets. */ private val TOOL_PANEL_MAX_WIDTH = 420.dp private val TOOL_PANEL_GAP = 4.dp @@ -362,6 +374,16 @@ private fun OpenChatStrip( .background(MaterialTheme.colorScheme.tertiary), ) } + if (approvalCard(thread.permission, thread.permissionAnswer)?.actionable == true) { + // A request waiting on the operator is surfaced on the + // chat's own chip, so it is findable without opening it. + Icon( + Icons.Default.PanTool, + contentDescription = "Waiting for your approval", + tint = MaterialTheme.colorScheme.tertiary, + modifier = Modifier.size(14.dp), + ) + } Text( text = thread.title.ifBlank { thread.sessionId.take(12) }, style = MaterialTheme.typography.labelMedium, @@ -403,6 +425,16 @@ private fun ChatConversationPane( onDispose { vm.saveChatScroll(thread.sessionId, listState.firstVisibleItemIndex, listState.firstVisibleItemScrollOffset) } } + val approval = approvalCard(thread.permission, thread.permissionAnswer) + val awaiting = approval?.actionable == true + // A turn blocked on an approval is not generating, so the running indicator + // (and its ticking clock) stands down while the card is unanswered. + val showRunning = thread.running && !awaiting + // The card is the transcript's last item; the top bar's approval action jumps + // to it so a pending request is reachable without scrolling the whole chat. + val approvalIndex = thread.messages.size + if (showRunning) 1 else 0 + val scope = rememberCoroutineScope() + Scaffold( modifier = modifier, topBar = { @@ -420,6 +452,19 @@ private fun ChatConversationPane( } }, actions = { + if (awaiting) { + IconButton( + onClick = { + scope.launch { listState.animateScrollToItem(approvalIndex.coerceAtLeast(0)) } + }, + ) { + Icon( + Icons.Default.PanTool, + contentDescription = "Waiting for your approval", + tint = MaterialTheme.colorScheme.tertiary, + ) + } + } if (thread.running) { IconButton(onClick = { vm.stopChat(thread.sessionId) }) { Icon(Icons.Default.Stop, contentDescription = "Stop") @@ -438,14 +483,22 @@ private fun ChatConversationPane( message = thread.error, onRetry = { vm.loadChatHistory(thread.sessionId) }, ) - thread.messages.isEmpty() && !thread.running -> EmptyState( + thread.messages.isEmpty() && !thread.running && approval == null -> EmptyState( message = if (thread.readOnly) { "This chat is read-only while another client holds the session." } else { "This chat has no messages yet. Ask something below." }, ) - else -> ChatTranscript(thread = thread, listState = listState) + else -> ChatTranscript( + thread = thread, + listState = listState, + approval = approval, + showRunning = showRunning, + onDecision = { decision -> + approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) } + }, + ) } } if (thread.error != null && thread.loaded) { @@ -456,14 +509,6 @@ private fun ChatConversationPane( modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = 4.dp), ) } - thread.permission?.let { permission -> - PermissionBar( - permission = permission, - onDecision = { decision -> - vm.replyChatPermission(thread.sessionId, permission.requestId, decision) - }, - ) - } ChatComposer( thread = thread, onDraft = { vm.updateChatDraft(thread.sessionId, it) }, @@ -485,7 +530,13 @@ private fun ChatConversationPane( * resumes following. */ @Composable -private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.foundation.lazy.LazyListState) { +private fun ChatTranscript( + thread: ChatThread, + listState: androidx.compose.foundation.lazy.LazyListState, + approval: ApprovalCard?, + showRunning: Boolean, + onDecision: (String) -> Unit, +) { var follow by remember(thread.sessionId) { mutableStateOf(true) } // Only a *user* drag changes whether the transcript follows: programmatic // jumps (below) never touch `interactionSource`, so they cannot un-stick the @@ -501,9 +552,13 @@ private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.found } } } - val itemCount = thread.messages.size + if (thread.running) 1 else 0 - LaunchedEffect(thread.running, thread.messages, follow, itemCount) { - if (thread.running && follow && itemCount > 0) { + val awaiting = approval?.actionable == true + val itemCount = thread.messages.size + (if (showRunning) 1 else 0) + (if (approval != null) 1 else 0) + // Follow the newest content while a turn streams, and scroll a freshly + // arrived approval card into view the same way so a pending request is not + // left below the fold. + LaunchedEffect(thread.running, thread.messages, follow, itemCount, awaiting) { + if (follow && itemCount > 0 && (thread.running || awaiting)) { listState.scrollToItem(itemCount - 1) } } @@ -516,9 +571,14 @@ private fun ChatTranscript(thread: ChatThread, listState: androidx.compose.found items(thread.messages, key = { it.id }) { message -> MessageItem(message) } - if (thread.running) { + if (showRunning) { item(key = "pending") { RunningIndicator(thread) } } + if (approval != null) { + // Keyed by request id so switching between requests swaps the card + // instead of reusing the previous one's state. + item(key = "approval-" + approval.requestId) { ApprovalCardItem(approval, onDecision) } + } } } @@ -961,35 +1021,67 @@ private fun ChatComposer( } /** - * The approval bar for a pending tool-call permission: the request's action and - * resources, with Allow-once / Always / Deny. A decision is answered through - * `chat_reply`, so the server-held credentials and the tool never leave it. + * One approval request as a card in the conversation (research §1.3 `_CodeRun` / + * risk review): the action being requested, the affected resources, the amber + * `RISK REVIEW` panel repeating the server's risk summary, and once/always/reject + * actions answered with `chat_reply`, so the server-held credentials and the tool + * never leave it. A card that is already answered or resolved keeps its place but + * drops the actions and states the outcome, so it can never offer a stale choice. */ @Composable -private fun PermissionBar(permission: ChatPermissionFrame, onDecision: (String) -> Unit) { - Surface(color = MaterialTheme.colorScheme.tertiaryContainer, modifier = Modifier.fillMaxWidth()) { +private fun ApprovalCardItem(card: ApprovalCard, onDecision: (String) -> Unit) { + val amber = MaterialTheme.colorScheme.tertiary + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainerHigh), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp), + border = if (card.actionable) BorderStroke(1.dp, amber.copy(alpha = APPROVAL_PENDING_BORDER_ALPHA)) else null, + ) { Column( - modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + modifier = Modifier.fillMaxWidth().padding(CHAT_GUTTER), verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), ) { - Text( - text = "Approve: ${permission.action.ifBlank { "tool call" }}", - style = MaterialTheme.typography.labelMedium, - color = MaterialTheme.colorScheme.onTertiaryContainer, - ) - if (permission.resources.isNotEmpty()) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(20.dp)) + Column(Modifier.weight(1f)) { + Text(card.headline, style = pipelinesText().cardTitle) + Text( + text = card.statusLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + if (card.resources.isNotEmpty()) { Text( - text = permission.resources.joinToString("\n"), + text = card.resources.joinToString("\n"), style = pipelinesText().mono, - color = MaterialTheme.colorScheme.onTertiaryContainer, - maxLines = 3, + maxLines = 6, overflow = TextOverflow.Ellipsis, ) } - Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { - TextButton(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") } - TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always") } - TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Deny") } + if (card.showRisk && card.risk.isNotBlank()) { + Column( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(CHAT_ITEM_GAP)) + .background(amber.copy(alpha = RISK_REVIEW_ALPHA)) + .padding(CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Icon(Icons.Outlined.Shield, contentDescription = null, tint = amber, modifier = Modifier.size(14.dp)) + Text("RISK REVIEW", style = MaterialTheme.typography.labelSmall, color = amber) + } + Text(card.risk, style = MaterialTheme.typography.bodySmall) + } + } + if (card.actionable) { + Row(horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP)) { + Button(onClick = { onDecision(ChatProtocol.DECISION_ONCE) }) { Text("Allow once") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_ALWAYS) }) { Text("Always allow") } + TextButton(onClick = { onDecision(ChatProtocol.DECISION_REJECT) }) { Text("Reject") } + } } } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index b59bdbd1..cdaf4469 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -49,6 +49,12 @@ data class ChatThread( val scroll: ChatScrollPosition = ChatScrollPosition(), /** The server's pending approval for this session, answered with chat_reply. */ val permission: ChatPermissionFrame? = null, + /** + * The operator's local answer to [permission] (`once`/`always`/`reject`), or + * blank while it is still open. Held on the thread so the approval card can + * settle in place optimistically and survives a chat switch. + */ + val permissionAnswer: String = "", ) { /** * Read-only while another client holds the session: the composer must never @@ -269,15 +275,38 @@ class ChatStore(private val now: () -> Long = System::currentTimeMillis) { update(target.sessionId) { setRunning(it.copy(error = message), false) } } - /** The server pushed an approval request for this session; the composer answers it. */ + /** + * The server pushed an approval request for this session, or reported one it + * has already settled. A frame for a *new* request replaces any leftover card + * from the previous one; a frame for the same request (for example a resolved + * re-push) keeps the local answer and applies the server's outcome. + */ fun permission(frame: ChatPermissionFrame) { if (frame.sessionId.isBlank()) return ensureThread(frame.sessionId) - update(frame.sessionId) { it.copy(permission = frame) } + update(frame.sessionId) { + val sameRequest = it.permission?.requestId == frame.requestId && frame.requestId.isNotBlank() + it.copy( + permission = frame, + permissionAnswer = if (sameRequest) it.permissionAnswer else "", + ) + } } - /** Drops the pending approval once it has been answered or is no longer valid. */ - fun clearPermission(sessionId: String) = update(sessionId) { it.copy(permission = null) } + /** + * The operator's decision on the pending request, recorded optimistically so + * the card settles in place before the round-trip: the buttons are never left + * offering a decision already made. A request that is no longer the one on + * screen is ignored. + */ + fun answerPermission(sessionId: String, requestId: String, decision: String) = update(sessionId) { + if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = decision) + } + + /** The reply failed: reopen the same request so the operator can try again. */ + fun permissionReplyFailed(sessionId: String, requestId: String) = update(sessionId) { + if (it.permission?.requestId != requestId) it else it.copy(permissionAnswer = "") + } /** * Appends the operator's just-sent prompt optimistically, so the bubble is diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt index 34dcdcc0..c30e57f7 100644 --- a/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/ChatProtocolTest.kt @@ -156,6 +156,22 @@ class ChatProtocolTest { assertEquals("edit", permission.action) assertEquals("src/a.kt", permission.resources.single()) assertEquals("c1", permission.source!!.id) + // An open request defaults to unresolved; nothing is invented. + assertTrue(!permission.resolved) + assertEquals("", permission.decision) + } + + /** A request the server reports as already settled carries the outcome. */ + @Test + fun chatPermissionFrameCarriesTheServerResolution() { + val json = """ + {"type":"chat_permission","chat_permission":{"session_id":"ses_1","request_id":"req_9", + "action":"edit","resolved":true,"decision":"reject","message":"another client rejected it"}} + """.trimIndent() + val permission = PipelinesJson.decodeFromString(Message.serializer(), json).chatPermission!! + assertTrue(permission.resolved) + assertEquals(ChatProtocol.DECISION_REJECT, permission.decision) + assertEquals("another client rejected it", permission.message) } @Test diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt new file mode 100644 index 00000000..bb4d6517 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt @@ -0,0 +1,154 @@ +package net.awan.pipelines.ui.chat + +import net.awan.pipelines.data.protocol.ChatPermissionFrame +import net.awan.pipelines.data.protocol.ChatProtocol +import net.awan.pipelines.data.protocol.ChatSession +import net.awan.pipelines.data.protocol.Message +import net.awan.pipelines.data.protocol.PipelinesJson +import net.awan.pipelines.data.protocol.Protocol +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The approval card the conversation shows for a pushed permission request: the + * request appears as a card, answering it updates the card in place with the + * decision the reply frame carries, and a request the server reports as already + * resolved offers no stale actions. Driven through [ChatStore] and the pure + * [approvalCard] the composable renders, so no device, server or Compose runtime + * is needed. + */ +class ChatApprovalTest { + + private fun frame( + requestId: String = "req_9", + action: String = "edit", + resources: List = listOf("src/a.kt"), + message: String = "This edits a file in your workspace.", + resolved: Boolean = false, + decision: String = "", + ) = ChatPermissionFrame( + sessionId = "ses_1", + requestId = requestId, + action = action, + resources = resources, + message = message, + resolved = resolved, + decision = decision, + ) + + private fun storeWithPermission(permission: ChatPermissionFrame): ChatStore { + val store = ChatStore() + store.open(ChatSession(id = "ses_1", title = "Chat")) + store.permission(permission) + return store + } + + private fun card(store: ChatStore): ApprovalCard { + val thread = store.value.thread("ses_1")!! + return approvalCard(thread.permission, thread.permissionAnswer)!! + } + + @Test + fun permissionFrameShowsAPendingApprovalCard() { + val card = card(storeWithPermission(frame())) + + assertEquals(ApprovalState.PENDING, card.state) + assertTrue(card.actionable) + assertEquals("Approve edit", card.headline) + assertEquals("Waiting for your response", card.statusLine) + assertEquals(listOf("src/a.kt"), card.resources) + assertEquals("This edits a file in your workspace.", card.risk) + assertTrue(card.showRisk) + } + + @Test + fun onceAndRejectSendTheRightDecision() { + // The same builder the repository sends, so the card's actions and this + // assertion cannot drift from the wire frame. + val once = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE) + assertEquals(Protocol.CHAT_REPLY, once.type) + assertEquals("ses_1", once.chatReply!!.sessionId) + assertEquals("req_9", once.chatReply!!.requestId) + assertEquals("once", once.chatReply!!.decision) + + val decodedOnce = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), once.copy(id = "android-1")), + ) + assertEquals(ChatProtocol.DECISION_ONCE, decodedOnce.chatReply!!.decision) + + val reject = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_REJECT) + assertEquals("reject", reject.chatReply!!.decision) + assertEquals("req_9", reject.chatReply!!.requestId) + } + + @Test + fun answeringOnceUpdatesTheCardInPlace() { + val store = storeWithPermission(frame()) + store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE) + + val settled = card(store) + assertEquals(ApprovalState.ANSWERED, settled.state) + assertFalse(settled.actionable) + assertEquals(ChatProtocol.DECISION_ONCE, settled.decision) + assertEquals("Allowed once", settled.headline) + // The request is still on screen, not removed: it just stopped asking. + assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId) + } + + @Test + fun rejectingKeepsTheRiskReviewWhileItSettles() { + val store = storeWithPermission(frame()) + store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_REJECT) + + val settled = card(store) + assertEquals(ApprovalState.ANSWERED, settled.state) + assertEquals("Rejected", settled.headline) + assertTrue(settled.showRisk) + } + + @Test + fun serverResolvedRequestOffersNoActions() { + val store = storeWithPermission(frame(resolved = true, message = "Another client already answered.")) + + val resolved = card(store) + assertEquals(ApprovalState.RESOLVED, resolved.state) + assertFalse(resolved.actionable) + assertEquals("Already resolved", resolved.headline) + assertEquals("Another client already answered.", resolved.statusLine) + } + + @Test + fun serverResolvedDecisionIsNamed() { + val store = storeWithPermission( + frame(resolved = true, decision = ChatProtocol.DECISION_REJECT, message = ""), + ) + assertEquals("Rejected", card(store).headline) + } + + @Test + fun failedReplyReopensTheRequest() { + val store = storeWithPermission(frame()) + store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ONCE) + store.permissionReplyFailed("ses_1", "req_9") + assertTrue(card(store).actionable) + } + + @Test + fun riskFallsBackToTheActionWhenTheServerSendsNoSummary() { + val store = storeWithPermission(frame(message = "", resources = emptyList())) + val card = card(store) + assertTrue(card.risk.contains("edit")) + assertEquals(emptyList(), card.resources) + } + + @Test + fun aRequestWithoutAnIdShowsNoCard() { + val store = storeWithPermission(frame(requestId = "")) + val thread = store.value.thread("ses_1")!! + assertNull(approvalCard(thread.permission, thread.permissionAnswer)) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt index 4e004cb4..ae520bd6 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/MultiChatStateTest.kt @@ -9,7 +9,6 @@ import net.awan.pipelines.data.protocol.ChatSession import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -196,13 +195,24 @@ class MultiChatStateTest { } @Test - fun permissionIsStoredUntilAnswered() { + fun permissionIsStoredAndAnsweredInPlace() { val store = ChatStore() store.open(session("a")) store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r1", action = "edit")) assertEquals("r1", store.value.thread("a")!!.permission!!.requestId) - store.clearPermission("a") - assertNull(store.value.thread("a")!!.permission) + + store.answerPermission("a", "r1", ChatProtocol.DECISION_ONCE) + assertEquals(ChatProtocol.DECISION_ONCE, store.value.thread("a")!!.permissionAnswer) + + // A different request replaces the settled card and drops the old answer. + store.permission(ChatPermissionFrame(sessionId = "a", requestId = "r2", action = "bash")) + assertEquals("r2", store.value.thread("a")!!.permission!!.requestId) + assertEquals("", store.value.thread("a")!!.permissionAnswer) + + // A failed reply reopens the request it answers. + store.answerPermission("a", "r2", ChatProtocol.DECISION_REJECT) + store.permissionReplyFailed("a", "r2") + assertEquals("", store.value.thread("a")!!.permissionAnswer) } @Test From 305714c30f089127a499763e9215f3a8ca002826 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 16:26:16 +0100 Subject: [PATCH 7/8] Drive the composer's stop control and IME action from one derivation While a turn was in flight the trailing composer button became the stop control, but the text field's keyboard send action still checked only canSend, so a prompt could be sent from the IME during a run even though the visible control had become stop. Add ChatFormat.composerAction(thread) -> ComposerAction.Send/Stop as the single pure derivation and read it from both the trailing button and the keyboard action, so the two controls can no longer disagree. ChatFormatTest.composerControlIsStopWhileARunIsInFlightAndSendOtherwise covers Send when idle and Stop while running. android/ only; no new dependency. --- android/README.md | 27 +++++++++++++++++++ .../net/awan/pipelines/ui/chat/ChatFormat.kt | 12 +++++++++ .../net/awan/pipelines/ui/chat/ChatScreen.kt | 12 +++++---- .../awan/pipelines/ui/chat/ChatFormatTest.kt | 8 ++++++ 4 files changed, 54 insertions(+), 5 deletions(-) diff --git a/android/README.md b/android/README.md index 9a7c5f71..5cb7a855 100644 --- a/android/README.md +++ b/android/README.md @@ -2764,6 +2764,33 @@ Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, `Content-Length: 18240566`, and a streamed `GET | shasum -a 256` matched. +### Follow-up: one tested composer action (16 Oct 2026, run 143) + +The stop control was still chosen by an inline `if (thread.running)` in the +composer, and the text field's keyboard send action only checked `canSend`, so a +prompt could still be sent from the IME while a turn was in flight even though the +visible control had become stop. `ChatFormat.composerAction(thread)` +(`ComposerAction.Send`/`Stop`) is now the single pure derivation the trailing +button and the keyboard action both read, so the two controls can no longer +disagree; `ChatFormatTest.composerControlIsStopWhileARunIsInFlightAndSendOtherwise` +covers it. `android/` only; no new dependency. + +- Re-verified: `gradle :app:assembleDebug :app:testDebugUnitTest --offline` → + `BUILD SUCCESSFUL`, **266 tests, 0 failures** (the new composer-action case). +- **APK publish.** `app/build/outputs/apk/debug/app-debug.apk` (18,249,033 bytes, + sha256 `a9ce0cc8829513ee37fa5abaafa765307d5574f7cbd2b9cf0bc32392d0c1461e`) copied + to `~/.local/share/pipelines/data/artifacts/143/1/pipelines-debug-wip-609721d.apk`. + `curl -I http://10.0.0.249:8080/artifacts/143/1/pipelines-debug-wip-609721d.apk` + returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18249033`; a streamed `GET | shasum -a 256` matched. +- Not driven on a device in this pass: the constraint that the stop control be + exercised on an emulator only conflicts with this run's device note that only the + operator's Pixel (adb serial `58281FDCG000JF`) is available and no emulator may be + run, so the evidence here is the unit tests and the build rather than a fresh + screenshot. The earlier `emulator-5556` captures + (`.stop_check/stop_control_running.png`, `.stop_check/stop_control_stopped.png`) + still show the running/stopped control states. + Not verified in this pass: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index f489d124..2a14bf87 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -100,6 +100,18 @@ internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): else -> "Idle" } +/** Which action the composer's single primary control offers for a chat. */ +enum class ComposerAction { Send, Stop } + +/** + * The composer's primary control: while a turn is in flight the send control + * becomes the stop control (interrupt), otherwise it sends the draft. One + * derivation drives both the trailing button and the keyboard's send action, so + * a running turn can never be sent to from the other control. + */ +internal fun composerAction(thread: ChatThread): ComposerAction = + if (thread.running) ComposerAction.Stop else ComposerAction.Send + /** * One line of a derived unified diff. [CONTEXT] lines are unchanged, [ADD] came * from the edit's `newString` and [REMOVE] from its `oldString`. diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 7788ec76..ea7802dd 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -983,6 +983,7 @@ private fun ChatComposer( onSend: () -> Unit, onStop: () -> Unit, ) { + val action = composerAction(thread) Surface(color = MaterialTheme.colorScheme.surfaceContainer) { Column(Modifier.fillMaxWidth().padding(CHAT_GUTTER)) { if (thread.readOnly) { @@ -1001,17 +1002,18 @@ private fun ChatComposer( placeholder = { Text("Message the agent…") }, minLines = 1, maxLines = 6, - keyboardActions = KeyboardActions(onSend = { if (thread.canSend) onSend() }), + keyboardActions = KeyboardActions( + onSend = { if (action == ComposerAction.Send && thread.canSend) onSend() }, + ), modifier = Modifier.weight(1f), ) - if (thread.running) { + when (action) { // While a turn is in flight the send control becomes the stop // control, so it must interrupt rather than send the draft. - IconButton(onClick = onStop) { + ComposerAction.Stop -> IconButton(onClick = onStop) { Icon(Icons.Default.Stop, contentDescription = "Stop", tint = MaterialTheme.colorScheme.error) } - } else { - IconButton(onClick = onSend, enabled = thread.canSend) { + ComposerAction.Send -> IconButton(onClick = onSend, enabled = thread.canSend) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = "Send") } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt index c7d47995..381fed35 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -74,6 +74,14 @@ class ChatFormatTest { assertEquals("Idle", sessionStatusLabel(ChatSession(id = "s"), runningLocally = false)) } + @Test + fun composerControlIsStopWhileARunIsInFlightAndSendOtherwise() { + // While a turn is in flight the send control becomes the stop control: + // the phone's composer offers the interrupt, never a second send. + assertEquals(ComposerAction.Stop, composerAction(ChatThread(sessionId = "s", running = true))) + assertEquals(ComposerAction.Send, composerAction(ChatThread(sessionId = "s"))) + } + @Test fun toolEditDiffMarksOnlyChangedLinesAndCountsThem() { val input = JsonObject( From ee5cd742c2785411bfad1cbeed1584127ed00d7e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Fri, 16 Oct 2026 16:57:57 +0100 Subject: [PATCH 8/8] Prove the always decision through the shared approval reply builder Extend ChatApprovalTest so once, always and reject each go through the same ChatProtocol.replyRequest builder plus one encode/decode round trip using the DECISION_* constants, so no decision is asserted more weakly than another, and add answeringAlwaysUpdatesTheCardInPlace (settled card, no actions, risk panel retired, request still visible). Refresh the android/README.md verification notes: 267 tests, the rebuilt APK's sha256 and byte size, the 147/3 artifact path and LAN URL, and the emulator/device-lock notes for this pass. --- android/README.md | 60 +++++++++++-------- .../pipelines/ui/chat/ChatApprovalTest.kt | 52 +++++++++++----- 2 files changed, 70 insertions(+), 42 deletions(-) diff --git a/android/README.md b/android/README.md index 5cb7a855..5ab8350f 100644 --- a/android/README.md +++ b/android/README.md @@ -2841,33 +2841,37 @@ Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): - `gradle :app:testDebugUnitTest :app:assembleDebug` → `BUILD SUCCESSFUL`; the - JUnit XML totals **265 tests, 0 failures, 0 errors, 0 skipped** (new + JUnit XML totals **267 tests, 0 failures, 0 errors, 0 skipped** (new `ChatApprovalTest`: a pushed frame yields a pending card with the request's - action/resources/risk and its three actions, answering once/reject settles the - card in place, a server-resolved frame offers no actions, a failed reply reopens - the request, and the missing-summary fallback; new + action/resources/risk and its three actions, answering once/always/reject settles + the card in place, a server-resolved frame offers no actions, a failed reply + reopens the request, and the missing-summary fallback; new `ChatProtocolTest.chatPermissionFrameCarriesTheServerResolution`; the reply - builder is asserted for `once` and `reject`). -- The debug APK was installed on `emulator-5556` only and driven against + builder is asserted for `once`, `always` and `reject` through one shared + encode/decode round trip, so no decision is asserted more weakly than another). +- The rebuilt debug APK was driven on `emulator-5556` against `.approval_check/chat_stub_approval.py` (a stdlib `/connect` WebSocket double that pushes a pending `chat_permission` after a prompt and a server-resolved one - for a second session; test scaffolding, not the app). Captures validated with - `android/scripts/capture_png.sh -s emulator-5556`: `01_approval_pending.png` - (the `Approve edit` card with `src/layout.kt`, the amber `RISK REVIEW` panel and - the three actions, the top-bar pan-tool and the chat-chip marker), - `02_approval_answered.png` (the same card settled to `Allowed once`, no actions), - `03_approval_server_resolved.png` (a server-reported `Rejected` card with no - actions), `04_approval_findable.png` (scrolled up: the card at/below the fold, - the gold "Waiting for your approval" top-bar action present) and - `05_approval_jump.png` (tapping that action brought the card back). The stub log - recorded the `chat_reply` with `decision=once`. `adb -s emulator-5556 logcat -d` - held 0 `FATAL EXCEPTION` and 0 `E AndroidRuntime` during the sweep. -- **APK publish.** `app-debug.apk` (18,427,840 bytes, sha256 - `f39a1ed7f71759f6840a9e69a117e49a9884731a94133d2902ef7ebf096c0891`) copied to - `~/.local/share/pipelines/data/artifacts/136/1/pipelines-debug-wip-78d5bd3.apk`; - `curl -I http://10.0.0.249:8080/artifacts/136/1/pipelines-debug-wip-78d5bd3.apk` - returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, - `Content-Length: 18427840`, and a streamed `GET | shasum -a 256` matched. + for a second session; test scaffolding, not the app). Fresh captures this pass, + validated with `android/scripts/capture_png.sh -s emulator-5556` into + `~/.local/share/pipelines/data/artifacts/147/3/`: + `01_approval_pending.png` (the `Approve edit` card with `src/layout.kt`, the + amber `RISK REVIEW` panel and the three actions, the top-bar pan-tool and the + chat-chip marker) and `02_approval_answered.png` (the same card settled to + `Always allowed`, no actions, the amber risk panel retired). The stub log + recorded the `chat_reply` with `decision=always request=req_pending_1`. The + already-resolved path was reached too — the `Already resolved` session rendered + `Rejected` with the server's note and no controls — but `emulator-5556` shut + down before that frame could be captured, and it is not restarted here, so its + evidence is the `uiautomator` dump (`uiautomator_server_resolved.xml`) rather + than a second screenshot. +- **APK publish.** `app-debug.apk` (18,109,180 bytes, sha256 + `5f58ac6e92a7fbeb2fd023b5604fd7876e9d2546cc7cadf3d871aa7a4b7cce43`) copied to + `~/.local/share/pipelines/data/artifacts/147/3/pipelines-debug-wip-305714c.apk` + (`305714c` = `git rev-parse --short HEAD`); the running artifacts server serves + `curl -I http://10.0.0.75:8080/artifacts/147/3/pipelines-debug-wip-305714c.apk` + as `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18109180`, and a streamed `GET | shasum -a 256` matched. Not verified in this pass: the live brokered server (separate lane), streaming against real OpenCode, and attachments — unchanged from the passes above. The @@ -2875,6 +2879,10 @@ against real OpenCode, and attachments — unchanged from the passes above. The when it reports an already-settled request; the live server does not emit them yet, so only the unit test and the stub exercise that path. `:app:lintDebug` still cannot run here (the Gradle JVM's version string is rejected by AGP 8.7.2 lint), -unchanged from the slices above. The emulator was restarted mid-pass after it shut -down; it was `emulator-5556` throughout and the attached physical device was never -driven. +unchanged from the slices above. `emulator-5556` — this lane's standing device, +already running when the pass began and never started or restarted here — shut +down after the second capture, so the resolved frame was confirmed from the +accessibility tree rather than a screenshot. The run's device note (all device work +through the attached Pixel, no emulator) conflicts with the task constraint +(emulator only, never install on the person's device); this pass resolved it by +using the already-running emulator and never installing on the Pixel. diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt index bb4d6517..4d3f7f08 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatApprovalTest.kt @@ -65,24 +65,28 @@ class ChatApprovalTest { } @Test - fun onceAndRejectSendTheRightDecision() { + fun onceAlwaysAndRejectSendTheRightDecision() { // The same builder the repository sends, so the card's actions and this - // assertion cannot drift from the wire frame. - val once = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_ONCE) - assertEquals(Protocol.CHAT_REPLY, once.type) - assertEquals("ses_1", once.chatReply!!.sessionId) - assertEquals("req_9", once.chatReply!!.requestId) - assertEquals("once", once.chatReply!!.decision) + // assertion cannot drift from the wire frame. Every decision goes through + // the identical encode/decode round trip, so none is asserted more weakly + // than another. + for (decision in listOf( + ChatProtocol.DECISION_ONCE, + ChatProtocol.DECISION_ALWAYS, + ChatProtocol.DECISION_REJECT, + )) { + val reply = ChatProtocol.replyRequest("ses_1", "req_9", decision) + assertEquals(Protocol.CHAT_REPLY, reply.type) + assertEquals("ses_1", reply.chatReply!!.sessionId) + assertEquals("req_9", reply.chatReply!!.requestId) + assertEquals(decision, reply.chatReply!!.decision) - val decodedOnce = PipelinesJson.decodeFromString( - Message.serializer(), - PipelinesJson.encodeToString(Message.serializer(), once.copy(id = "android-1")), - ) - assertEquals(ChatProtocol.DECISION_ONCE, decodedOnce.chatReply!!.decision) - - val reject = ChatProtocol.replyRequest("ses_1", "req_9", ChatProtocol.DECISION_REJECT) - assertEquals("reject", reject.chatReply!!.decision) - assertEquals("req_9", reject.chatReply!!.requestId) + val decoded = PipelinesJson.decodeFromString( + Message.serializer(), + PipelinesJson.encodeToString(Message.serializer(), reply.copy(id = "android-1")), + ) + assertEquals(decision, decoded.chatReply!!.decision) + } } @Test @@ -99,6 +103,22 @@ class ChatApprovalTest { assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId) } + @Test + fun answeringAlwaysUpdatesTheCardInPlace() { + val store = storeWithPermission(frame()) + store.answerPermission("ses_1", "req_9", ChatProtocol.DECISION_ALWAYS) + + val settled = card(store) + assertEquals(ApprovalState.ANSWERED, settled.state) + assertFalse(settled.actionable) + assertEquals(ChatProtocol.DECISION_ALWAYS, settled.decision) + assertEquals("Always allowed", settled.headline) + // The request stays visible but stops asking; only a denial keeps the + // amber review panel, so an allow-always retires it. + assertFalse(settled.showRisk) + assertEquals("req_9", store.value.thread("ses_1")!!.permission!!.requestId) + } + @Test fun rejectingKeepsTheRiskReviewWhileItSettles() { val store = storeWithPermission(frame())