diff --git a/android/README.md b/android/README.md index 44a598b7..1daf0a2c 100644 --- a/android/README.md +++ b/android/README.md @@ -5783,3 +5783,279 @@ Not verified in this pass: the search field, the directory sections and the empty state on a device, and the narrow/wide layouts — the brief keeps implementation verification to the build and the unit tests, and visual review owns the operator's Pixel 9 Pro XL. + +## The conversation header names the session's model (17 Oct 2026) + +A chat session's model was only visible in the session list row; inside a +conversation there was nothing saying what was answering. The conversation header +now shows the session's model beside its `Operator` tag and its directory, read +from the session the server already reports. `android/` only; no dependency was +added beyond the already-declared material-icons-extended, nothing in the +Pipelines server, its Go source, the installer or the Docker files was touched, +and no run is started from the app. + +- **One derivation, server-reported only.** `ui/chat/ChatFormat.kt` adds + `chatHeaderMeta(thread)`: the model id, the session's kind tag (through the + shared `sessionTagLabel`, refactored to a tag-value overload so the list row + and the header cannot label a tag differently) and the directory, joined with + ` · `. Every part is a value the server reported; a blank part is omitted, so a + session the server reported without a model (or an older server that omits the + field) shows no model claim at all — never a guess and never a catalogue. +- **The open thread carries what the server reports.** `ChatThread` gains the + `tag` field (it already mirrored title/directory/model/agent/busy), and + `ChatStore` now folds the server's `model`/`agent`/`tag` into an already-open + thread on `sessionsLoaded` (not only on first `open`), and seeds them in the + `ensureThread` placeholder. So the header never shows a stale or missing model + after a list refresh or for a background chat. +- **The header surface.** `ChatScreen.ChatConversationPane`'s top bar title + becomes a two-line `Column`: the existing title, then the meta line in the + shared `pipelinesText().meta` role with `onSurfaceVariant`, ellipsised — no new + geometry literal. + +**No model chooser is shipped, and why.** The brief asks to let the operator +choose a session's model and report the exact server change if the server has no +request for it. It does not: `ChatPromptRequest` carries `model`/`agent` on the +wire (`internal/protocol/chat.go`), but the endpoint drops them — +`handleChatPrompt` calls `broker.Prompt(ctx, sessionID, prompt.Text)` and +`opencode.Chat.Prompt` posts only `{"text": ...}` — and there is no request that +sets a session's model, nor any request that lists the endpoint's models or +agents to offer a choice from. Shipping a picker would be a control that does +nothing, so the create flow instead says so plainly ("This server has no request +for choosing a chat's model, so a new chat uses the server's default.") and the +header shows the model the server does report once the session exists. + +The exact server change it would need: (1) forward the chosen model/agent — +extend `chatBroker.Prompt` and `opencode.Chat.Prompt` to accept them and include +`model`/`agent` in the `POST /api/session/{id}/prompt` body, and pass +`prompt.Model`/`prompt.Agent` from `handleChatPrompt`; (2) expose a catalogue +request (for example `chat_models`/`chat_agents`, answered from the endpoint's +model/agent list) so the client can offer only what the server reports; and +(3) optionally accept `model`/`agent` on `chat_create` so a session starts with +the operator's chosen default rather than the endpoint's. Until then the app is +honest: it shows what the server reports and does not pretend to set it. + +Tests (4 new): in `ChatFormatTest`, that `chatHeaderMeta` shows the reported +model, tag and directory, that it never claims a model the server did not report +(blank thread → empty, tag only → `Operator`), and that a session tag and a +thread tag label the same; in `ChatSessionManagementTest`, that an open +conversation carries the model/agent/tag the server reports and that a later list +refresh folds the server's new model into the open thread. + +Evidence (this run's implementer pass, macOS, Gradle 8.11.1 at +`~/.gradle/wrapper/dists/gradle-8.11.1-bin/bpt9gzteqjrbo1mjrsomdt32c/gradle-8.11.1/bin/gradle` +with `JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home"` +(JDK 17) and `ANDROID_HOME=/Users/alan/Library/Android/sdk`): +`gradle --offline --no-daemon :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the +JUnit XMLs total **55 suites / 505 tests / 0 failures / 0 errors / 0 skipped** (4 +new). `gradle --offline --no-daemon :app:assembleDebug` → `BUILD SUCCESSFUL`; the +APK was published to this run's artifacts directory as +`pipelines-debug-wip-8e6cb39.apk` (18,706,104 bytes, sha256 +`b52f2be1fcfce2654b90b9735ce03683fbf91e0a651b2b0ad49e92488d81ad05`; `8e6cb39` is +`git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it) and is +served at +`http://10.0.0.75:8080/artifacts/272/1/pipelines-debug-wip-8e6cb39.apk` +(`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, +`Content-Length: 18706104`). + +Not verified in this pass: the header meta on a device and the create-flow note — +the brief keeps implementation verification to the build and the unit tests, and +visual review owns the operator's Pixel 9 Pro XL. No packaged skill reference was +touched: this is an app-UI change and no reference describes the chat surface. + +## Conversation reading: markdown, collapsed reasoning, one identity (17 Oct 2026) + +Making the conversation readable on a phone. `android/` only; no new dependency +(the declared `material-icons-extended` only), no Pipelines server/Go/installer/ +Docker file touched and no run started from the app. + +- **Markdown reaches the transcript (tested).** The assistant `text` part was + already rendered through `MarkdownText`, but the transcript's decision was + buried in a private composable. `ChatFormat.partRendering(part)` now names the + one decision the transcript makes (`MARKDOWN` / `REASONING` / `PLAIN` / + `HIDDEN`), `MessagePart` consumes it, and `ChatTranscriptTest` drives a sample + covering the whole documented subset (headings, paragraph, bullet and ordered + lists, quote, table, fenced code, rule, inline code/bold/italic/link) from a + `ChatPart` into `parseMarkdown`/`parseInline`. Text outside the subset (raw + HTML, `~~strike~~`) still parses to a paragraph and renders verbatim; an + unknown part kind still renders its text, never drops it. +- **Reasoning collapsed by default.** `ReasoningBlock` is now one compact, + muted line per part — a `Psychology` icon, a label (`Thinking…` while the + newest turn streams, `Reasoning` once settled) and a chevron — that expands on + tap to the full, still-muted text. Expansion is a pure + `ReasoningExpansion` set hoisted to the conversation pane (not the lazy + transcript), so a part keeps its state while the operator scrolls and its item + is disposed, and every part starts collapsed in a freshly opened chat. The + choice for a running turn: its streaming reasoning stays collapsed and keeps + following the stream under the live `Thinking…` label, so it signals progress + without competing with the answer. +- **One identity in the header.** `ChatFormat.conversationHeader(thread)` builds + the app-bar title plus the only extra context — the labelled kind chip + (`Operator`) from the server's own tag, the activity (`Running` / + `Busy · read-only` / `Idle`), the directory and the model — and the app bar and + context line read the same value. The conversation's active chip is omitted + from the open-chat strip (`openChatsBeside`), so the session's title is shown + once; every *other* open chat is still one tap away, and the session list is + unchanged. + +Tests (`ChatTranscriptTest`, 7 cases, plus the existing `ChatFormatTest`): the +markdown subset reaches the renderer from a `ChatPart`; text outside the subset +and an unknown part kind still render; reasoning starts collapsed, toggles per +part and never expands on a blank key; the header names the session once with +only kind/activity/directory/model beside it; and the conversation strip offers +only the other open chats. + +Evidence (macOS, JDK 17, Gradle 9.7.1 `--offline`, `--no-daemon`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:assembleDebug --no-daemon --offline --rerun-tasks` → `BUILD + SUCCESSFUL` (35 tasks executed). +- `gradle :app:testDebugUnitTest --no-daemon --offline --rerun-tasks` → + `BUILD SUCCESSFUL`; the JUnit XMLs total **508 tests, 0 failures, 0 errors, 0 + skipped** (7 new in `ChatTranscriptTest`). +- **APK publish.** `app-debug.apk` copied to this run's artifacts directory as + `pipelines-debug-wip-5ac196c.apk` (18,486,624 bytes, sha256 + `0df6899429a8f5632ec568340dddb63a5617b1a04af19f52c6ebb793470a0b23`; `5ac196c` + is `git rev-parse --short HEAD`, the tree being uncommitted WIP on top of it). + It is served at + `http://10.0.0.75:8080/artifacts/274/1/pipelines-debug-wip-5ac196c.apk` + (`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18486624`). + +Not verified in this pass: the conversation, the collapsed/expanded reasoning +and the header on a device — the brief keeps implementation verification to the +build and the unit tests, and visual review owns the operator's Pixel 9 Pro XL +(captures: headings/list/fenced code/table, reasoning collapsed then expanded, +and the header). + +## Answer a waiting human decision from the phone (17 Oct 2026) + +The last piece of the original goal the app was missing: a run parked on a person +is now answerable from the phone. `android/` only; nothing in the Pipelines +server, its Go source, the installer or the Docker files was touched, no +dependency was added (the new glyph comes from the already-declared +`material-icons-extended`), no run was started from the app and no server field +was added. + +- **The same `decide` request the terminal uses.** `Protocol.DECIDE_RUN` + (`decide_run`) with `stage`, `option` and optional `feedback`, exactly the fields + `internal/protocol/message.go` carries and the TUI's Enter builds + (`internal/tui/decision.go`); `PipelinesRepository.decideRun` sends them and + returns the resumed run's detail. There is no second mechanism. +- **Surfaced through the existing push path, with no server change.** A waiting + transition already arrives as a `run_event` with `status: waiting` and a waiting + step delta. The compact delta omits the waiting step's `output` — where the + author's options and instructions are recorded — so `runDetailNeedsFullSync` now + also fetches the full run on a waiting run/step; that fetch fills the recorded + evidence and the decision appears live, with no refresh. `RunState` gained + `Waiting` (violet, `FrontHand`, its own label) so the runs list and the run + summary show "waiting" instead of the unknown fallback. `lastWaitingStep`, + `waitingOptions`, `waitingPrompt` and `humanOptions` mirror `tui.lastWaitingStep`, + `protocol.WaitingOptions`/`WaitingPrompt` and `stage.HumanOptions`. +- **Where it is reachable.** A prominent "Waiting for your decision" card with a + Decide action sits above the run detail's tabs (on any tab — opening the run is + enough) and at the top of the waiting stage's pane; both open the same sheet. It + is not wired to a submenu, and an attention surface (another item) renders the + same shared `DecisionPrompt`/`pendingDecision` component. +- **The sheet.** It shows the run and the waiting stage, the author's recorded + instructions, every option exactly as written (its edge key) with the label it + routes to (`deploy → SUCCESS`), an optional feedback field and a deliberate + `Confirm decision` button. Selecting an option only selects it; the button stays + disabled until one is chosen, so a stray tap cannot answer by accident. + Answering applies the returned run immediately, so the run's new stage is shown + without a manual refresh. +- **Refusals are honest.** A refusal (the run moved on, the stage changed, another + client answered first) keeps the sheet open with the server's own message + verbatim, and the run is re-read silently so the app stops offering a decision + that is gone — never a silent failure and never a faked success. + +Pure helpers: `pendingDecision` (the step's recorded evidence first, the pinned +graph as the fallback), `DecisionOption`, `DecisionDraft` (the deliberate-confirm +gate) and `decisionRefusalMessage`. + +Tests (13 new): `HumanDecisionTest` (6 — the recorded options/instructions, +non-string tolerance, the sorted non-error-edge fallback, the last waiting step +and the `decide_run` envelope with its exact wire names) and `DecisionTest` (7 — +the waiting run's stage/options/targets/instructions, non-waiting runs, the graph +fallback, the prompt fallback, stage inference, the confirm gate with optional +feedback, and the verbatim refusal message). `RunEventsTest`'s sync rule gained +the waiting cases and `RunStatusTest` the waiting status mapping. + +Evidence (implementer pass, macOS, cached Gradle 8.11.1 at +`~/.gradle/wrapper/dists/gradle-8.11.1-bin/bpt9gzteqjrbo1mjrsomdt32c/gradle-8.11.1/bin/gradle`, +JDK 17 from Homebrew `openjdk@17`, +`ANDROID_HOME=/Users/alan/Library/Android/sdk`, every command +`--no-daemon --offline`): + +- `gradle :app:testDebugUnitTest --offline --no-daemon --console=plain` → + `BUILD SUCCESSFUL`; the JUnit XMLs total **57 suites / 518 tests / 0 failures / + 0 errors / 0 skipped** (up from 55 suites / 505 tests). +- `gradle :app:assembleDebug --offline --no-daemon --console=plain` → + `BUILD SUCCESSFUL`; `app/build/outputs/apk/debug/app-debug.apk` is 18,519,392 + bytes, sha256 + `4086e6dab453dba81fd0e2f023b0c6713600a68f78d95ada073e0df785b971a1` + (`--rerun-tasks --no-build-cache`, reproduced byte-for-byte by a second full + rebuild; an incremental package is not byte-reproducible), published to this + run's artifacts directory as `pipelines-debug-wip-d48175a.apk` (`d48175a` = + `git rev-parse --short HEAD`; the tree is uncommitted WIP on top of it) and + served at + `http://10.0.0.75:8080/artifacts/277/1/pipelines-debug-wip-d48175a.apk` + (`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`, + `Content-Length: 18519392`); `10.0.0.249` served it too. + +Not verified in this pass: the on-device sheet/feedback/refusal behaviour and the +screenshots — the brief keeps implementation verification to the build and the +unit tests, and visual review owns the operator's Pixel 9 Pro XL. The "attention +surface" named in the brief is not present in this tree, so the decision is +reachable from the run detail and its stage and the shared component is ready for +it. No packaged skill reference was touched: the decide protocol is unchanged and +already documented, and this is an app-UI change. + +## Run title readability: whole in the run view, two lines in the list (17 Oct 2026) + +A run's title is derived from its prompt, so it is often long. The run view now +guarantees the operator can read it whole, while the places that are one of many +clamp deliberately. `android/` only; no new dependency, no Pipelines +server/Go/installer/Docker file touched and no run started from the app; the build +and unit tests only, no device command run. + +- **Run view shows the whole title.** The run-summary title line rendered + `runLabel(run.title, run.name)` with the Compose default; it now states the + intent with `RUN_VIEW_TITLE_LINES` (`Int.MAX_VALUE`) and `TextOverflow.Clip`, so + it wraps over as many lines as it needs and is never ellipsised. The fixed-height + M3 app-bar copy stays a compact one-line label; the summary's scrollable title is + the complete one. +- **Runs-list rows grow, then clamp.** `RunHistoryScreen.RunRow`'s title went from + `maxLines = 1` to `RUN_ROW_TITLE_LINES` (2), so a longer title takes a second + line before it ellipsises; the row's glyph, status chip and meta line keep their + alignment and the selection highlight and tap target are unchanged. +- **Stage-pane context line.** `StageDetailPane`'s run-label line went from + `maxLines = 1` to `STAGE_RUN_LABEL_LINES` (2) — the pane is compact context, not + the place the whole title lives. +- **One named budget.** `ui/RunIdentity.kt` holds the three named line budgets so + the choice is deliberate at each call site. `RunTitlesTest` (4 cases) pins them + and asserts a clamping place is never more generous than the run view; + `RunIdentityTest` gained a case that `runLabel`/`runIdentity` never shorten a + long title, so re-introducing a truncating helper here fails. + +Tests: the 57 result XMLs aggregate to **513 tests, 0 failures, 0 errors, 0 +skipped** (`RunTitlesTest` 4/0, `RunIdentityTest` 6/0). + +Evidence (macOS, JDK 17 from Homebrew `openjdk@17`, Gradle 9.7.1 `--offline`, +`--no-daemon`, `ANDROID_HOME=/Users/alan/Library/Android/sdk`): + +- `gradle :app:testDebugUnitTest --no-daemon --offline --rerun` → `BUILD + SUCCESSFUL`. +- `gradle :app:assembleDebug --no-daemon --offline` → `BUILD SUCCESSFUL`; + `app-debug.apk` 18,486,624 bytes, sha256 + `2b23762b54f011bbec680804a232f32bd43c244fb52c465a0f4b2c2c9a0148cb`. +- **APK publish.** Copied to this run's artifacts directory as + `pipelines-debug-wip-2bc00a2.apk` (`2bc00a2` = `git rev-parse --short HEAD`, the + tree being uncommitted WIP on top of it), served at + `http://10.0.0.75:8080/artifacts/278/4/pipelines-debug-wip-2bc00a2.apk` + (`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`; the + downloaded bytes hash to the same sha256). + +Not verified in this pass: how the wrapping summary title, the two-line list row +and the two-line stage header actually render — that needs the device, which this +build-and-unit-test pass did not use; visual review owns the operator's Pixel 9 +Pro XL. 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 3f2a0896..77189e59 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 @@ -207,6 +207,34 @@ class PipelinesRepository( Message(type = Protocol.RETRY_RUN, runId = id, requestKey = requestKey), ).runDetail ?: throw ProtocolException("The server returned no run detail.") + /** + * Answers a run's waiting human stage with the chosen [option] and optional + * [feedback] (the `decide` command behind `pipelines decide`). The server + * validates the option against the waiting stage and resumes the run along + * that edge; the reply is the resumed run's detail. A refused decision (the + * run moved on, the stage changed, or another client answered first) comes + * back as a [ProtocolException] carrying the server's own reason. + */ + suspend fun decideRun( + runId: Long, + stage: String, + option: String, + feedback: String = "", + ): RunDetail { + if (runId <= 0) throw ProtocolException("Select a run to decide.") + if (option.isBlank()) throw ProtocolException("Choose one of the stage's options.") + val response = client.call( + Message( + type = Protocol.DECIDE_RUN, + runId = runId, + stage = stage.takeIf { it.isNotBlank() }, + option = option, + feedback = feedback.takeIf { it.isNotBlank() }, + ), + ) + return response.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. ---- diff --git a/android/app/src/main/java/net/awan/pipelines/data/protocol/HumanDecision.kt b/android/app/src/main/java/net/awan/pipelines/data/protocol/HumanDecision.kt new file mode 100644 index 00000000..0972472a --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/data/protocol/HumanDecision.kt @@ -0,0 +1,68 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull + +/** + * A `type=human` stage pauses its run until a person chooses one of its + * non-error edges. The step's status, the run's status and the recorded + * evidence keys below mirror `internal/protocol/runs.go` exactly, so the phone + * reads the same one definition the store, runner, CLI and TUI write. + * + * The names are the wire contract: [WAITING_PROMPT_KEY]/[WAITING_OPTIONS_KEY] + * are the keys the server records in the waiting step's output + * (`protocol.NewWaitingEvidence`), and the phone is their read side + * (`protocol.WaitingPrompt`/`WaitingOptions`). + */ + +/** Run status while parked on a person; no later stage runs until it is decided. */ +const val RUN_STATUS_WAITING = "waiting" + +/** The waiting step's status, i.e. the step a decision answers. */ +const val STEP_STATUS_WAITING = "waiting" + +/** Waiting evidence key holding the author's operator instructions. */ +const val WAITING_PROMPT_KEY = "prompt" + +/** Waiting evidence key holding the author's ordered selectable options. */ +const val WAITING_OPTIONS_KEY = "options" + +/** + * The recorded operator instructions from a waiting step's output, or "" when + * none were recorded. Mirrors `protocol.WaitingPrompt`. + */ +fun waitingPrompt(output: Map?): String = + (output?.get(WAITING_PROMPT_KEY) as? JsonPrimitive)?.contentOrNull.orEmpty() + +/** + * The recorded selectable options from a waiting step's output, in recorded + * order. Mirrors `protocol.WaitingOptions`: strings only, a malformed entry + * dropped rather than crashing, and an absent key yields an empty list. The + * options are exactly the author's non-error edge keys, recorded at wait time so + * the choice is answerable without re-reading the pinned graph. + */ +fun waitingOptions(output: Map?): List { + val array = output?.get(WAITING_OPTIONS_KEY) as? JsonArray ?: return emptyList() + return array.mapNotNull { element -> + // Only string options, exactly like protocol.WaitingOptions' `option.(string)`. + (element as? JsonPrimitive)?.takeIf { it.isString }?.contentOrNull + }.filter { it.isNotBlank() } +} + +/** + * A stage's selectable outcomes: its non-error edges in sorted order. Mirrors + * `stage.HumanOptions`, the fallback when a waiting step recorded no options + * (a step from an older server). + */ +fun humanOptions(edges: Map): List = + edges.keys.filter { it != "error" }.sorted() + +/** + * The most recent step a run is waiting on (the last waiting step by sequence), + * or null when no step is waiting. Mirrors `tui.lastWaitingStep`, so the phone + * and the run inspector answer the same step. + */ +fun lastWaitingStep(steps: List): RunStep? = + steps.lastOrNull { it.status == STEP_STATUS_WAITING } 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 b83db794..1fa78fd3 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 @@ -34,6 +34,9 @@ object Protocol { const val RUN = "run" const val CANCEL_RUN = "cancel_run" const val RETRY_RUN = "retry_run" + // Answers a waiting human stage: the stage (optional; the server infers it + // from the run's current stage), the chosen option and optional feedback. + const val DECIDE_RUN = "decide_run" const val GET_RUN_EVIDENCE = "get_run_evidence" const val RUN_EVIDENCE = "run_evidence" @@ -616,6 +619,12 @@ data class Message( @SerialName("run_id") val runId: Long = 0, @SerialName("run_detail") val runDetail: RunDetail? = null, val runs: List? = null, + // The decide request body (runs.go DecideRun): the stage to answer (empty + // lets the server infer it), the chosen option and optional feedback. Every + // field is optional so an unrelated envelope never carries them. + val stage: String? = null, + val option: String? = null, + val feedback: String? = null, // The workspace-scoped run-state push subscription: `run_ids` is the optional // subscribe scope and `run_event` the server-pushed delta (runevents.go). @SerialName("run_ids") val runIds: List? = null, 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 77d6ca34..248f62c4 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 @@ -789,6 +789,43 @@ class AppViewModel( } } + /** + * Answers a run's waiting human stage with [option] and optional [feedback]. + * The reply is the resumed run's detail, applied immediately so the run's + * state reflects the new stage without waiting for the next push. A refused + * decision is not hidden: the run is re-read (silently, so the shown detail + * never flashes to an error) so the app stops offering a decision the run has + * already moved past, and the failure is reported to the caller. + */ + fun decideRun( + id: Long, + stage: String, + option: String, + feedback: String, + onResult: (Result) -> Unit, + ) { + viewModelScope.launch { + try { + val run = repository.decideRun(id, stage, option, feedback.trim()) + // Apply the resumed run now: it is newer than any in-flight + // detail sync, so bump the delta counter to keep an older fetch + // from writing over it. + if (_runDetail.value.data?.id == id) { + detailDeltaCount++ + _runDetail.value = LoadState(loading = false, data = run, loaded = true) + } + onResult(Result.success(run)) + } catch (t: Throwable) { + if (t is CancellationException) throw t + // The run moved on, the stage changed or another client answered + // first: re-read the run so the view tells the truth, then report + // the server's own reason to the caller. + loadRun(id, silent = true) + onResult(Result.failure(t)) + } + } + } + // ---- Brokered chat ------------------------------------------------------- /** Refreshes the server's session list; never clears open conversations. */ diff --git a/android/app/src/main/java/net/awan/pipelines/ui/Decision.kt b/android/app/src/main/java/net/awan/pipelines/ui/Decision.kt new file mode 100644 index 00000000..3f602114 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/Decision.kt @@ -0,0 +1,107 @@ +package net.awan.pipelines.ui + +import net.awan.pipelines.data.ErrorMessages +import net.awan.pipelines.data.protocol.GraphSemantics +import net.awan.pipelines.data.protocol.Protocol +import net.awan.pipelines.data.protocol.RUN_STATUS_WAITING +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.humanOptions +import net.awan.pipelines.data.protocol.lastWaitingStep +import net.awan.pipelines.data.protocol.waitingOptions +import net.awan.pipelines.data.protocol.waitingPrompt + +/** + * One option the author wrote for a waiting human stage: the edge [key] (the + * exact outcome the decision carries) and the [target] it routes to, resolved to + * the same label the graph shows (`publish`, `SUCCESS`, `FAILURE`). The target is + * what tells the operator where an option leads; it is blank when the pinned + * graph does not declare the option (an older server, or a recorded option the + * graph no longer carries). + */ +data class DecisionOption(val key: String, val target: String) + +/** + * A run parked on a person: the run, the stage waiting, the author's recorded + * instructions and their ordered options. Derived purely from the run detail the + * app already holds (the waiting step's recorded evidence, falling back to the + * pinned graph), so the decision sheet and its unit test read one model instead + * of each parsing the step. + */ +data class PendingDecision( + val runId: Long, + val runLabel: String, + val stageKey: String, + val instructions: String, + val options: List, +) { + /** The author's option keys, in recorded order. */ + val optionKeys: List get() = options.map { it.key } +} + +/** + * The pending decision a [run] is waiting on, or null when it is not waiting (or + * recorded no selectable options). The waiting step's own evidence wins over the + * pinned graph, so the decision still works when the graph is absent; the graph + * only supplies the target labels and, for a step from an older server, the + * option set itself. + */ +fun pendingDecision(run: RunDetail?): PendingDecision? { + if (run == null || run.status != RUN_STATUS_WAITING) return null + val step = lastWaitingStep(run.steps) + val stageKey = step?.stage?.takeIf { it.isNotBlank() } + ?: run.currentStage.takeIf { it.isNotBlank() } + ?: return null + val declared = run.graph.stages.firstOrNull { it.key == stageKey } + val keys = step?.let { waitingOptions(it.output) }.orEmpty() + .ifEmpty { declared?.let { humanOptions(it.edges) }.orEmpty() } + if (keys.isEmpty()) return null + val edges = declared?.edges.orEmpty() + val options = keys.map { key -> DecisionOption(key, decisionTargetLabel(key, edges[key])) } + val instructions = step?.let { waitingPrompt(it.output) }.orEmpty() + .ifBlank { declared?.prompt.orEmpty() } + return PendingDecision( + runId = run.id, + runLabel = runLabel(run.title, run.name), + stageKey = stageKey, + instructions = instructions, + options = options, + ) +} + +/** + * The resolved target label for one option: the author's target, with the `#` + * shorthand resolved and terminals named as the graph names them. Blank when the + * option's edge is not declared, so the sheet omits the detail instead of + * inventing a destination. + */ +internal fun decisionTargetLabel(option: String, target: String?): String { + if (target.isNullOrBlank()) return "" + return GraphSemantics.nodeLabel(Protocol.resolveTarget(option, target)) +} + +/** + * The operator's in-progress answer to a [PendingDecision]: the chosen option and + * optional feedback. Pure, so the deliberate-confirm rule (nothing is sent until + * an option is chosen and the confirm pressed) is unit-tested without a device. + */ +data class DecisionDraft( + val selected: String? = null, + val feedback: String = "", +) { + /** A decision is only sendable once the operator has chosen one option. */ + val canSubmit: Boolean get() = !selected.isNullOrBlank() + + /** Selecting an option is not an answer: it only enables the confirm. */ + fun select(option: String): DecisionDraft = copy(selected = option) + + /** Feedback is optional and carried verbatim (trimmed by the sender). */ + fun withFeedback(text: String): DecisionDraft = copy(feedback = text) +} + +/** + * The message a refused decision shows. The server's own text is used verbatim + * because it names exactly what happened (the run moved on, the stage changed, + * another client answered first), so a refusal is reported, never replaced by a + * generic failure. + */ +fun decisionRefusalMessage(error: Throwable): String = ErrorMessages.describe(error) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt index cfd68435..ffaa7c48 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunEvents.kt @@ -22,6 +22,15 @@ import net.awan.pipelines.data.protocol.RunSummary /** Run statuses from which a run never transitions again. */ internal val TERMINAL_RUN_STATUSES = setOf("succeeded", "failed", "canceled", "interrupted") +/** + * Whether [status] is the human-stage status a run (or its waiting step) parks on: + * it is not terminal and it is not executing, but it still needs the full detail + * (the compact delta carries no options/prompt), so a pending decision is + * surfaced live. + */ +internal fun isWaitingRunStatus(status: String): Boolean = + status.trim().lowercase() == "waiting" + /** The lifecycle rank at which a status is settled: a later status never rewrites it. */ private const val SETTLED_RANK = 2 @@ -97,12 +106,16 @@ internal fun foldRunEvent(detail: RunDetail, frame: RunEventFrame): RunDetail { /** * Whether a frame carries data the compact delta cannot express (recorded * artifacts, output, a settled visit's diagnostic), so the caller fetches the - * full run once to fill those in rather than showing a stale gallery. + * full run once to fill those in rather than showing a stale gallery. A waiting + * run or step is included: its options and prompt live in the waiting step's + * `output`, which the compact delta deliberately omits, so the fetch is what + * surfaces a pending decision without a manual refresh. */ internal fun runDetailNeedsFullSync(frame: RunEventFrame): Boolean { val step = frame.step val stepSettled = step != null && stepLifecycleRank(step.status) >= 2 - return stepSettled || isTerminalRunStatus(frame.status) + val stepWaiting = step != null && isWaitingRunStatus(step.status) + return stepSettled || stepWaiting || isTerminalRunStatus(frame.status) || isWaitingRunStatus(frame.status) } /** diff --git a/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt b/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt index 79e9c079..38ebeaf2 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/RunIdentity.kt @@ -24,3 +24,22 @@ fun runIdentity(title: String?, name: String): RunIdentity { val stored = title?.trim().orEmpty() return if (stored.isEmpty()) RunIdentity(name, null) else RunIdentity(stored, name) } + +/** + * The line budget for a run's title in each place the app shows it. A title is + * derived from the run's prompt, so it is often long, and the places it appears + * have different jobs: the run view exists to let the operator read the run, so + * its own title is complete, while a runs-list row (one of many) and the stage + * pane's compact run-context line may clamp because the run view still carries + * the whole title. Kept here, named, so the budgets are a deliberate choice the + * tests pin rather than a bare `maxLines` literal at each call site. + */ + +/** The run view's own title never elides: it wraps over as many lines as it needs. */ +internal const val RUN_VIEW_TITLE_LINES: Int = Int.MAX_VALUE + +/** A runs-list row's title grows to two lines for a longer title, then ellipsises. */ +internal const val RUN_ROW_TITLE_LINES: Int = 2 + +/** The stage pane's compact run-context line shows at most two lines, then ellipsises. */ +internal const val STAGE_RUN_LABEL_LINES: Int = 2 diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt index 56836c07..563d261b 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatFormat.kt @@ -93,12 +93,35 @@ internal fun sessionTitle(session: ChatSession): String = * session shows no chip. This only *labels*; the app never filters on the tag, * because the server already lists operator sessions only. */ -internal fun sessionTagLabel(session: ChatSession): String? = when { - session.tag.isBlank() -> null - session.tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL - else -> session.tag +internal fun sessionTagLabel(session: ChatSession): String? = tagLabel(session.tag) + +/** + * The kind chip label for a session's own tag value (see [sessionTagLabel]). + * Kept as the single mapping so a session and the conversation it opens cannot + * label the same tag differently. + */ +internal fun sessionTagLabel(tag: String): String? = tagLabel(tag) + +private fun tagLabel(tag: String): String? = when { + tag.isBlank() -> null + tag == ChatProtocol.TAG_OPERATOR -> OPERATOR_TAG_LABEL + else -> tag } +/** + * The one-line meta under a conversation's own title: the model the server + * reports is answering, the session's kind tag and its directory. Every part is + * a value the server reported (a model id, the wire tag, the directory), so + * nothing is guessed and no catalogue is invented; a blank part is omitted, so a + * session the server reported without a model (or an older server that omits the + * field) shows no model claim at all. + */ +internal fun chatHeaderMeta(thread: ChatThread): String = listOfNotNull( + thread.model.takeIf { it.isNotBlank() }, + sessionTagLabel(thread.tag), + thread.directory.takeIf { it.isNotBlank() }, +).joinToString(" · ") + private const val OPERATOR_TAG_LABEL = "Operator" /** @@ -110,9 +133,13 @@ private const val OPERATOR_TAG_LABEL = "Operator" * `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 { +internal fun sessionStatusLabel(session: ChatSession, runningLocally: Boolean): String = + sessionStatusLabel(session.busy, runningLocally) + +/** The status of a conversation from its own model flags (see [sessionStatusLabel]). */ +internal fun sessionStatusLabel(busy: Boolean, runningLocally: Boolean): String = when { runningLocally -> "Running" - session.busy -> "Busy · read-only" + busy -> "Busy · read-only" else -> "Idle" } @@ -135,6 +162,73 @@ internal fun sessionActivity(running: Boolean, unseen: Boolean): SessionActivity else -> SessionActivity.IDLE } +/** + * The one identity a conversation header shows: the title is the session's + * name, and everything else is context that cannot be mistaken for a second + * name — the server's kind tag, the live activity and the directory/model. + * Kept pure so the header and its unit test agree that the title appears once. + */ +internal data class ConversationHeader( + val title: String, + val kind: String?, + val activity: String, + val directory: String, + val model: String, +) { + /** The extra identity context, in reading order, with blank fields omitted. */ + val context: List = listOf(directory, model).filter { it.isNotBlank() } +} + +/** Builds the conversation header from the open thread's copied session fields. */ +internal fun conversationHeader(thread: ChatThread): ConversationHeader = ConversationHeader( + title = sessionTitle(ChatSession(id = thread.sessionId, title = thread.title)), + kind = sessionTagLabel(thread.tag), + activity = sessionStatusLabel(thread.busy, thread.running), + directory = thread.directory, + model = thread.model, +) + +/** + * The open chats a conversation still offers to switch to: every other open + * chat, never the active one, so its title is not repeated beside its own + * header. The session list keeps showing all open chats. + */ +internal fun openChatsBeside(open: List, activeSessionId: String): List = + open.filterNot { it.sessionId == activeSessionId } + +/** + * How the transcript renders one part. The decision is pure so the markdown + * route out of the transcript can be tested without Compose: assistant text is + * markdown, reasoning is its own collapsed presentation, any other part with + * text is plain, and an empty part renders nothing. + */ +internal enum class PartRendering { MARKDOWN, REASONING, PLAIN, HIDDEN } + +internal fun partRendering(part: ChatPart): PartRendering = when { + part.type == ChatProtocol.PART_TEXT && part.text.isNotBlank() -> PartRendering.MARKDOWN + part.type == ChatProtocol.PART_REASONING && part.text.isNotBlank() -> PartRendering.REASONING + part.text.isNotBlank() -> PartRendering.PLAIN + else -> PartRendering.HIDDEN +} + +/** + * Which reasoning parts the operator has opened. A set keyed by the stable + * per-part key, so a streaming part keeps its state as deltas arrive and every + * part starts collapsed in a freshly opened conversation. + */ +internal data class ReasoningExpansion(private val expanded: Set = emptySet()) { + fun isExpanded(partKey: String): Boolean = partKey in expanded + + fun toggled(partKey: String): ReasoningExpansion { + if (partKey.isBlank()) return this + return copy(expanded = if (partKey in expanded) expanded - partKey else expanded + partKey) + } +} + +/** The stable key for one reasoning part, even when the server omitted its id. */ +internal fun reasoningKey(messageId: String, part: ChatPart, index: Int): String = + messageId + ":" + part.id.ifBlank { index.toString() } + /** Which action the composer's single primary control offers for a chat. */ enum class ComposerAction { Send, Stop } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt index 189ecb1a..ab0767f0 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatScreen.kt @@ -70,6 +70,7 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar +import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -139,6 +140,7 @@ import net.awan.pipelines.ui.theme.ICON_LIST_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.SPACING_S import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_XS import net.awan.pipelines.ui.theme.SPACING_XXS import net.awan.pipelines.ui.theme.TOOL_PANEL_MAX_WIDTH_DP import net.awan.pipelines.ui.theme.pipelinesText @@ -628,6 +630,19 @@ private fun NewChatPane( modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), ) } + // The brokered server exposes no request for choosing a + // session's model: chat_prompt carries model/agent fields but + // the server does not forward them, and there is no catalogue + // request to offer a choice from. So the flow says so plainly + // rather than shipping a picker that would do nothing. The + // conversation header then shows whatever model the server + // reports for the created session. + Text( + text = "This server has no request for choosing a chat's model, so a new chat uses the server's default.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + ) NewChatActions( directory = selected?.createDirectory ?: create.directory, creating = create.creating, @@ -726,17 +741,26 @@ private fun NotConnectedNotice() { } /** - * 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). + * The open-conversation switcher: one chip per open conversation, so several + * chats can be kept at once and switched between in one tap. A running chat + * carries its live dot, a chat waiting on an approval carries its hand, and the + * X closes that chat (optional close is provided). [excludeSessionId] omits one + * chat — the conversation pane omits its own active one, whose title already + * stands in the app bar, while the session list shows every open chat. */ @Composable private fun OpenChatStrip( state: ChatState, onSelect: (String) -> Unit, onClose: (String) -> Unit, + excludeSessionId: String? = null, ) { + val threads = if (excludeSessionId == null) { + state.open + } else { + openChatsBeside(state.open, excludeSessionId) + } + if (threads.isEmpty()) return Row( modifier = Modifier .fillMaxWidth() @@ -744,7 +768,7 @@ private fun OpenChatStrip( .padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), ) { - state.open.forEach { thread -> + threads.forEach { thread -> val selected = state.activeId == thread.sessionId Surface( shape = RoundedCornerShape(50), @@ -800,6 +824,41 @@ private fun OpenChatStrip( // ---- Pane 1: the active conversation ----------------------------------------- +/** + * The conversation's identity context, directly below the app bar that carries + * its title: the session kind (labelled, never a bare name), its activity and, + * when the server knows them, the directory and model. The title is not repeated + * here — this block adds only what the title cannot say. + */ +@Composable +private fun ConversationHeader(header: ConversationHeader) { + val texts = pipelinesText() + Column( + modifier = Modifier.fillMaxWidth().padding(horizontal = CHAT_GUTTER, vertical = CHAT_ITEM_GAP), + verticalArrangement = Arrangement.spacedBy(SPACING_XS), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + ) { + header.kind?.let { LabelChip(it, SPACING_S, SPACING_XXS) } + Text( + text = header.activity, + style = texts.label, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (header.context.isNotEmpty()) { + Text( + text = header.context.joinToString(" · "), + style = texts.meta, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } +} + @OptIn(ExperimentalMaterial3Api::class) @Composable private fun ChatConversationPane( @@ -810,6 +869,15 @@ private fun ChatConversationPane( ) { val approval = approvalCard(thread.permission, thread.permissionAnswer) val awaiting = approval?.actionable == true + // The header's one identity: the title, with the kind, activity, directory and + // model as context below it. It is built once so the app bar and the context + // line cannot disagree about the session's name. + val header = conversationHeader(thread) + // Reasoning expansion is hoisted here, not into the lazy transcript: a + // reasoning part keeps its open/closed state while the operator scrolls (and + // the item is disposed), and the state is per conversation, so a newly opened + // chat starts with every reasoning part collapsed. + var reasoning by remember(thread.sessionId) { mutableStateOf(ReasoningExpansion()) } // A turn blocked on an approval is not generating, so the running indicator // (and its ticking clock) stands down while the card is unanswered. val showRunning = thread.running && !awaiting @@ -851,11 +919,29 @@ private fun ChatConversationPane( topBar = { TopAppBar( title = { - Text( - text = thread.title.ifBlank { sessionTitle(ChatSession(id = thread.sessionId)) }, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) + // The one identity: the app bar carries the title (the value + // the context line below is built beside), and under it the + // model meta the server reports — its model, kind tag and + // directory — so what is answering is visible without leaving + // the conversation. Every part is server-reported; a blank one + // is simply omitted. + Column { + Text( + text = header.title, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + val meta = chatHeaderMeta(thread) + if (meta.isNotBlank()) { + Text( + text = meta, + style = pipelinesText().meta, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } }, navigationIcon = { IconButton(onClick = vm::showChatList) { @@ -889,7 +975,15 @@ private fun ChatConversationPane( }, ) { padding -> Column(Modifier.fillMaxSize().padding(padding).imePadding()) { - OpenChatStrip(state = state, onSelect = vm::activateChat, onClose = vm::closeChat) + ConversationHeader(header) + // Every *other* open chat is still one tap away; the active one is + // already named by the app bar, so it is not repeated here. + OpenChatStrip( + state = state, + onSelect = vm::activateChat, + onClose = vm::closeChat, + excludeSessionId = thread.sessionId, + ) Box(Modifier.weight(1f).fillMaxWidth()) { when { thread.loading && !thread.loaded -> LoadingState("Loading conversation…") @@ -911,6 +1005,8 @@ private fun ChatConversationPane( itemCount = itemCount, approval = approval, showRunning = showRunning, + reasoning = reasoning, + onToggleReasoning = { reasoning = reasoning.toggled(it) }, onDecision = { decision -> approval?.let { vm.replyChatPermission(thread.sessionId, it.requestId, decision) } }, @@ -961,6 +1057,8 @@ private fun ChatTranscript( itemCount: Int, approval: ApprovalCard?, showRunning: Boolean, + reasoning: ReasoningExpansion, + onToggleReasoning: (String) -> Unit, onDecision: (String) -> Unit, ) { val scope = rememberCoroutineScope() @@ -1043,6 +1141,9 @@ private fun ChatTranscript( if (following) listState.scrollToEnd(itemCount, animated = true) } Box(Modifier.fillMaxSize()) { + // Only the newest turn can be streaming, so its reasoning wears the live + // label; a settled turn's reasoning is labelled as settled. + val streamingMessageId = thread.messages.lastOrNull()?.id?.takeIf { thread.running } LazyColumn( state = listState, modifier = Modifier.fillMaxSize(), @@ -1050,7 +1151,12 @@ private fun ChatTranscript( verticalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP, Alignment.Bottom), ) { items(thread.messages, key = { it.id }) { message -> - MessageItem(message) + MessageItem( + message = message, + reasoning = reasoning, + streaming = message.id == streamingMessageId, + onToggleReasoning = onToggleReasoning, + ) } if (showRunning) { item(key = "pending") { RunningIndicator(thread) } @@ -1181,7 +1287,12 @@ private fun rememberElapsedNow(runningSince: Long): Long { } @Composable -private fun MessageItem(message: ChatMessage) { +private fun MessageItem( + message: ChatMessage, + reasoning: ReasoningExpansion, + streaming: Boolean, + onToggleReasoning: (String) -> Unit, +) { val isUser = message.role == ChatProtocol.ROLE_USER Row( modifier = Modifier.fillMaxWidth(), @@ -1201,7 +1312,13 @@ private fun MessageItem(message: ChatMessage) { if (isUser) { UserParts(message.parts) } else { - AssistantParts(message.parts) + AssistantParts( + messageId = message.id, + parts = message.parts, + reasoning = reasoning, + streaming = streaming, + onToggleReasoning = onToggleReasoning, + ) } } } @@ -1234,7 +1351,13 @@ private fun UserParts(parts: List) { * as they fit, instead of each taking a row, so the transcript stays scannable. */ @Composable -private fun AssistantParts(parts: List) { +private fun AssistantParts( + messageId: String, + parts: List, + reasoning: ReasoningExpansion, + streaming: Boolean, + onToggleReasoning: (String) -> Unit, +) { var index = 0 while (index < parts.size) { if (parts[index].type == ChatProtocol.PART_TOOL) { @@ -1243,42 +1366,101 @@ private fun AssistantParts(parts: List) { ToolCalls(parts.subList(index, end)) index = end } else { - MessagePart(parts[index]) + val part = parts[index] + MessagePart( + part = part, + reasoningKey = reasoningKey(messageId, part, index), + reasoning = reasoning, + streaming = streaming, + onToggleReasoning = onToggleReasoning, + ) index++ } } } @Composable -private fun MessagePart(part: ChatPart) { - when (part.type) { - ChatProtocol.PART_TEXT -> if (part.text.isNotBlank()) { - MarkdownText(part.text) - } - ChatProtocol.PART_REASONING -> ReasoningBlock(part.text) - else -> if (part.text.isNotBlank()) Text(part.text, style = MaterialTheme.typography.bodyMedium) +private fun MessagePart( + part: ChatPart, + reasoningKey: String, + reasoning: ReasoningExpansion, + streaming: Boolean, + onToggleReasoning: (String) -> Unit, +) { + when (partRendering(part)) { + PartRendering.MARKDOWN -> MarkdownText(part.text) + PartRendering.REASONING -> ReasoningBlock( + text = part.text, + expanded = reasoning.isExpanded(reasoningKey), + streaming = streaming, + onToggle = { onToggleReasoning(reasoningKey) }, + ) + PartRendering.PLAIN -> Text(part.text, style = MaterialTheme.typography.bodyMedium) + PartRendering.HIDDEN -> Unit } } -/** Reasoning is visually secondary: a muted, bordered block, never body weight. */ +/** + * Reasoning is visually secondary and collapsed by default: one compact, muted + * line per part (its spinner-free label names the state; the live label is + * `Thinking…`) that expands on tap to the full, still-muted text. The expansion + * state lives on the conversation, so it survives the transcript disposing the + * item while the operator scrolls and a streaming part keeps its state as + * deltas arrive. + */ @Composable -private fun ReasoningBlock(text: String) { +private fun ReasoningBlock( + text: String, + expanded: Boolean, + streaming: Boolean, + onToggle: () -> Unit, +) { 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, - ) + val label = if (streaming) REASONING_STREAMING_LABEL else REASONING_SETTLED_LABEL + Column(Modifier.fillMaxWidth()) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(CHAT_ITEM_GAP), + modifier = Modifier + .fillMaxWidth() + .minimumInteractiveComponentSize() + .clickable(role = Role.Button, onClick = onToggle) + .padding(vertical = SPACING_XS), + ) { + Icon( + Icons.Default.Psychology, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ICON_INLINE_DP), + ) + Text( + text = label, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + Icon( + imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = if (expanded) "Hide reasoning" else "Show reasoning", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(ICON_INLINE_DP), + ) + } + if (expanded) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Default), + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = ICON_INLINE_DP + CHAT_ITEM_GAP, bottom = CHAT_ITEM_GAP), + ) + } } } +/** The live and settled labels of a reasoning part's one collapsed line. */ +private const val REASONING_STREAMING_LABEL = "Thinking…" +private const val REASONING_SETTLED_LABEL = "Reasoning" + /** * One turn's tool calls as a single group of compact chips, mirroring the * reference transcript's `_ToolCalls`/`_ToolChip` (research §1.3): each call diff --git a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt index 4a094e28..a3d80f75 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/chat/ChatStore.kt @@ -51,6 +51,8 @@ data class ChatThread( val title: String = "", val directory: String = "", val model: String = "", + /** The session's kind tag the server reported (see [ChatSession.tag]). */ + val tag: String = "", val agent: String = "", val updatedAt: Long = 0, /** The server reports another client (or an active run) holds this session. */ @@ -298,6 +300,9 @@ class ChatStore( thread.copy( title = renamed[thread.sessionId] ?: session.title.ifBlank { thread.title }, directory = session.directory.ifBlank { thread.directory }, + model = session.model.ifBlank { thread.model }, + agent = session.agent.ifBlank { thread.agent }, + tag = session.tag.ifBlank { thread.tag }, busy = session.busy, ) } @@ -445,6 +450,7 @@ class ChatStore( title = title, directory = session.directory, model = session.model, + tag = session.tag, agent = session.agent, updatedAt = session.updatedAt, busy = session.busy, @@ -455,6 +461,9 @@ class ChatStore( val merged = existing.copy( title = title.ifBlank { existing.title }, directory = session.directory.ifBlank { existing.directory }, + model = session.model.ifBlank { existing.model }, + agent = session.agent.ifBlank { existing.agent }, + tag = session.tag.ifBlank { existing.tag }, busy = session.busy, ) _state.value = _state.value.copy( @@ -720,6 +729,9 @@ class ChatStore( sessionId = sessionId, title = _state.value.overrides.titles[sessionId] ?: session?.title ?: "", directory = session?.directory ?: "", + model = session?.model ?: "", + agent = session?.agent ?: "", + tag = session?.tag ?: "", busy = session?.busy ?: false, ) _state.value = _state.value.copy(open = _state.value.open + placeholder) diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt new file mode 100644 index 00000000..89d8a647 --- /dev/null +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt @@ -0,0 +1,253 @@ +package net.awan.pipelines.ui.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.FrontHand +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +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.semantics.Role +import androidx.compose.ui.text.style.TextOverflow +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.ui.DecisionDraft +import net.awan.pipelines.ui.DecisionOption +import net.awan.pipelines.ui.PendingDecision +import net.awan.pipelines.ui.decisionRefusalMessage +import net.awan.pipelines.ui.theme.SPACING_L +import net.awan.pipelines.ui.theme.SPACING_M +import net.awan.pipelines.ui.theme.SPACING_S +import net.awan.pipelines.ui.theme.SPACING_XL +import net.awan.pipelines.ui.theme.SPACING_XS +import net.awan.pipelines.ui.theme.SPACING_XXS +import net.awan.pipelines.ui.theme.pipelinesText + +/** + * The one place a run's pending human decision is surfaced: a prominent card + * ("Waiting for your decision") with a deliberate Decide action, plus the + * decision sheet it opens. It is rendered by the run detail and by the stage + * pane of the waiting stage, so the decision is reachable exactly where the + * operator already is rather than buried in a submenu; an attention surface can + * render the same component. + * + * [decision] is nullable because the host outlives it: when a decision is + * refused and the run has moved on, the refreshed run no longer carries a + * decision, but the already-open sheet is kept — with the server's own reason — + * until the operator dismisses it, instead of vanishing mid-report. + * + * [onSend] performs the request; it reports the outcome through its callback so + * this component owns no networking and is unit-testable through the pure + * [DecisionDraft]/[decisionRefusalMessage] model. + */ +@Composable +fun DecisionPrompt( + decision: PendingDecision?, + onSend: (decision: PendingDecision, option: String, feedback: String, onResult: (Result) -> Unit) -> Unit, + modifier: Modifier = Modifier, +) { + val shown = rememberPaneContent(decision) + var open by remember { mutableStateOf(false) } + var draft by remember(shown?.runId, shown?.stageKey) { mutableStateOf(DecisionDraft()) } + var sending by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + + if (decision != null) { + DecisionCard( + decision = decision, + onOpen = { + error = null + open = true + }, + modifier = modifier, + ) + } + if (open && shown != null) { + DecisionSheet( + decision = shown, + draft = draft, + sending = sending, + error = error, + onDraftChange = { draft = it }, + onDismiss = { + if (!sending) { + open = false + error = null + } + }, + onConfirm = { option -> + sending = true + error = null + onSend(shown, option.key, draft.feedback) { result -> + sending = false + result.onSuccess { open = false } + result.onFailure { error = decisionRefusalMessage(it) } + } + }, + ) + } +} + +/** The waiting-for-decision banner: the run, the stage and the deliberate action. */ +@Composable +private fun DecisionCard( + decision: PendingDecision, + onOpen: () -> Unit, + modifier: Modifier = Modifier, +) { + val text = pipelinesText() + val scheme = MaterialTheme.colorScheme + Surface(modifier = modifier.fillMaxWidth(), color = scheme.secondaryContainer) { + Row( + modifier = Modifier.fillMaxWidth().padding(SPACING_L), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_M), + ) { + Icon( + imageVector = Icons.Default.FrontHand, + contentDescription = null, + tint = scheme.onSecondaryContainer, + ) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(SPACING_XXS), + ) { + Text( + "Waiting for your decision", + style = text.cardTitle, + color = scheme.onSecondaryContainer, + ) + Text( + "${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}", + style = text.meta, + color = scheme.onSecondaryContainer, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Button(onClick = onOpen) { Text("Decide") } + } + } +} + +/** + * The decision sheet: the run and the waiting stage, the author's recorded + * instructions, their options exactly as written (each with what it routes to), + * an optional feedback field and a deliberate confirm. Selecting an option only + * selects it; nothing is sent until Confirm decision is pressed, so a stray tap + * can never answer for the operator. A refusal keeps the sheet open and shows + * the server's exact reason. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun DecisionSheet( + decision: PendingDecision, + draft: DecisionDraft, + sending: Boolean, + error: String?, + onDraftChange: (DecisionDraft) -> Unit, + onDismiss: () -> Unit, + onConfirm: (DecisionOption) -> Unit, +) { + val text = pipelinesText() + val scheme = MaterialTheme.colorScheme + val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) + ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(horizontal = SPACING_L) + .padding(bottom = SPACING_XL), + verticalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + Text("Decide ${decision.stageKey}", style = text.screenTitle) + Text("run ${decision.runId} · ${decision.runLabel}", style = text.meta) + if (decision.instructions.isNotBlank()) { + Text(decision.instructions, style = text.body) + } + decision.options.forEach { option -> + DecisionOptionRow( + option = option, + selected = draft.selected == option.key, + onSelect = { onDraftChange(draft.select(option.key)) }, + ) + } + OutlinedTextField( + value = draft.feedback, + onValueChange = { onDraftChange(draft.withFeedback(it)) }, + label = { Text("Feedback (optional)") }, + modifier = Modifier.fillMaxWidth(), + ) + if (error != null) { + Text(error, color = scheme.error, style = text.body) + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(SPACING_S, Alignment.End), + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton(onClick = onDismiss, enabled = !sending) { Text("Cancel") } + Button( + onClick = { decision.options.firstOrNull { it.key == draft.selected }?.let(onConfirm) }, + enabled = draft.canSubmit && !sending, + ) { + Text(if (sending) "Sending…" else "Confirm decision") + } + } + } + } +} + +/** + * One selectable option row: a radio target carrying the author's option key and, + * when the graph declares it, the label it routes to. Tapping selects; it never + * answers. + */ +@Composable +private fun DecisionOptionRow( + option: DecisionOption, + selected: Boolean, + onSelect: () -> Unit, +) { + val text = pipelinesText() + Row( + modifier = Modifier + .fillMaxWidth() + .selectable(selected = selected, role = Role.RadioButton, onClick = onSelect) + .padding(vertical = SPACING_XS), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(SPACING_S), + ) { + RadioButton(selected = selected, onClick = null) + Column( + modifier = Modifier.weight(1f), + verticalArrangement = Arrangement.spacedBy(SPACING_XXS), + ) { + Text(option.key, style = text.cardTitle) + if (option.target.isNotBlank()) { + Text("→ ${option.target}", style = text.meta) + } + } + } +} diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt index 443e8eee..4b3d54fd 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatus.kt @@ -14,6 +14,7 @@ import androidx.compose.material.icons.filled.Bolt import androidx.compose.material.icons.filled.Cancel import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.Error +import androidx.compose.material.icons.filled.FrontHand import androidx.compose.material.icons.filled.PauseCircle import androidx.compose.material.icons.filled.Schedule import androidx.compose.material3.Icon @@ -42,6 +43,7 @@ import net.awan.pipelines.ui.theme.pipelinesText enum class RunState(val label: String) { Running("running"), Queued("queued"), + Waiting("waiting"), Succeeded("succeeded"), Failed("failed"), Canceled("canceled"), @@ -59,6 +61,7 @@ enum class RunState(val label: String) { fun runStateOf(status: String): RunState = when (status.trim().lowercase()) { "running" -> RunState.Running "queued" -> RunState.Queued + "waiting" -> RunState.Waiting "active" -> RunState.Active "succeeded", "success", "completed", "done" -> RunState.Succeeded "failed", "error" -> RunState.Failed @@ -78,6 +81,7 @@ fun runStateColor(state: RunState): Color = RunStatusPalette.of(state).color fun runStateIcon(state: RunState): ImageVector = when (state) { RunState.Running -> Icons.AutoMirrored.Filled.DirectionsRun RunState.Queued -> Icons.Default.Schedule + RunState.Waiting -> Icons.Default.FrontHand RunState.Succeeded -> Icons.Default.CheckCircle RunState.Failed -> Icons.Default.Error RunState.Canceled -> Icons.Default.Cancel diff --git a/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatusPalette.kt b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatusPalette.kt index 5c6d973b..418d4760 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatusPalette.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/components/RunStatusPalette.kt @@ -49,6 +49,13 @@ internal object RunStatusPalette { private val Queued = Entry(Color(0xFF9AA6A2), "neutral grey: waiting, clearly not the in-progress blue") + /** + * Parked on a person: violet, distinct from the in-progress blue, the queued + * grey and the amber operator-stop, so a run needing a decision is unmistakable. + */ + private val Waiting = + Entry(Color(0xFFC0A3F5), "violet: parked for the operator's decision; not running, not a stop") + /** Unknown/blank status: the safe, low-key fallback. */ private val Unknown = Entry(Color(0xFFBEC9C5), "neutral surface grey: an unrecognised status stays low-key") @@ -65,6 +72,7 @@ internal object RunStatusPalette { RunState.Interrupted -> Interrupted RunState.Canceled -> Canceled RunState.Queued -> Queued + RunState.Waiting -> Waiting RunState.Unknown -> Unknown } } diff --git a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt index 6af92d25..838a5cbb 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/graph/StageDetailPane.kt @@ -37,21 +37,26 @@ import net.awan.pipelines.data.protocol.ControlEvidence import net.awan.pipelines.data.protocol.Graph import net.awan.pipelines.data.protocol.GraphSemantics import net.awan.pipelines.data.protocol.Protocol +import net.awan.pipelines.data.protocol.RunDetail import net.awan.pipelines.data.protocol.RunStep import net.awan.pipelines.data.protocol.Stage import net.awan.pipelines.data.protocol.edges import net.awan.pipelines.ui.AppViewModel +import net.awan.pipelines.ui.PendingDecision import net.awan.pipelines.ui.components.CodeBlock +import net.awan.pipelines.ui.components.DecisionPrompt import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.KeyValueRow import net.awan.pipelines.ui.components.PaneIdentity import net.awan.pipelines.ui.components.SectionHeader import net.awan.pipelines.ui.components.paneSafeArea +import net.awan.pipelines.ui.STAGE_RUN_LABEL_LINES import net.awan.pipelines.ui.displayMap import net.awan.pipelines.ui.fileChangeLine import net.awan.pipelines.ui.fileChangesSummary import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.notificationLine +import net.awan.pipelines.ui.pendingDecision import net.awan.pipelines.ui.runLabel import net.awan.pipelines.ui.screens.runTimeline import net.awan.pipelines.ui.theme.SPACING_L @@ -389,6 +394,8 @@ fun StageDetailPane( covered: Boolean = false, runContext: Boolean = false, runLabel: String? = null, + decision: PendingDecision? = null, + onDecide: (PendingDecision, String, String, (Result) -> Unit) -> Unit = { _, _, _, _ -> }, ) { // A covered pane shows its compact identity only; the visit tab row and the // stage body must never be drawn squeezed into the peek strip. @@ -422,7 +429,10 @@ fun StageDetailPane( Text( label, style = pipelinesText().meta, - maxLines = 1, + // The run's own complete title lives in the run + // view; here it is a compact context line, so it may + // take a second line but not run away with the pane. + maxLines = STAGE_RUN_LABEL_LINES, overflow = TextOverflow.Ellipsis, ) } @@ -449,6 +459,8 @@ fun StageDetailPane( fetchArtifactBytes = fetchArtifactBytes, wide = wide, runContext = runContext, + decision = decision, + onDecide = onDecide, modifier = Modifier.padding(padding), ) } @@ -467,6 +479,8 @@ private fun StageDetailBody( fetchArtifactBytes: suspend (String) -> ByteArray?, wide: Boolean, runContext: Boolean, + decision: PendingDecision?, + onDecide: (PendingDecision, String, String, (Result) -> Unit) -> Unit, modifier: Modifier = Modifier, ) { val text = pipelinesText() @@ -490,6 +504,11 @@ private fun StageDetailBody( .padding(horizontal = SPACING_L, vertical = SPACING_S), verticalArrangement = Arrangement.spacedBy(SPACING_XS), ) { + // A run parked on this stage surfaces its decision here, at the top of + // the stage screen: reaching the stage is enough. Rendered + // unconditionally so the open sheet survives a refusal (which clears the + // decision) and can report the server's reason. + DecisionPrompt(decision = decision, onSend = onDecide) Text( GraphSemantics.nodeLabel(stageKey), style = text.screenTitle, @@ -754,6 +773,12 @@ fun RunStagePane( val timeline = remember(steps) { runTimeline(steps) } val runSteps = remember(timeline, stageKey) { timeline.visitsByStage[stageKey].orEmpty() } val graph = run?.graph ?: Graph() + // The run's pending decision, but only when it is this stage that is waiting: + // the run detail already surfaces it for the whole run, and a stage pane for + // another stage should not offer someone else's gate. + val decision = remember(run, stageKey) { + pendingDecision(run)?.takeIf { it.stageKey == stageKey } + } if (openSection == null) { StageDetailPane( stageKey = stageKey, @@ -770,6 +795,10 @@ fun RunStagePane( covered = covered, runContext = true, runLabel = run?.let { runLabel(it.title, it.name) }, + decision = decision, + onDecide = { pending, option, feedback, onResult -> + vm.decideRun(pending.runId, pending.stageKey, option, feedback, onResult) + }, ) } else { StageSectionPane( diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt index c98f40ca..adc2d623 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunDetailScreen.kt @@ -55,6 +55,7 @@ import net.awan.pipelines.ui.ArtifactGroup import net.awan.pipelines.ui.LoadState import net.awan.pipelines.ui.components.CodeBlock import net.awan.pipelines.ui.components.ColoredChip +import net.awan.pipelines.ui.components.DecisionPrompt import net.awan.pipelines.ui.components.DetailTabBody import net.awan.pipelines.ui.components.DetailTabs import net.awan.pipelines.ui.components.ErrorState @@ -77,6 +78,7 @@ import net.awan.pipelines.ui.components.runDetailTabs import net.awan.pipelines.ui.components.runStateIcon import net.awan.pipelines.ui.components.runStateOf import net.awan.pipelines.ui.displayText +import net.awan.pipelines.ui.pendingDecision import net.awan.pipelines.ui.runDurationText import net.awan.pipelines.ui.graph.ArtifactGallery import net.awan.pipelines.ui.graph.ArtifactSelection @@ -89,6 +91,7 @@ import net.awan.pipelines.ui.runArtifactGroups import net.awan.pipelines.ui.runArtifactsHeader import net.awan.pipelines.ui.runIdentity import net.awan.pipelines.ui.runLabel +import net.awan.pipelines.ui.RUN_VIEW_TITLE_LINES import net.awan.pipelines.ui.theme.ICON_INLINE_DP import net.awan.pipelines.ui.theme.ICON_STATUS_DP import net.awan.pipelines.ui.theme.SPACING_L @@ -193,7 +196,11 @@ fun RunDetailScreen( // The header names the run by its title and keeps the pipeline // it belongs to on a second line, so a stage pane opened from // here carries the same context. Without a title the pipeline - // name is the single identity, never a blank first line. + // name is the single identity, never a blank first line. This + // app-bar copy is a compact one-line label (the M3 app bar is a + // fixed height, so it cannot grow); the run's own complete, + // wrapping title is the summary's title line below, which is + // never elided. val identity = run?.let { runIdentity(it.title, it.name) } Column { Text( @@ -236,69 +243,85 @@ fun RunDetailScreen( ) }, ) { selection, onSelectionChange, padding -> - StateCrossfade( - phase = detailLoadPhase(state.error, hasData = run != null), - modifier = Modifier.fillMaxSize(), - ) { phase -> - when (phase) { - is LoadPhase.Error -> ErrorState( - phase.message, - onRetry = { vm.loadRun(runId) }, - modifier = Modifier.padding(padding), - ) - LoadPhase.Loading -> LoadingState("Loading run…", Modifier.padding(padding)) - else -> if (shownRun != null) { - DetailTabs( - tabs = runDetailTabs, - selectedIndex = selectedSection, - onSelect = onSelectSection, - wide = wide, - modifier = Modifier.padding(padding).fillMaxSize(), - ) { tab, contentModifier -> - // Only the selected section's content is composed at rest. - when (tab.key) { - "summary" -> RunSummaryTab( - run = shownRun, - wide = wide, - modifier = contentModifier, - configuredServerUrl = configuredServerUrl, - fetchArtifactBytes = vm::fetchArtifactBytes, - artifactGroups = artifactGroups, - selection = selection, - onSelectionChange = onSelectionChange, - ) - "graph" -> RunGraphTab( - run = shownRun, - modifier = contentModifier, - onStageTap = onOpenStage, - ) - "input" -> RunFieldSectionsTab( - emptyMessage = "No input recorded.", - keyPrefix = "input", - entries = shownRun.input.orEmpty().toList(), - wide = wide, - modifier = contentModifier, - ) - "output" -> RunFieldSectionsTab( - emptyMessage = "No output recorded.", - keyPrefix = "output", - entries = shownRun.output.orEmpty().toList(), - wide = wide, - modifier = contentModifier, - ) - "evidence" -> RunEvidenceTab( - evidenceState = evidenceState, - steps = shownRun.steps, - onLoadEvidence = { vm.loadEvidence(runId) }, - wide = wide, - modifier = contentModifier, - ) - else -> RunTimelineTab( - run = shownRun, - wide = wide, - modifier = contentModifier, - onStageTap = onOpenStage, - ) + Column(Modifier.fillMaxSize().padding(padding)) { + // A run parked on a person surfaces its decision here, above the tabs, + // wherever in the run detail the operator is: opening the run is enough, + // no tab hunt. Derived from the run actually loaded (never the retained + // outgoing one), so a decision is never offered for a run the operator + // has navigated away from. The prompt owns the sheet and the refusal + // report; the callback is the one decide request. + val decision = remember(run) { pendingDecision(run) } + DecisionPrompt( + decision = decision, + onSend = { pending, option, feedback, onResult -> + vm.decideRun(pending.runId, pending.stageKey, option, feedback, onResult) + }, + modifier = Modifier.padding(horizontal = SPACING_L, vertical = SPACING_S), + ) + StateCrossfade( + phase = detailLoadPhase(state.error, hasData = run != null), + modifier = Modifier.weight(1f).fillMaxWidth(), + ) { phase -> + when (phase) { + is LoadPhase.Error -> ErrorState( + phase.message, + onRetry = { vm.loadRun(runId) }, + modifier = Modifier.fillMaxSize(), + ) + LoadPhase.Loading -> LoadingState("Loading run…", Modifier.fillMaxSize()) + else -> if (shownRun != null) { + DetailTabs( + tabs = runDetailTabs, + selectedIndex = selectedSection, + onSelect = onSelectSection, + wide = wide, + modifier = Modifier.fillMaxSize(), + ) { tab, contentModifier -> + // Only the selected section's content is composed at rest. + when (tab.key) { + "summary" -> RunSummaryTab( + run = shownRun, + wide = wide, + modifier = contentModifier, + configuredServerUrl = configuredServerUrl, + fetchArtifactBytes = vm::fetchArtifactBytes, + artifactGroups = artifactGroups, + selection = selection, + onSelectionChange = onSelectionChange, + ) + "graph" -> RunGraphTab( + run = shownRun, + modifier = contentModifier, + onStageTap = onOpenStage, + ) + "input" -> RunFieldSectionsTab( + emptyMessage = "No input recorded.", + keyPrefix = "input", + entries = shownRun.input.orEmpty().toList(), + wide = wide, + modifier = contentModifier, + ) + "output" -> RunFieldSectionsTab( + emptyMessage = "No output recorded.", + keyPrefix = "output", + entries = shownRun.output.orEmpty().toList(), + wide = wide, + modifier = contentModifier, + ) + "evidence" -> RunEvidenceTab( + evidenceState = evidenceState, + steps = shownRun.steps, + onLoadEvidence = { vm.loadEvidence(runId) }, + wide = wide, + modifier = contentModifier, + ) + else -> RunTimelineTab( + run = shownRun, + wide = wide, + modifier = contentModifier, + onStageTap = onOpenStage, + ) + } } } } @@ -429,7 +452,17 @@ private fun RunSummaryTab( modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L), verticalArrangement = Arrangement.spacedBy(SPACING_XS), ) { - Text(runLabel(run.title, run.name), style = text.screenTitle) + // The run view's own copy of the title: the operator must be + // able to read what the run is called, so it is never elided - + // it wraps over as many lines as it needs. The compact app-bar + // copy above stays a one-line label for context while this + // scrollable, complete one is what the operator reads. + Text( + runLabel(run.title, run.name), + style = text.screenTitle, + maxLines = RUN_VIEW_TITLE_LINES, + overflow = TextOverflow.Clip, + ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(SPACING_S), diff --git a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt index 4cd57055..40b39c62 100644 --- a/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt +++ b/android/app/src/main/java/net/awan/pipelines/ui/screens/RunHistoryScreen.kt @@ -70,6 +70,7 @@ import net.awan.pipelines.ui.components.paneSafeArea import net.awan.pipelines.ui.components.rememberLiveNowMillis import net.awan.pipelines.ui.components.runStateColor import net.awan.pipelines.ui.components.runStateOf +import net.awan.pipelines.ui.RUN_ROW_TITLE_LINES import net.awan.pipelines.ui.formatDuration import net.awan.pipelines.ui.runDurationText import net.awan.pipelines.ui.runIdentity @@ -529,7 +530,7 @@ private fun RunRow( Text( identity.label, style = text.cardTitle, - maxLines = 1, + maxLines = RUN_ROW_TITLE_LINES, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), ) diff --git a/android/app/src/test/java/net/awan/pipelines/data/protocol/HumanDecisionTest.kt b/android/app/src/test/java/net/awan/pipelines/data/protocol/HumanDecisionTest.kt new file mode 100644 index 00000000..a2b366ac --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/data/protocol/HumanDecisionTest.kt @@ -0,0 +1,112 @@ +package net.awan.pipelines.data.protocol + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.jsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The phone's read side of a waiting human stage, against the exact wire keys + * `internal/protocol/runs.go` writes: the recorded options/instructions + * (`protocol.WaitingOptions`/`WaitingPrompt`), the non-error-edge fallback + * (`stage.HumanOptions`), the last waiting step (`tui.lastWaitingStep`) and the + * `decide_run` request envelope. Pure, so the decision parsing is pinned without + * a device or a socket. + */ +class HumanDecisionTest { + + private fun output(json: String): Map = + Json.parseToJsonElement(json).jsonObject + + private fun step( + sequence: Int = 1, + stage: String = "gate", + status: String = "waiting", + outputJson: String? = null, + ) = RunStep( + sequence = sequence, + stage = stage, + status = status, + output = outputJson?.let { output(it) }, + ) + + @Test + fun waitingEvidenceReadsTheAuthorsOptionsAndInstructions() { + val evidence = output("""{"prompt":"Choose where it goes.","options":["deploy","revise","abort"]}""") + assertEquals("Choose where it goes.", waitingPrompt(evidence)) + assertEquals(listOf("deploy", "revise", "abort"), waitingOptions(evidence)) + } + + @Test + fun waitingEvidenceToleratesAbsentAndMalformedEntries() { + assertEquals("", waitingPrompt(null)) + assertEquals(emptyList(), waitingOptions(null)) + assertEquals(emptyList(), waitingOptions(output("""{"prompt":""}"""))) + // A non-string option is dropped, exactly like protocol.WaitingOptions. + assertEquals( + listOf("deploy", "abort"), + waitingOptions(output("""{"options":["deploy",3,{"key":"x"},"abort"]}""")), + ) + } + + @Test + fun humanOptionsAreTheSortedNonErrorEdges() { + val edges = mapOf( + "revise" to "worker", + "deploy" to "#success", + "abort" to "#failure", + "error" to "#failure", + ) + assertEquals(listOf("abort", "deploy", "revise"), humanOptions(edges)) + assertEquals(emptyList(), humanOptions(mapOf("error" to "#failure"))) + } + + @Test + fun theLastWaitingStepWinsAndNothingElseMatches() { + val steps = listOf( + step(sequence = 1, stage = "plan", status = "completed"), + step(sequence = 2, stage = "gate", status = "waiting"), + step(sequence = 3, stage = "gate", status = "waiting"), + step(sequence = 4, stage = "after", status = "running"), + ) + assertEquals(3, lastWaitingStep(steps)?.sequence) + assertNull(lastWaitingStep(emptyList())) + assertNull(lastWaitingStep(listOf(step(status = "completed")))) + } + + @Test + fun theDecideRequestCarriesStageOptionAndFeedbackWithTheWireNames() { + val encoded = PipelinesJson.encodeToString( + Message.serializer(), + Message( + type = Protocol.DECIDE_RUN, + id = "cli-1", + runId = 42, + stage = "gate", + option = "go", + feedback = "looks good", + ), + ) + val decoded = PipelinesJson.decodeFromString(Message.serializer(), encoded) + assertEquals(Protocol.DECIDE_RUN, decoded.type) + assertEquals(42L, decoded.runId) + assertEquals("gate", decoded.stage) + assertEquals("go", decoded.option) + assertEquals("looks good", decoded.feedback) + assertTrue("run_id is the exact wire name", encoded.contains("\"run_id\":42")) + } + + @Test + fun anAbsentStageOrFeedbackIsOmittedSoTheServerCanInferOrSkipThem() { + val encoded = PipelinesJson.encodeToString( + Message.serializer(), + Message(type = Protocol.DECIDE_RUN, runId = 7, option = "go"), + ) + assertTrue(!encoded.contains("\"stage\"")) + assertTrue(!encoded.contains("\"feedback\"")) + assertEquals("go", PipelinesJson.decodeFromString(Message.serializer(), encoded).option) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/DecisionTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/DecisionTest.kt new file mode 100644 index 00000000..8c994537 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/DecisionTest.kt @@ -0,0 +1,143 @@ +package net.awan.pipelines.ui + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.jsonObject +import net.awan.pipelines.data.protocol.Graph +import net.awan.pipelines.data.protocol.RUN_STATUS_WAITING +import net.awan.pipelines.data.protocol.RunDetail +import net.awan.pipelines.data.protocol.RunStep +import net.awan.pipelines.data.protocol.Stage +import net.awan.pipelines.data.transport.ProtocolException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The decision sheet's pure model: the pending decision read from a waiting run, + * the author's options with what they route to, the deliberate-confirm rule and + * the verbatim refusal message. No Compose runtime, so the sheet's contract is + * pinned as a plain JVM test (the rendering itself is exercised on a device). + */ +class DecisionTest { + + private fun output(json: String): Map = + Json.parseToJsonElement(json).jsonObject + + private fun waitingRun( + status: String = RUN_STATUS_WAITING, + currentStage: String = "gate", + stepOutput: String? = """{"prompt":"Review the screenshots, then choose.","options":["deploy","revise","abort"]}""", + graphPrompt: String = "Review and choose where the run goes.", + edges: Map = mapOf( + "deploy" to "#success", + "revise" to "worker", + "abort" to "#failure", + "error" to "#failure", + ), + steps: List = listOf( + RunStep( + sequence = 1, + stage = "gate", + status = "waiting", + output = stepOutput?.let { output(it) }, + ), + ), + ): RunDetail = RunDetail( + id = 42, + pipelineId = 7, + name = "demo", + title = "Ship the release", + status = status, + currentStage = currentStage, + graph = Graph( + stages = listOf( + Stage(key = "gate", type = "human", prompt = graphPrompt, edges = edges), + ), + ), + steps = steps, + ) + + @Test + fun aWaitingRunYieldsItsStageOptionsAndInstructions() { + val decision = pendingDecision(waitingRun())!! + assertEquals(42L, decision.runId) + assertEquals("Ship the release", decision.runLabel) + assertEquals("gate", decision.stageKey) + assertEquals("Review the screenshots, then choose.", decision.instructions) + // The author's options exactly, in recorded order, each with the label it + // routes to (the author wrote `deploy -> #success`). + assertEquals( + listOf( + DecisionOption("deploy", "SUCCESS"), + DecisionOption("revise", "worker"), + DecisionOption("abort", "FAILURE"), + ), + decision.options, + ) + assertEquals(listOf("deploy", "revise", "abort"), decision.optionKeys) + } + + @Test + fun aNonWaitingRunHasNoDecision() { + assertNull(pendingDecision(null)) + assertNull(pendingDecision(waitingRun(status = "running"))) + assertNull(pendingDecision(waitingRun(status = "succeeded"))) + } + + @Test + fun theRecordedEvidenceWinsButThePinnedGraphIsTheFallback() { + // A step that recorded no options still answers from the declared edges. + val fallback = pendingDecision( + waitingRun(stepOutput = """{"prompt":"Choose."}"""), + )!! + assertEquals(listOf("abort", "deploy", "revise"), fallback.optionKeys) + assertEquals("Choose.", fallback.instructions) + + // With neither recorded options nor declared edges there is nothing to offer. + assertNull(pendingDecision(waitingRun(stepOutput = null, edges = mapOf("error" to "#failure")))) + } + + @Test + fun theInstructionsFallBackToTheStagePromptWhenTheStepRecordedNone() { + val decision = pendingDecision( + waitingRun(stepOutput = """{"options":["deploy"]}"""), + )!! + assertEquals("Review and choose where the run goes.", decision.instructions) + } + + @Test + fun theStageIsInferredFromTheRunWhenNoStepRecordedIt() { + val decision = pendingDecision( + waitingRun( + currentStage = "gate", + steps = listOf(RunStep(sequence = 1, stage = "", status = "waiting")), + stepOutput = null, + ), + )!! + assertEquals("gate", decision.stageKey) + } + + @Test + fun aDecisionIsOnlySubmittableOnceAnOptionIsChosen() { + // Nothing selected: not sendable, and feedback alone never changes that, + // so a stray tap on the field can never answer for the operator. + assertFalse(DecisionDraft().canSubmit) + assertFalse(DecisionDraft(feedback = "ship it").canSubmit) + // Selecting only enables the confirm; it does not answer. + assertTrue(DecisionDraft().select("deploy").canSubmit) + // Feedback is optional and carried verbatim. + val draft = DecisionDraft().select("deploy").withFeedback("looks good") + assertEquals("deploy", draft.selected) + assertEquals("looks good", draft.feedback) + assertTrue(draft.canSubmit) + } + + @Test + fun aRefusalReportsTheServersOwnReason() { + val refused = ProtocolException("run 42 is not waiting (state running)") + assertEquals("run 42 is not waiting (state running)", decisionRefusalMessage(refused)) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt index 560af136..422e91d3 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/RunEventsTest.kt @@ -304,11 +304,15 @@ class RunEventsTest { // --- sync heuristic --------------------------------------------------------- @Test - fun onlySettledVisitsAndTerminalRunsNeedAFullDetailSync() { + fun settledVisitsTerminalRunsAndPendingDecisionsNeedAFullDetailSync() { assertTrue(runDetailNeedsFullSync(frame(runId = 1, step = RunStepDelta(sequence = 1, status = "completed")))) assertTrue(runDetailNeedsFullSync(frame(runId = 1, step = RunStepDelta(sequence = 1, status = "failed")))) assertTrue(runDetailNeedsFullSync(frame(runId = 1, status = "succeeded"))) assertTrue(runDetailNeedsFullSync(frame(runId = 1, status = "canceled"))) + // A pending human decision lives in the waiting step's output, which the + // compact delta omits, so the full detail must be fetched to surface it. + assertTrue(runDetailNeedsFullSync(frame(runId = 1, status = "waiting"))) + assertTrue(runDetailNeedsFullSync(frame(runId = 1, step = RunStepDelta(sequence = 1, status = "waiting")))) assertFalse(runDetailNeedsFullSync(frame(runId = 1, status = "running", step = RunStepDelta(sequence = 1, status = "running")))) assertFalse(runDetailNeedsFullSync(frame(runId = 1, status = "queued"))) } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt index cfd1e135..53fcfba9 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/RunIdentityTest.kt @@ -47,4 +47,16 @@ class RunIdentityTest { assertEquals("android-app", runLabel(null, "android-app")) assertEquals("android-app", runLabel(" ", "android-app")) } + + @Test + fun aVeryLongTitleIsKeptWholeAtTheDataLevel() { + // The run view's own title is rendered from this value with no line limit, + // so the identity itself must never silently shorten it: a prompt-derived + // title stays complete and the view, not this function, decides the + // layout. Guards against re-introducing a truncating helper here. + val long = "Implement the whole thing carefully, then review it ".repeat(40).trim() + assertEquals(long, runLabel(long, "android-app")) + assertEquals(long, runIdentity(long, "android-app").label) + assertEquals("android-app", runIdentity(long, "android-app").pipeline) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/RunTitlesTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/RunTitlesTest.kt new file mode 100644 index 00000000..f49f18b9 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/RunTitlesTest.kt @@ -0,0 +1,38 @@ +package net.awan.pipelines.ui + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The run title's line budget in each place it is shown. A title is derived from + * the run's prompt and is often long, so the run view - the place whose whole job + * is to let the operator read the run - must show it complete, while the places + * that are one of many (a runs-list row) or a compact label (the stage pane's + * run-context line) clamp. The budgets are pinned here so a change to one is a + * deliberate, reviewed decision and the run view can never become the most + * generous place by accident. + */ +class RunTitlesTest { + + @Test + fun theRunViewShowsTheWholeTitleNeverEliding() { + assertEquals(Int.MAX_VALUE, RUN_VIEW_TITLE_LINES) + } + + @Test + fun aRunsListRowGrowsForALongTitleThenClampsAtTwoLines() { + assertEquals(2, RUN_ROW_TITLE_LINES) + } + + @Test + fun theStagePaneRunContextTakesASecondLineThenClamps() { + assertEquals(2, STAGE_RUN_LABEL_LINES) + } + + @Test + fun aClampingPlaceIsNeverMoreGenerousThanTheCompleteOne() { + assertTrue("a list row may not outlive the run view", RUN_ROW_TITLE_LINES < RUN_VIEW_TITLE_LINES) + assertTrue("a stage context line may not outlive the run view", STAGE_RUN_LABEL_LINES < RUN_VIEW_TITLE_LINES) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt index 381fed35..7991e473 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatFormatTest.kt @@ -152,4 +152,32 @@ class ChatFormatTest { assertEquals("Named", sessionTitle(ChatSession(id = "ses_1", title = "Named"))) assertEquals("ses_abcdefghijklmn", sessionTitle(ChatSession(id = "ses_abcdefghijklmnop"))) } + + @Test + fun chatHeaderMetaShowsTheReportedModelTagAndDirectory() { + // The conversation header names what is answering beside the session's + // kind tag and its directory, every part the server's own value. + val thread = ChatThread( + sessionId = "ses_1", + model = "deepseek-v4.1-flash", + tag = ChatProtocol.TAG_OPERATOR, + directory = "/home/op/work", + ) + assertEquals("deepseek-v4.1-flash · Operator · /home/op/work", chatHeaderMeta(thread)) + } + + @Test + fun chatHeaderMetaNeverClaimsAModelTheServerDidNotReport() { + // A session the server reported without a model (or an older server that + // omits the field) shows no model claim, never a guess or a catalogue. + assertEquals("", chatHeaderMeta(ChatThread(sessionId = "ses_1"))) + assertEquals("Operator", chatHeaderMeta(ChatThread(sessionId = "ses_1", tag = ChatProtocol.TAG_OPERATOR))) + } + + @Test + fun aSessionTagAndAThreadTagLabelTheSame() { + assertEquals(sessionTagLabel(ChatSession(tag = ChatProtocol.TAG_OPERATOR)), sessionTagLabel(ChatProtocol.TAG_OPERATOR)) + assertEquals("scratch", sessionTagLabel("scratch")) + assertNull(sessionTagLabel("")) + } } diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt index 779ceb66..57cf17a4 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatSessionManagementTest.kt @@ -143,6 +143,23 @@ class ChatSessionManagementTest { assertTrue(store.value.visibleSessions == listed) } + @Test + fun anOpenConversationCarriesTheModelAndTagTheServerReports() { + val store = ChatStore() + store.sessionsLoaded(listOf(session("a").copy(model = "deepseek-v4.1-flash", agent = "build"))) + store.open(store.value.sessions.single()) + // The header reads the server's own values, so opening a session shows + // what is answering without a second request. + assertEquals("deepseek-v4.1-flash", store.value.thread("a")!!.model) + assertEquals("build", store.value.thread("a")!!.agent) + assertEquals(ChatProtocol.TAG_OPERATOR, store.value.thread("a")!!.tag) + + // A later list refresh folds the server's reported model into the open + // conversation too, so the header never shows a stale model id. + store.sessionsLoaded(listOf(session("a").copy(model = "gpt-x", agent = "build"))) + assertEquals("gpt-x", store.value.thread("a")!!.model) + } + @Test fun theCoveredPaneCountMatchesTheVisibleList() { val store = ChatStore() diff --git a/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt new file mode 100644 index 00000000..43712b85 --- /dev/null +++ b/android/app/src/test/java/net/awan/pipelines/ui/chat/ChatTranscriptTest.kt @@ -0,0 +1,152 @@ +package net.awan.pipelines.ui.chat + +import net.awan.pipelines.data.protocol.ChatPart +import net.awan.pipelines.data.protocol.ChatProtocol +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The conversation's reading decisions, all pure so they need no device: the + * markdown route out of the transcript, reasoning collapsed and remembering its + * expansion, and a header that names the session once with only context beside + * and below it. + */ +class ChatTranscriptTest { + + @Test + fun assistantTextReachesTheMarkdownRendererWithTheDocumentedSubset() { + val sample = """ + # Release notes + + Intro with **bold**, *italic*, `inline code` and a [link](https://example.com/x). + + - first + - second + + 1. one + 2. two + + > quoted line + + | Name | Value | + | --- | --- | + | a | 1 | + + ```kotlin + val gap = 8.dp + ``` + + --- + """.trimIndent() + val part = ChatPart(type = ChatProtocol.PART_TEXT, id = "p1", text = sample) + + // The transcript's own decision routes assistant text through markdown... + assertEquals(PartRendering.MARKDOWN, partRendering(part)) + // ...and the whole documented subset parses into the renderer's blocks. + val blocks = parseMarkdown(part.text) + assertTrue(blocks.any { it is MdHeading }) + assertTrue(blocks.any { it is MdParagraph }) + assertTrue(blocks.any { it is MdListBlock }) + assertTrue(blocks.any { it is MdQuote }) + assertTrue(blocks.any { it is MdTableBlock }) + assertTrue(blocks.any { it is MdCodeBlock }) + assertTrue(blocks.contains(MdRule)) + val spans = parseInline("**bold** *italic* `code` [link](https://example.com/x)") + assertTrue(spans.any { it is MdStrong }) + assertTrue(spans.any { it is MdEmphasis }) + assertTrue(spans.any { it is MdCodeSpan }) + assertTrue(spans.any { it is MdLinkSpan }) + } + + @Test + fun textOutsideTheMarkdownSubsetStillRendersAsItsOwnText() { + val text = "~~struck~~ and raw html; \$_unclosed" + val part = ChatPart(type = ChatProtocol.PART_TEXT, id = "p1", text = text) + assertEquals(PartRendering.MARKDOWN, partRendering(part)) + // Nothing in the subset matches, so the paragraph keeps the source verbatim. + assertEquals(listOf(MdParagraph(text)), parseMarkdown(text)) + + // A part kind the renderer does not know still shows its text, never drops it. + val unknown = ChatPart(type = "status", id = "p2", text = "connection restored") + assertEquals(PartRendering.PLAIN, partRendering(unknown)) + assertEquals(PartRendering.HIDDEN, partRendering(ChatPart(type = ChatProtocol.PART_TEXT, id = "p3"))) + } + + @Test + fun reasoningStartsCollapsedAndKeepsItsExpansionPerPart() { + var reasoning = ReasoningExpansion() + assertFalse(reasoning.isExpanded("m:r1")) + assertFalse(reasoning.isExpanded("m:r2")) + + reasoning = reasoning.toggled("m:r1") + assertTrue(reasoning.isExpanded("m:r1")) + assertFalse(reasoning.isExpanded("m:r2")) + + // Expanding a second part does not disturb the first. + reasoning = reasoning.toggled("m:r2") + assertTrue(reasoning.isExpanded("m:r1")) + assertTrue(reasoning.isExpanded("m:r2")) + + // Collapsing brings only that part back. + reasoning = reasoning.toggled("m:r1") + assertFalse(reasoning.isExpanded("m:r1")) + assertTrue(reasoning.isExpanded("m:r2")) + + // A blank key is never a key: it can never expand every id-less part at once. + val untouched = ReasoningExpansion().toggled("") + assertFalse(untouched.isExpanded("")) + } + + @Test + fun reasoningKeyIsStableForAServerPartAndFallsBackToTheIndex() { + assertEquals("m:r1", reasoningKey("m", ChatPart(id = "r1"), 0)) + assertEquals("m:2", reasoningKey("m", ChatPart(id = ""), 2)) + } + + @Test + fun theHeaderNamesTheSessionOnceAndOnlyAddsContext() { + val header = conversationHeader( + ChatThread( + sessionId = "ses_1", + title = "Fix the parser", + directory = "/Users/alan/repos/pipelines", + model = "openai/gpt-5", + tag = ChatProtocol.TAG_OPERATOR, + running = true, + ), + ) + assertEquals("Fix the parser", header.title) + assertEquals("Operator", header.kind) + assertEquals("Running", header.activity) + assertEquals(listOf("/Users/alan/repos/pipelines", "openai/gpt-5"), header.context) + + // The title is the only identity: the context never repeats it. + assertFalse(header.context.contains(header.title)) + assertFalse(header.kind == header.title) + assertFalse(header.activity == header.title) + } + + @Test + fun theHeaderFallsBackToTheIdAndOmitsUnknownContext() { + val header = conversationHeader(ChatThread(sessionId = "ses_untitled", running = false)) + assertEquals("ses_untitled", header.title) + assertNull(header.kind) + assertEquals("Idle", header.activity) + assertEquals(emptyList(), header.context) + } + + @Test + fun theConversationOffersOnlyTheOtherOpenChatsToSwitchTo() { + val a = ChatThread(sessionId = "a", title = "Alpha") + val b = ChatThread(sessionId = "b", title = "Beta") + val open = listOf(a, b) + + // The active chat is never repeated beside its own header... + assertEquals(listOf(b), openChatsBeside(open, "a")) + // ...and a single open chat leaves nothing to switch to. + assertEquals(emptyList(), openChatsBeside(listOf(a), "a")) + } +} diff --git a/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt b/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt index bb6d6a74..2c98d746 100644 --- a/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt +++ b/android/app/src/test/java/net/awan/pipelines/ui/components/RunStatusTest.kt @@ -9,6 +9,7 @@ class RunStatusTest { fun runStateOfMirrorsTheServerVocabulary() { assertEquals(RunState.Running, runStateOf("running")) assertEquals(RunState.Queued, runStateOf("queued")) + assertEquals(RunState.Waiting, runStateOf("waiting")) assertEquals(RunState.Active, runStateOf("active")) assertEquals(RunState.Succeeded, runStateOf("succeeded")) // Step/outcome words map onto the same states.