Merge lane-app2: keep the lane's reviewed work

Combine the reviewed Android work already on main (conversation reading:
markdown, collapsed reasoning, one identity) with the incoming lane's
"answer a waiting human decision from the phone" change (the waiting
run/step sync, HumanDecision/DecisionPrompt, the decide_run envelope and
the waiting RunState) over merge base d48175a.

The only conflicted file, android/README.md, now carries both sections
exactly once ("Conversation reading: markdown, collapsed reasoning, one
identity" and "Answer a waiting human decision from the phone") with no
bullet or paragraph dropped. The auto-merged Kotlin tree carries both
features; no conflict markers, duplicated blocks or dead code remain. The
resolution also restored the blank line between the two README sections.

Verified on the merged tree (JDK 17 from Homebrew openjdk@17,
ANDROID_HOME=/Users/alan/Library/Android/sdk, offline, no daemon):
- gradle :app:testDebugUnitTest --rerun-tasks -> BUILD SUCCESSFUL; JUnit
  XMLs total 58 suites / 525 tests / 0 failures / 0 errors / 0 skipped.
- gradle :app:assembleDebug -> BUILD SUCCESSFUL;
  app/build/outputs/apk/debug/app-debug.apk present (18,519,392 bytes).

Docs check: android/README.md records the resolved change. No packaged
template, README/topic doc or packaged authoring skill reference describes
the Android decision surface or changed as a result, so nothing there
needed updating. Nothing was deliberately left uncommitted.
This commit is contained in:
2026-10-17 15:47:04 +01:00
16 changed files with 979 additions and 66 deletions
@@ -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. ----
@@ -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, JsonElement>?): 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<String, JsonElement>?): List<String> {
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<String, String>): List<String> =
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>): RunStep? =
steps.lastOrNull { it.status == STEP_STATUS_WAITING }
@@ -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<RunSummary>? = 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<Long>? = null,
@@ -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<RunDetail>) -> 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. */
@@ -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<DecisionOption>,
) {
/** The author's option keys, in recorded order. */
val optionKeys: List<String> 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)
@@ -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)
}
/**
@@ -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<RunDetail>) -> 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<String?>(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)
}
}
}
}
@@ -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
@@ -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
}
}
@@ -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<RunDetail>) -> 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<RunDetail>) -> 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(
@@ -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,
)
}
}
}
}
@@ -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<String, JsonElement> =
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<String>(), waitingOptions(null))
assertEquals(emptyList<String>(), 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<String>(), 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)
}
}
@@ -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<String, JsonElement> =
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<String, String> = mapOf(
"deploy" to "#success",
"revise" to "worker",
"abort" to "#failure",
"error" to "#failure",
),
steps: List<RunStep> = 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))
}
}
@@ -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")))
}
@@ -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.