Files
pipelines/web/src/runDetail.js
T

905 lines
34 KiB
JavaScript

// Pure, DOM-free logic for the run-detail tabs and the stage pane, ported from
// the Android client so the browser says and shows exactly the same things:
// ui/screens/RunDetailScreen.kt the tab set (RUN_DETAIL_TABS)
// ui/screens/RunSummaryTab.kt the summary rows and identity line
// ui/screens/RunFieldSectionsTab.kt input/output field sections
// ui/screens/Timeline.kt runTimeline, timelineDescription, hasArtifacts
// ui/graph/StageDetailPane.kt runStepFields, headline/evidence split,
// stageSectionSpecs, stageDefinitionFields,
// controlVisitLabel, clampVisitIndex
// ui/graph/StageVerdict.kt verdictReasonSegments, referencedVerdictArtifacts
// ui/Format.kt displayText/displayMap, fileChangeLine,
// notificationLine, fileChangesSummary
// data/protocol/GraphSemantics.kt nodeLabel, outcome ordering, edge labels
// ui/graph/GraphPalette.kt the curated graph-only outcome palette
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and formatting can be unit-tested without a
// browser. The tab/pane wiring lives in app.js. Every server-provided string is
// only ever compared or rendered, never parsed as markup; the caller sets it
// with textContent.
import {
runIdentity,
visitCount,
formatDuration,
durationSeconds,
secondsSince,
formatLocalTimestamp,
runStateOf,
} from "./runs.js";
import { presentedArtifacts, sessionExportArtifact, stageArtifacts, visitArtifacts, displayVisit } from "./artifacts.js";
import { changeStat, parseUnifiedPatch, runChanges, runChangesHeader } from "./changes.js";
import { effectiveStageType } from "./templates.js";
// ---------------------------------------------------------------------------
// Tabs
// ---------------------------------------------------------------------------
/**
* The run-detail tabs, Summary first so it is the default selection. The Graph
* tab sits between Summary and Input (R5) and mounts the shared workflow graph
* in run mode. The timeline keeps Android's stable key `steps` with the visible
* title `Timeline`.
*/
export const RUN_DETAIL_TABS = [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "input", label: "Input" },
{ key: "output", label: "Output" },
{ key: "steps", label: "Timeline" },
];
/**
* The tabs the browser renders. Input and Output are run Summary sections now
* (alongside Artifacts and Files changed), not separate tabs; the stable keys
* `input`/`output` remain in RUN_DETAIL_TABS for Android parity and old routes.
*/
export const RENDERED_RUN_TABS = [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "steps", label: "Timeline" },
];
// The empty-state sentences, exactly as the app spells them.
export const EMPTY_INPUT_MESSAGE = "No input recorded.";
export const EMPTY_OUTPUT_MESSAGE = "No output recorded.";
export const EMPTY_TIMELINE_MESSAGE = "No visits recorded.";
export const NO_STAGE_DETAILS_MESSAGE = "No details recorded for this node.";
/** The original run prompt, without display formatting or a fallback source. */
export function originalRunPrompt(run) {
return typeof run?.input?.prompt === "string" ? run.input.prompt : undefined;
}
/** The stage-pane section titles (Android StageDetailPane constants). */
export const STAGE_ARTIFACTS_TITLE = "Artifacts";
export const STAGE_SESSION_TITLE = "Session";
export const STAGE_EVIDENCE_TITLE = "This run";
export const STAGE_DEFINITION_TITLE = "Stage definition";
// ---------------------------------------------------------------------------
// Field display (ui/Format.kt displayText / displayMap)
// ---------------------------------------------------------------------------
/**
* Compact rendering of an arbitrary JSON value for read-only display: a
* primitive verbatim, an array `, `-joined, an object `k=v` `, `-joined.
* Mirrors Format.kt JsonElement.displayText (a JSON null reads `null`).
*/
export function displayText(value) {
if (Array.isArray(value)) return value.map((item) => displayText(item)).join(", ");
if (value !== null && typeof value === "object") {
return Object.entries(value)
.map(([key, item]) => `${key}=${displayText(item)}`)
.join(", ");
}
if (value === undefined) return "null";
return String(value);
}
/**
* A field map rendered one `key: value` line per entry, in insertion order.
* Mirrors Format.kt Map<String, JsonElement>?.displayMap (a null/empty map is
* the empty string).
*/
export function displayMap(map) {
if (!map) return "";
return Object.entries(map)
.map(([key, value]) => `${key}: ${displayText(value)}`)
.join("\n");
}
/**
* The input/output tab's sections, one per map entry in insertion order: the
* entry's own key as the title (falling back to the section prefix so it is
* never empty) and the value's display text. Mirrors
* RunFieldSectionsTab.fieldSectionTitle + displayText.
*/
export function fieldSections(map, keyPrefix) {
if (!map) return [];
return Object.entries(map).map(([key, value]) => ({
key,
title: fieldSectionTitle(key, keyPrefix),
value: displayText(value),
}));
}
/** A field section's title: the field's own name, else the section prefix. */
export function fieldSectionTitle(key, keyPrefix) {
const text = String(key ?? "");
return text.trim() === "" ? keyPrefix : text;
}
// ---------------------------------------------------------------------------
// Run summary (ui/screens/RunSummaryTab.kt)
// ---------------------------------------------------------------------------
/**
* The summary rows in Android order: Pipeline `id {id} · v{version}`, Stage, the
* resource-wait line only when `resource_wait` is set, Workspace, Content hash
* (monospace), Started, Finished, the live-aware Duration, `Retry of run {n}`
* when set, and the Diagnostic block. Blank values are omitted so no empty row
* is ever drawn. Each entry is tagged with a `kind` so the renderer can style
* and (for `duration`) live-update it.
*/
export function summaryRows(run, nowMillis, options = {}) {
if (!run) return [];
const rows = [];
const kv = (key, value, monospace = false) => {
const text = String(value ?? "");
if (text.trim() === "") return;
rows.push({ kind: "kv", key, value: text, monospace });
};
if (Number(run.pipeline_id) > 0) {
rows.push({
kind: "pipeline",
key: "Pipeline",
value: `id ${run.pipeline_id} · v${run.version ?? 0}`,
pipelineId: Number(run.pipeline_id),
pipelineName: String(run.name ?? ""),
version: Number(run.version) || 0,
});
} else {
kv("Pipeline", `id ${run.pipeline_id ?? 0} · v${run.version ?? 0}`);
}
kv("Stage", run.current_stage);
const wait = resourceWaitLine(run);
if (wait) rows.push({ kind: "wait", value: wait });
kv("Workspace", run.workspace);
kv("Content hash", run.content_hash, true);
kv("Started", formatLocalTimestamp(run.created_at, options));
kv("Finished", formatLocalTimestamp(run.finished_at, options));
const duration = runDurationText(run, nowMillis);
if (duration != null) rows.push({ kind: "duration", key: "Duration", value: duration });
if (Number(run.retry_of) > 0) kv("Retry of", `run ${run.retry_of}`);
if (String(run.diagnostic ?? "").trim() !== "") {
rows.push({ kind: "block", key: "Diagnostic", value: String(run.diagnostic) });
}
return rows;
}
/**
* The resource-wait line, `Waiting for resource {name}`, only when the run is
* waiting on a resource. Mirrors RunSummaryTab's `run.resourceWait?.let { ... }`
* and ResourceWait.statusLabel.
*/
export function resourceWaitLine(run) {
if (!run || run.resource_wait == null) return "";
return `Waiting for resource ${String(run.resource_wait.resource ?? "")}`;
}
/**
* The run's identity line: `run {id} · {recorded visits} · {completed visits}`,
* the same recorded/completed vocabulary the runs list and the server use.
* Mirrors RunSummaryTab's buildString.
*/
export function runIdentityLine(run) {
if (!run) return "";
const recorded = visitCount((run.steps ?? []).length, "recorded");
const completed = visitCount(Number(run.completed_steps) || 0, "completed");
return `run ${run.id} · ${recorded} · ${completed}`;
}
/**
* The run's primary label (stored title, else the pipeline name), from the one
* runIdentity helper the runs list also uses so the two never disagree.
*/
export function runLabelFor(run) {
return runIdentity(run?.title, run?.name).label;
}
/**
* The summary's Duration value: live elapsed while executing, else the stored
* total. Mirrors Format.kt runDurationText (null when unavailable, so the caller
* omits the row).
*/
export function runDurationText(run, nowMillis) {
if (!run) return null;
if (run.executing) {
const elapsed = secondsSince(run.created_at, nowMillis);
return elapsed == null ? null : formatDuration(elapsed);
}
const total = durationSeconds(run.created_at, run.finished_at);
return total == null ? null : formatDuration(total);
}
// ---------------------------------------------------------------------------
// Timeline (ui/screens/Timeline.kt)
// ---------------------------------------------------------------------------
/**
* The run's timeline plus each stage's ordered visits, derived in one pass.
* Stages keep first-appearance order; a stage's visits are ordered by sequence.
* One entry per recorded visit, in step order, with the display visit number,
* the outcome chip label (`outcome` else `status`), whether the visit recorded
* artifacts, its duration and its one-line description. Pure and total over an
* empty list and blank control/outcome fields. Mirrors `runTimeline`.
*/
export function runTimeline(steps) {
const list = steps ?? [];
if (list.length === 0) return { entries: [], visitsByStage: new Map() };
const visitsByStage = new Map();
for (const step of list) {
const stage = step?.stage ?? "";
if (!visitsByStage.has(stage)) visitsByStage.set(stage, []);
visitsByStage.get(stage).push(step);
}
const indexByStageSequence = new Map();
for (const [stage, visits] of visitsByStage) {
[...visits]
.sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0))
.forEach((visit, index) => indexByStageSequence.set(`${stage}\u0000${visit?.sequence ?? 0}`, index));
}
const entries = list.map((step) => {
const index = indexByStageSequence.get(`${step?.stage ?? ""}\u0000${step?.sequence ?? 0}`) ?? 0;
return {
step,
stageKey: step?.stage ?? "",
visit: displayVisit(step, index),
visitIndex: index,
outcomeLabel: String(step?.outcome ?? "").trim() !== "" ? String(step.outcome) : String(step?.status ?? ""),
hasArtifacts: hasArtifacts(step),
duration: stepDuration(step),
description: timelineDescription(step),
};
});
const orderedVisits = new Map();
for (const [stage, visits] of visitsByStage) {
orderedVisits.set(
stage,
[...visits].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0)),
);
}
return { entries, visitsByStage: orderedVisits };
}
/**
* The brief one-line description after a visit's name: the first non-blank
* diagnostic line, else the resolved target, else nothing (never fabricated).
*/
export function timelineDescription(step) {
const diagnostic = String(step?.diagnostic ?? "");
const line = diagnostic.split(/\r?\n/).find((candidate) => candidate.trim() !== "");
if (line != null) return line.trim();
const target = String(step?.target ?? "");
if (target.trim() !== "") return `→ ${nodeLabel(target)}`;
return "";
}
/**
* Whether a visit recorded any presented artifact. The retired session markdown
* is not presented, so it never counts. Composes the one presentedArtifacts
* filter so the timeline and the pane never disagree.
*/
export function hasArtifacts(step) {
return presentedArtifacts(step).length > 0;
}
/** Human duration between a step's timestamps, or null when unavailable. */
export function stepDuration(step) {
const seconds = durationSeconds(step?.started_at, step?.finished_at);
return seconds == null ? null : formatDuration(seconds);
}
// ---------------------------------------------------------------------------
// Graph semantics (data/protocol/GraphSemantics.kt, Message.kt)
// ---------------------------------------------------------------------------
export const SUCCESS_END = "#success";
export const FAILURE_END = "#failure";
/** A node label: the success/failure terminal shorthand, else the key itself. */
export function nodeLabel(key) {
if (key === SUCCESS_END) return "SUCCESS";
if (key === FAILURE_END) return "FAILURE";
return String(key ?? "");
}
/** Whether a resolved target is an explicit terminal. */
export function isTerminal(target) {
return target === SUCCESS_END || target === FAILURE_END;
}
/** Mirrors Protocol.resolveTarget: preserve `#` as the outcome's terminal. */
export function resolveTarget(outcome, target) {
if (target !== "#") return target;
return outcome === "error" ? FAILURE_END : SUCCESS_END;
}
/** A stage's outcomes (edge keys) in the app's order: success, others, error. */
export function stageOutcomes(stage) {
return Object.keys(stage?.edges ?? {}).sort((a, b) => {
const pa = a === "success" ? 0 : a === "error" ? 2 : 1;
const pb = b === "success" ? 0 : b === "error" ? 2 : 1;
return pa - pb || (a < b ? -1 : a > b ? 1 : 0);
});
}
/** Every definition edge in stable order. Mirrors Graph.edges(). */
export function graphEdges(graph) {
const result = [];
for (const stage of graph?.stages ?? []) {
for (const outcome of stageOutcomes(stage)) {
const target = resolveTarget(outcome, stage.edges[outcome]);
result.push({
source: stage.key,
outcome,
target,
label: outcome === "error" && stage.fallback_error ? "error*" : outcome,
});
}
}
return result;
}
/**
* Which stages and routes a run actually recorded, for the graph's execution
* highlighting. Mirrors Android `RunGraphState.from` (GraphSemantics.kt:91-116):
* every step's stage key is a visited stage (insertion order), a step with a
* non-blank outcome and target contributes a taken route
* `{source, outcome, resolvedTarget}` (recorded as a `source\0outcome\0target`
* key the graph matches) and, when that resolved target is a terminal, marks the
* terminal visited too. `currentStage` is the run's own stage, else the last
* visit's stage, else null; `executing` mirrors the run; `currentStageStartedAt`
* is the running visit's start for the active stage, only while executing. Pure
* and DOM-free so the renderer and the tests share one definition.
*/
export function runGraphState(run) {
const visitedStages = [];
const seenStages = new Set();
const takenRoutes = [];
const seenRoutes = new Set();
const steps = run?.steps ?? [];
const visit = (key) => {
if (key == null || seenStages.has(key)) return;
seenStages.add(key);
visitedStages.push(key);
};
for (const step of steps) {
visit(step?.stage);
const outcome = String(step?.outcome ?? "");
const target = String(step?.target ?? "");
if (target.trim() !== "" && outcome.trim() !== "") {
const resolved = resolveTarget(outcome, target);
const route = `${step?.stage}\u0000${outcome}\u0000${resolved}`;
if (!seenRoutes.has(route)) {
seenRoutes.add(route);
takenRoutes.push(route);
}
if (isTerminal(resolved)) visit(resolved);
}
}
const lastStage = steps.length > 0 ? steps[steps.length - 1]?.stage : "";
const rawCurrent = String(run?.current_stage ?? "").trim() !== "" ? run.current_stage : lastStage;
const currentStage = String(rawCurrent ?? "").trim() !== "" ? String(rawCurrent) : null;
const executing = Boolean(run?.executing);
let currentStageStartedAt = null;
if (executing && currentStage != null) {
for (let index = steps.length - 1; index >= 0; index -= 1) {
const step = steps[index];
if (step?.stage === currentStage && step?.status === "running") {
const started = String(step?.started_at ?? "");
if (started.trim() !== "") currentStageStartedAt = started;
break;
}
}
}
return { visitedStages, takenRoutes, currentStage, executing, currentStageStartedAt };
}
// ---------------------------------------------------------------------------
// Stage pane (ui/graph/StageDetailPane.kt)
// ---------------------------------------------------------------------------
/** One labelled row/block of stage detail, rendered by the pane. */
function field(label, value, mono = false, block = false) {
return { label, value, mono, block };
}
/**
* The always-visible run-side identity/result labels of a step. The item's
* headline list adds `Session` beside the app's six, so a visit that recorded a
* session id shows it up top with the rest of its result facts.
*/
export const STAGE_HEADLINE_LABELS = new Set([
"Status",
"Outcome",
"Target",
"Duration",
"Visit",
"Model target",
"Session",
]);
/** The always-visible run-side identity/result fields of a step's evidence. */
export function headlineFields(fields) {
return (fields ?? []).filter((entry) => STAGE_HEADLINE_LABELS.has(entry.label));
}
/**
* The remaining run evidence (diagnostic, transcript, agent, file changes,
* notifications) that belongs in the collapsible "This run" section: the
* headline facts and the input/output result blocks are surfaced elsewhere.
*/
export function evidenceFields(fields) {
return (fields ?? []).filter(
(entry) =>
!STAGE_HEADLINE_LABELS.has(entry.label) && entry.label !== "Input" && entry.label !== "Output",
);
}
/**
* The pure run view of one step: status, outcome, duration, visit against the
* control's max visits, target, session id, agent flag, diagnostic, transcript,
* the step's input/output, a file-change summary, changed files and notification
* receipts. Blank fields are skipped, so no empty row is ever emitted. Mirrors
* `runStepFields`.
*/
/** What an empty turn body reads as, matching input.md's own marker. */
const NO_TURN_OUTPUT = "_(no output)_";
/**
* A turn's value map carries the whole markdown body under the single key
* `markdown`. Returns that body so the pane can render it as the document it is;
* null means an ordinary map that still needs its keys shown.
*/
function turnBody(map) {
if (!map || typeof map !== "object") return null;
const keys = Object.keys(map);
if (keys.length !== 1 || keys[0] !== "markdown" || typeof map.markdown !== "string") return null;
return map.markdown;
}
export function runStepFields(step) {
const fields = [];
if (step == null) return fields;
if (str(step.status).trim() !== "") fields.push(field("Status", str(step.status)));
if (str(step.outcome).trim() !== "") fields.push(field("Outcome", str(step.outcome)));
const duration = stepDuration(step);
if (duration != null) fields.push(field("Duration", duration));
const control = step.control;
if (control) {
if (Number(control.max_visits) > 0 || Number(control.visit) > 0) {
fields.push(field("Visit", controlVisitLabel(control)));
}
const modelTarget = str(control.model_target);
if (modelTarget.trim() !== "") fields.push(field("Model target", modelTarget));
}
if (str(step.target).trim() !== "") fields.push(field("Target", str(step.target)));
if (str(step.session_id).trim() !== "") fields.push(field("Session", str(step.session_id), true));
if (step.agent_active) fields.push(field("Agent", "active"));
if (str(step.diagnostic).trim() !== "") fields.push(field("Diagnostic", str(step.diagnostic), false, true));
if (str(step.transcript).trim() !== "") fields.push(field("Transcript", str(step.transcript), false, true));
if (step.input && Object.keys(step.input).length > 0) {
const body = turnBody(step.input);
fields.push(
body == null
? field("Input", displayMap(step.input), false, true)
: field("Input", body.trim() === "" ? NO_TURN_OUTPUT : body, false, true),
);
}
if (step.output && Object.keys(step.output).length > 0) {
const body = turnBody(step.output);
fields.push(
body == null
? field("Output", displayMap(step.output), false, true)
: field("Output", body.trim() === "" ? NO_TURN_OUTPUT : body, false, true),
);
}
const changes = step.file_changes;
if (changes) {
const summary = fileChangesSummary(changes);
if (summary.trim() !== "") fields.push(field("File changes", summary));
const files = changes.files ?? [];
if (files.length > 0) {
fields.push(field("Changed files", files.map((file) => fileChangeLine(file)).join("\n"), false, true));
}
}
for (const receipt of step.notifications ?? []) {
if (str(receipt?.status).trim() !== "" || str(receipt?.destination).trim() !== "") {
fields.push(field("Notification", notificationLine(receipt)));
}
}
return fields;
}
/**
* The stage definition view: key + type title, prompt, output, edges with their
* outcomes and resolved terminals, configs, tools, limits and memory sources.
* Only non-blank fields are emitted. Mirrors `stageDefinitionFields`.
*/
export function stageDefinitionFields(stage) {
const fields = [];
if (stage == null) return fields;
fields.push(field("Type", effectiveStageType(stage.type)));
if (str(stage.prompt).trim() !== "") fields.push(field("Prompt", str(stage.prompt), false, true));
if (str(stage.output).trim() !== "") fields.push(field("Output", str(stage.output), false, true));
const outcomes = stageOutcomes(stage).map((outcome) => {
const target = resolveTarget(outcome, String(stage.edges?.[outcome] ?? ""));
const suffix = isTerminal(target) ? " (terminal)" : "";
return `${outcome} → ${nodeLabel(target)}${suffix}`;
});
if (outcomes.length > 0) fields.push(field("Outcomes", outcomes.join("\n"), false, true));
const configs = stage.configs ?? {};
for (const key of Object.keys(configs).sort()) {
const value = str(configs[key]);
if (value.trim() !== "") fields.push(field(configLabel(key), value));
}
const tools = stage.blocks?.tools;
if (str(tools).trim() !== "") fields.push(field("Tools", str(tools), false, true));
const limits = stage.limits;
if (limits) {
if (Number(limits.max_visits) > 0) fields.push(field("Max visits", String(limits.max_visits)));
const on = limits.on ?? [];
if (on.length > 0) fields.push(field("Limit on", on.join(", ")));
}
const memory = stage.memory;
if (memory && Object.keys(memory).length > 0) {
const value = Object.entries(memory)
.map(([key, source]) => `${key}: ${source}`)
.join("\n");
fields.push(field("Memory", value, false, true));
}
const notify = stage.notify;
if (notify) {
const on = notify.on ?? [];
if (on.length > 0) fields.push(field("Notify on", on.join(", ")));
if (str(notify.destination).trim() !== "") fields.push(field("Notify destination", str(notify.destination)));
const artifacts = notify.artifacts ?? [];
if (artifacts.length > 0) fields.push(field("Notify artifacts", artifacts.join(", ")));
}
return fields;
}
/** The config key's display label (mirrors StageDetailPane.configLabel). */
export function configLabel(key) {
switch (key) {
case "provider":
return "Provider";
case "model":
return "Model";
case "retries":
return "Retries";
case "timeout":
return "Timeout";
case "budget_usd":
return "Budget (USD)";
case "budget_tokens":
return "Budget (tokens)";
case "harness":
return "Harness";
default:
return key;
}
}
/** Incoming routes into a terminal node, for a pane opened on a terminal. */
export function terminalFields(graph, key) {
const lines = graphEdges(graph)
.filter((edge) => edge.target === key)
.map((edge) => `${edge.source} · ${edge.label} → ${nodeLabel(key)}`);
return lines.length === 0 ? [] : [field("Incoming routes", lines.join("\n"), false, true)];
}
/**
* The shared visit label for a step's control evidence, e.g.
* `3 / 5 (limit reached)` (or just `3` when no max is recorded). Mirrors
* `controlVisitLabel`.
*/
export function controlVisitLabel(control) {
const visit = Number(control?.visit) || 0;
const max = Number(control?.max_visits) || 0;
const base = max > 0 ? `${visit} / ${max}` : String(visit);
return base + (control?.limit_reached ? " (limit reached)" : "");
}
/** Clamps a visit index into `[0, count)`; an empty list yields 0. */
export function clampVisitIndex(index, count) {
if (count <= 0) return 0;
return Math.min(Math.max(Number(index) || 0, 0), count - 1);
}
/**
* The ordered sections of the stage pane for one stage and visit: a run pane
* leads with the visit's Artifacts gallery, then its exported Session when it
* has one, then Output, Input and the remaining evidence (`This run`); the
* stage's own definition is last. Blank field sections are skipped; the
* artifacts section always shows for a reached visit. Mirrors
* `stageSectionSpecs`.
*/
/**
* Whether a recorded field value is markdown rather than plain text: a heading, a
* fenced block, a bullet/ordered list or a table. The new stage turns write
* markdown bodies (`# outcome` …), while historical steps store plain maps; this
* keeps the old ones rendering as code.
*/
export function looksLikeMarkdown(value) {
const text = typeof value === "string" ? value : "";
if (!text) return false;
return /^#{1,6}\s/m.test(text) || /```/.test(text) || /^\s*(?:[-*]|\d+\.)\s+/m.test(text) || /^\|.+\|/m.test(text);
}
/**
* The stage pane's body sections for one visit: what the stage produced (its
* non-system artifacts) and what it changed. The turn files, session export and
* stage definition live behind Audit & debug, so the pane stays about the work.
*/
export function stageSectionSpecs(stageKey, graph, runSteps, visitIndex, runContext, allSteps = null) {
const specs = [];
const steps = runSteps ?? [];
const selectedStep = steps[clampVisitIndex(visitIndex, steps.length)];
if (runContext && selectedStep != null) {
const used = visitArtifacts(selectedStep, allSteps ?? steps).length;
specs.push({ key: "artifacts", title: `${STAGE_ARTIFACTS_TITLE} · ${used} recorded`, artifacts: true });
if (selectedStep.file_changes != null) {
specs.push({ key: "changes", title: runChangesHeader(runChanges([selectedStep])), changes: true });
}
}
return specs;
}
// ---------------------------------------------------------------------------
// Verdict (ui/graph/StageVerdict.kt)
// ---------------------------------------------------------------------------
/**
* The recorded artifacts a verdict refers to: its referenced names resolved to
* the visit's recorded artifacts, in recorded order and deduplicated by name. A
* name the server never recorded is dropped. Mirrors
* `referencedVerdictArtifacts`.
*/
export function referencedVerdictArtifacts(verdict, artifacts) {
const names = verdict?.artifacts ?? [];
if (names.length === 0) return [];
const wanted = new Set(names);
const seen = new Set();
const referenced = [];
for (const artifact of artifacts ?? []) {
const name = str(artifact?.name);
if (name === "" || seen.has(name)) continue;
seen.add(name);
if (wanted.has(name)) referenced.push(artifact);
}
return referenced;
}
/**
* Splits a reason into literal runs and references to the recorded artifacts it
* names (by full name or basename). At the same index a longer token wins. With
* nothing to reference the whole reason is one literal segment; an empty reason
* yields no segments. Mirrors `verdictReasonSegments`.
*/
export function verdictReasonSegments(reason, references) {
const text = String(reason ?? "");
if (text === "") return [];
const list = references ?? [];
if (list.length === 0) return [{ text }];
const tokens = [];
for (const artifact of list) {
const name = str(artifact?.name);
tokens.push([name, artifact]);
const base = artifactBaseName(name);
if (base !== "" && base !== name) tokens.push([base, artifact]);
}
tokens.sort((a, b) => b[0].length - a[0].length);
const segments = [];
let literal = "";
let index = 0;
while (index < text.length) {
const match = tokens.find(([token]) => text.startsWith(token, index));
if (!match) {
literal += text[index];
index++;
} else {
if (literal !== "") {
segments.push({ text: literal });
literal = "";
}
segments.push({ text: match[0], artifact: match[1] });
index += match[0].length;
}
}
if (literal !== "") segments.push({ text: literal });
return segments;
}
/** The last path segment of a recorded artifact name (`shots/x.png` → `x.png`). */
export function artifactBaseName(name) {
const text = str(name);
const slash = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\"));
return slash === -1 ? text : text.slice(slash + 1);
}
// ---------------------------------------------------------------------------
// Formatting (ui/Format.kt)
// ---------------------------------------------------------------------------
/**
* One changed-file line, e.g. `modified src/a.kt +3 -2 (truncated)`. The kind,
* path and binary/truncated markers are Format.kt's exact spelling; the `+N -M`
* stat is added when the recorded patch is readable (not binary) and parses to
* at least one hunk, so a line never claims a line count it could not read. A
* binary file keeps its marker and never gets a text stat.
*/
export function fileChangeLine(file) {
const base = `${str(file?.kind)} ${str(file?.path)}`;
const binary = file?.binary ? " (binary)" : "";
const truncated = file?.truncated ? " (truncated)" : "";
let stat = "";
if (!file?.binary) {
const patch = str(file?.patch);
if (patch.trim() !== "") {
const parsed = parseUnifiedPatch(patch);
if (parsed.hunks.length > 0) stat = changeStat(parsed.added, parsed.removed);
}
}
return base + (stat !== "" ? ` ${stat}` : "") + binary + truncated;
}
/** One notification receipt, e.g. `delivered → ntfy · ok`, skipping a blank diagnostic. */
export function notificationLine(receipt) {
const diagnostic = str(receipt?.diagnostic);
const suffix = diagnostic.trim() !== "" ? ` · ${diagnostic}` : "";
return `${str(receipt?.status)} → ${str(receipt?.destination)}${suffix}`;
}
/**
* A compact file-change summary, e.g.
* `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`.
* The status word, file count, skipped and omitted counts are the capture's own
* honest facts; the trimmed diagnostic follows after ` · ` when present. Blank
* parts are omitted, and an entirely blank change set renders as "".
*/
export function fileChangesSummary(changes) {
let text = "";
const status = str(changes?.status).trim();
if (status !== "") text += status;
const files = changes?.files ?? [];
if (files.length > 0) {
if (text !== "") text += " ";
text += `(${files.length} files)`;
}
if (Number(changes?.skipped) > 0) {
if (text !== "") text += ", ";
text += `${changes.skipped} skipped`;
}
if (Number(changes?.omitted) > 0) {
if (text !== "") text += ", ";
text += `${changes.omitted} omitted`;
}
const diagnostic = str(changes?.diagnostic).trim();
if (diagnostic !== "") {
if (text !== "") text += " · ";
text += diagnostic;
}
return text;
}
// ---------------------------------------------------------------------------
// Outcome colours (ui/graph/GraphPalette.kt, WorkflowGraph.outcomeColor)
// ---------------------------------------------------------------------------
/**
* The fixed palette for the graph-only flow outcomes (rejected/exhausted/retry/
* approved/fast/missing) plus the reserved fallback slots. Mirrors
* GraphPalette.colors.
*/
export const FLOW_OUTCOME_COLORS = [
"#F5A3A3", // rejected
"#F5B37A", // exhausted
"#7FD4E8", // retry
"#C0A3F5", // approved
"#F0E07A", // fast
"#F5A3D0", // missing
"#D8C98A", // fallback
"#9FD8C0", // fallback
"#D8A8C0", // fallback
];
const KNOWN_FLOW_OUTCOMES = ["rejected", "exhausted", "retry", "approved", "fast", "missing"];
/**
* The stable palette index for an outcome with no run-state meaning: known flow
* outcomes get their curated slot, everything else a stable fallback slot.
* Mirrors GraphPalette.outcomeColorIndex.
*/
export function flowOutcomeIndex(outcome) {
const known = KNOWN_FLOW_OUTCOMES.indexOf(outcome);
if (known !== -1) return known;
const fallbackStart = KNOWN_FLOW_OUTCOMES.length;
const fallbackCount = FLOW_OUTCOME_COLORS.length - fallbackStart;
if (fallbackCount <= 0) return 0;
return fallbackStart + (Math.abs(hashString(outcome)) % fallbackCount);
}
/**
* The colour token for an outcome/stage status: a run-state word takes the
* shared status palette (`state {state}`), any other flow outcome its curated
* palette slot (`flow {index}`). The renderer maps the token onto a CSS class so
* the timeline and the verdict block agree. Mirrors WorkflowGraph.outcomeColor.
*/
export function outcomeColorToken(outcome, status) {
const state = runStateOf(String(outcome ?? "").trim() !== "" ? outcome : status);
if (state !== "unknown") return `state ${state}`;
return `flow ${flowOutcomeIndex(String(outcome ?? "").trim() !== "" ? outcome : status)}`;
}
/** A distinct glyph per run state, echoing the app's one-glyph-per-state set. */
export function stateGlyph(state) {
switch (state) {
case "running":
return "▶";
case "queued":
return "◷";
case "waiting":
return "✋";
case "succeeded":
return "✓";
case "failed":
return "✕";
case "canceled":
return "⊘";
case "interrupted":
return "❚❚";
case "blocked":
return "■";
case "skipped":
return "⏭";
case "active":
return "⚡";
default:
return "?";
}
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
function str(value) {
return value == null ? "" : String(value);
}
/** A small, stable 31-bit string hash (Kotlin String.hashCode analogue). */
function hashString(value) {
let hash = 0;
for (let i = 0; i < value.length; i++) {
hash = (hash * 31 + value.charCodeAt(i)) | 0;
}
return hash;
}