From f782c51c189f78c77cf3132b38b7d020ebfb7540 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 17 Oct 2026 15:38:58 +0100 Subject: [PATCH] android: answer a run's waiting human decision from the phone A human stage parks its run on a person, and the terminal client could answer it while the app had no decide request at all. This adds the missing piece so a waiting run is answerable from the phone. Protocol/repo: - PipelinesRepository.decideRun sends the same `decide_run` request the CLI and TUI build: stage (optional; the server infers it), option, optional feedback, with the exact wire names internal/protocol/message.go declares. Message gains the stage/option/feedback fields; no second mechanism is invented. - A waiting run/step now forces the existing push-driven full get_run (runDetailNeedsFullSync), so the waiting step's recorded options/prompt surface live with no refresh and no server field added. - RunState.Waiting (label "waiting", FrontHand glyph, violet palette entry) makes the waiting state honest in the list and summary. UI: - DecisionPrompt is the one shared surface: a "Waiting for your decision" card with a deliberate Decide action, plus the sheet showing the run and waiting stage, the author's instructions, every option as written with the label it routes to, an optional feedback field, and a Confirm decision button that is disabled until an option is chosen. It sits above the run detail's tabs and at the top of the waiting stage's pane, reachable from where the operator already is. - Answering applies the returned run detail immediately, so the new stage shows without a manual refresh. A refusal keeps the sheet open with the server's own message verbatim and silently re-reads the run rather than faking success. - Pure helpers pendingDecision, DecisionOption, DecisionDraft (the confirm gate) and decisionRefusalMessage; Tests: HumanDecisionTest and DecisionTest (13 new) plus waiting cases in RunEventsTest and RunStatusTest. Scope: android/ only. No server/Go/installer/Docker change, no new dependency (the glyph is from the already-declared material-icons-extended), no run started from the app, no adb or device use. Reflected where it belongs: android/README.md gained the dated feature section for this change. Checked and needing no update: the packaged pipeline templates (the change touches no pipeline definition), the repository's top-level README and docs/ topic docs (none enumerates the app's operations or the decide protocol; the TUI/CLI wording they carry is unchanged), and the packaged authoring skill references (the decide protocol is unchanged and already documented; no reference describes this app surface). --- android/README.md | 83 ++++++ .../pipelines/data/PipelinesRepository.kt | 28 ++ .../pipelines/data/protocol/HumanDecision.kt | 68 +++++ .../awan/pipelines/data/protocol/Message.kt | 9 + .../net/awan/pipelines/ui/AppViewModel.kt | 37 +++ .../java/net/awan/pipelines/ui/Decision.kt | 107 ++++++++ .../java/net/awan/pipelines/ui/RunEvents.kt | 17 +- .../pipelines/ui/components/DecisionPrompt.kt | 253 ++++++++++++++++++ .../awan/pipelines/ui/components/RunStatus.kt | 4 + .../ui/components/RunStatusPalette.kt | 8 + .../pipelines/ui/graph/StageDetailPane.kt | 25 ++ .../pipelines/ui/screens/RunDetailScreen.kt | 144 +++++----- .../data/protocol/HumanDecisionTest.kt | 112 ++++++++ .../net/awan/pipelines/ui/DecisionTest.kt | 143 ++++++++++ .../net/awan/pipelines/ui/RunEventsTest.kt | 6 +- .../pipelines/ui/components/RunStatusTest.kt | 1 + 16 files changed, 979 insertions(+), 66 deletions(-) create mode 100644 android/app/src/main/java/net/awan/pipelines/data/protocol/HumanDecision.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/Decision.kt create mode 100644 android/app/src/main/java/net/awan/pipelines/ui/components/DecisionPrompt.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/data/protocol/HumanDecisionTest.kt create mode 100644 android/app/src/test/java/net/awan/pipelines/ui/DecisionTest.kt diff --git a/android/README.md b/android/README.md index 40ba3020..3fa8b3e1 100644 --- a/android/README.md +++ b/android/README.md @@ -5861,3 +5861,86 @@ 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. + +## 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. 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/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..9277f9d0 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,11 +37,14 @@ 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 @@ -52,6 +55,7 @@ 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 +393,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. @@ -449,6 +455,8 @@ fun StageDetailPane( fetchArtifactBytes = fetchArtifactBytes, wide = wide, runContext = runContext, + decision = decision, + onDecide = onDecide, modifier = Modifier.padding(padding), ) } @@ -467,6 +475,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 +500,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 +769,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 +791,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..42d80ab9 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 @@ -236,69 +238,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, + ) + } } } } 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/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.