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" }) + } +}