Files
pipelines/web/src/actions.js
T

248 lines
9.7 KiB
JavaScript

// Pure, DOM-free logic for the run-level operator actions the browser client
// offers on a run detail: the pending human decision (R11), cancel (R12), retry
// / restart (R13) and rename (R14). Ported from the Android client so the
// browser asks for and shows exactly the same things:
// ui/Decision.kt PendingDecision, DecisionOption,
// pendingDecision, decisionTargetLabel,
// DecisionDraft
// data/protocol/HumanDecision.kt lastWaitingStep, waitingPrompt,
// waitingOptions, humanOptions
// ui/components/DecisionPrompt.kt the decision card and sheet wording
// ui/screens/RunDetailScreen.kt the cancel/retry dialogs, Action failed
//
// Nothing here touches the DOM or imports the app: the decision model, the
// action eligibility rules and every user-visible string are unit-tested without
// a browser. The caller sets each string with textContent, never innerHTML.
import { nodeLabel, resolveTarget, runLabelFor } from "./runDetail.js";
/** Run status while parked on a person (mirrors protocol.RunStatusWaiting). */
export const RUN_STATUS_WAITING = "waiting";
/** The waiting step's status, i.e. the step a decision answers. */
export const STEP_STATUS_WAITING = "waiting";
/** Run status a retry is offered for. */
export const RUN_STATUS_FAILED = "failed";
/** Waiting evidence keys, the wire contract the server records. */
export const WAITING_PROMPT_KEY = "prompt";
export const WAITING_OPTIONS_KEY = "options";
// ---------------------------------------------------------------------------
// Decision evidence (data/protocol/HumanDecision.kt)
// ---------------------------------------------------------------------------
function str(value) {
return value == null ? "" : String(value);
}
/**
* The most recent step a run is waiting on (the last waiting step), or null when
* no step is waiting. Mirrors `tui.lastWaitingStep` / `HumanDecision.kt`.
*/
export function lastWaitingStep(steps) {
const list = steps ?? [];
for (let index = list.length - 1; index >= 0; index -= 1) {
if (list[index]?.status === STEP_STATUS_WAITING) return list[index];
}
return null;
}
/**
* The recorded operator instructions from a waiting step's output, or "" when
* none were recorded. Mirrors `protocol.WaitingPrompt`.
*/
export function waitingPrompt(output) {
const value = output?.[WAITING_PROMPT_KEY];
return typeof value === "string" ? value : "";
}
/**
* The recorded selectable options from a waiting step's output, in recorded
* order. Strings only, a malformed/blank entry dropped, an absent key yields an
* empty list — exactly like `protocol.WaitingOptions` / `waitingOptions`.
*/
export function waitingOptions(output) {
const value = output?.[WAITING_OPTIONS_KEY];
if (!Array.isArray(value)) return [];
return value.filter((entry) => typeof entry === "string" && entry.trim() !== "");
}
/**
* A stage's selectable outcomes: its non-`error` edges in sorted order. Mirrors
* `stage.HumanOptions`, the fallback when a waiting step recorded no options.
*/
export function humanOptions(edges) {
return Object.keys(edges ?? {})
.filter((key) => key !== "error")
.sort();
}
/**
* 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.
*/
export function decisionTargetLabel(option, target) {
if (target == null || String(target).trim() === "") return "";
return nodeLabel(resolveTarget(option, target));
}
/**
* 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; the graph only supplies the target labels and, for a step from
* an older server, the option set itself. Mirrors `pendingDecision`.
*/
export function pendingDecision(run) {
if (run == null || run.status !== RUN_STATUS_WAITING) return null;
if (Number(run.export_pending_sequence) > 0) return null;
const step = lastWaitingStep(run.steps ?? []);
const stepStage = str(step?.stage).trim() !== "" ? String(step.stage) : "";
const runStage = str(run.current_stage).trim() !== "" ? String(run.current_stage) : "";
const stageKey = stepStage !== "" ? stepStage : runStage;
if (stageKey === "") return null;
const declared = (run.graph?.stages ?? []).find((candidate) => candidate?.key === stageKey) ?? null;
if (declared?.type && declared.type !== "human") return null;
const recorded = waitingOptions(step?.output);
const keys = recorded.length > 0 ? recorded : humanOptions(declared?.edges);
if (keys.length === 0) return null;
const edges = declared?.edges ?? {};
const options = keys.map((key) => ({ key, target: decisionTargetLabel(key, edges[key]) }));
const stepPrompt = waitingPrompt(step?.output);
const instructions = stepPrompt.trim() !== "" ? stepPrompt : str(declared?.prompt);
return {
runId: run.id,
runLabel: runLabelFor(run),
stageKey,
instructions,
options,
};
}
/**
* The operator's in-progress answer: the chosen option and optional feedback.
* Pure, so the deliberate-confirm rule (nothing is sent until an option is
* chosen and Confirm is pressed) is unit-tested without a device. Mirrors
* `DecisionDraft`.
*/
export class DecisionDraft {
constructor(selected = null, feedback = "") {
this.selected = selected;
this.feedback = feedback;
}
/** A decision is only sendable once the operator has chosen one option. */
get canSubmit() {
return typeof this.selected === "string" && this.selected.trim() !== "";
}
/** Selecting an option is not an answer: it only enables the confirm. */
select(option) {
return new DecisionDraft(option, this.feedback);
}
/** Feedback is optional and carried verbatim (trimmed by the sender). */
withFeedback(text) {
return new DecisionDraft(this.selected, String(text ?? ""));
}
}
// ---------------------------------------------------------------------------
// Action eligibility (RunDetailScreen.kt)
// ---------------------------------------------------------------------------
/** Cancel is offered only while the run is executing. */
export function canCancel(run) {
return (Boolean(run?.executing) || (run?.status === RUN_STATUS_WAITING && Number(run.export_pending_sequence) > 0)) && !run.cancel_requested && !run.cleanup_unconfirmed;
}
/** Retry is offered only for a loaded, non-executing, `failed` run. */
export function canRetry(run) {
return run != null && !run.executing && run.status === RUN_STATUS_FAILED;
}
/** The retry modes available for a run: resume (default) and restart. */
export function retryModes(run) {
return canRetry(run) ? ["resume", "restart"] : [];
}
/**
* A fresh idempotency key for a retry request. The server requires one and caps
* it at 128 characters (PipelinesRepository.MAX_REQUEST_KEY); this stays well
* inside that bound and unique per attempt.
*/
export function retryRequestKey(runId, now = Date.now(), random = Math.random) {
const suffix = Math.floor((Number(random()) || 0) * 1e9).toString(36);
return `web-retry-${runId}-${now}-${suffix}`;
}
// ---------------------------------------------------------------------------
// Wording (DecisionPrompt.kt / RunDetailScreen.kt), verbatim
// ---------------------------------------------------------------------------
export const DECISION_CARD_TITLE = "Waiting for your decision";
export const DECISION_ACTION = "Decide";
export const FEEDBACK_LABEL = "Feedback (optional)";
export const DECISION_CANCEL = "Cancel";
export const DECISION_CONFIRM = "Confirm decision";
export const DECISION_SENDING = "Sending…";
export const CANCEL_DIALOG_MESSAGE = "This asks the server to stop the active run.";
export const CANCEL_CONFIRM = "Cancel run";
export const RETRY_DIALOG_MESSAGE =
"Only failed runs can be retried. The server starts a new run from the same input.";
export const RETRY_CONFIRM = "Retry";
export const DISMISS_KEEP = "Keep";
// The restart confirm is browser-only (Android exposes resume alone): it states
// plainly that it replays the whole pipeline instead of resuming the failed
// stage, so the more destructive choice is never ambiguous.
export const RESTART_CONFIRM = "Restart from start";
export const RESTART_DIALOG_MESSAGE =
"This replays the whole pipeline from the start instead of resuming the failed stage.";
export const RENAME_ACTION = "Rename";
export const RENAME_SAVE = "Save";
export const RENAME_CANCEL = "Cancel";
export const RENAME_FIELD_LABEL = "Run title";
export const ACTION_FAILED_TITLE = "Action failed";
export const ACTION_FAILED_OK = "OK";
/** The decision card's meta line: `{stage} · run {id} · {runLabel}`. */
export function decisionCardMeta(decision) {
return `${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}`;
}
/** The sheet title: `Decide {stage}`. */
export function decisionSheetTitle(stageKey) {
return `Decide ${stageKey}`;
}
/** The sheet meta line: `run {id} · {runLabel}`. */
export function decisionSheetMeta(decision) {
return `run ${decision.runId} · ${decision.runLabel}`;
}
/** The option's target line, `→ {target}`, or "" when the target is unknown. */
export function optionTargetText(target) {
return String(target ?? "").trim() === "" ? "" : `→ ${target}`;
}
/** The cancel dialog's title: `Cancel run {id}?`. */
export function cancelDialogTitle(runId) {
return `Cancel run ${runId}?`;
}
/** The retry dialog's title: `Retry run {id}?`. */
export function retryDialogTitle(runId) {
return `Retry run ${runId}?`;
}
/** The restart dialog's title: `Restart run {id}?`. */
export function restartDialogTitle(runId) {
return `Restart run ${runId}?`;
}