Files
pipelines/web/test/graph.test.mjs
T
alan ff70b3796f web: run-detail polish — bigger graph, artifact counts, tighter stage pane
- the run Graph tab drops the guidance paragraph and the graph fills ~70vh;
- the Artifacts collapsible carries the visit's count in its title (the body keeps
  the reason line only when there is nothing to show);
- the stage panel's section padding and gaps are reduced.
2026-10-19 20:05:47 +01:00

502 lines
20 KiB
JavaScript

// Unit tests for the pure workflow-graph helpers (src/graph.js): node order,
// the terminal row, edge label order and the `error*` fallback marker, lane
// assignment, the node-kind mapping, the stage-definition pane derivation and
// the viewport maths (fitScale/clampOffset/zoomAbout/hitTest). No DOM and no
// server: `node --test test/graph.test.mjs` proves the module's maths is pure.
// Wording is asserted against the Android app's own strings (WorkflowGraph.kt,
// GraphPalette.kt, GraphSemantics.kt, StageDetailPane.kt, RunGraphTab.kt).
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import {
MIN_SCALE,
MAX_SCALE,
PIPELINE_GRAPH_EMPTY,
RUN_GRAPH_MISSING,
NO_NODE_DETAILS,
STAGE_DEFINITION_TITLE,
configLabel,
edgeLabel,
graphEdges,
graphNodeKind,
graphDescription,
hitTest,
layoutGraph,
mount,
nodeDisplayLabel,
nodeKindClass,
stageDefinitionFields,
stageOutcomes,
terminalFields,
toGraphPoint,
clampOffset,
fitScale,
zoomAbout,
stageIsExecuted,
edgeIsExecuted,
activeStage,
} from "../src/graph.js";
import { runGraphState } from "../src/runDetail.js";
// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------
/** A two-stage definition ending in both terminals. */
function twoStageGraph() {
return {
stages: [
{
key: "plan",
type: "model",
prompt: "plan the work",
output: "a plan",
edges: { success: "impl", error: "#" },
fallback_error: true,
configs: {},
},
{
key: "impl",
type: "ntfy",
edges: { success: "#success" },
configs: {},
},
],
};
}
// ---------------------------------------------------------------------------
// Edge derivation (GraphSemantics)
// ---------------------------------------------------------------------------
test("stageOutcomes orders success first, error last, others alphabetical", () => {
const stage = {
edges: { error: "#", rejected: "a", success: "b", approved: "b", retry: "a" },
};
assert.deepEqual(stageOutcomes(stage), ["success", "approved", "rejected", "retry", "error"]);
});
test("graphEdges builds every definition edge in stable id order", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", error: "#", rejected: "a" }, fallback_error: true },
{ key: "b", edges: { success: "#success" } },
],
};
const edges = graphEdges(graph);
assert.deepEqual(
edges.map((edge) => edge.source),
["a", "a", "a", "b"],
);
assert.deepEqual(
edges.map((edge) => edge.id),
[1, 2, 3, 4],
);
// `#` resolves to the terminal on the error route; a stage target is kept.
assert.equal(edges[0].target, "b");
assert.equal(edges[1].target, "a");
assert.equal(edges[2].target, "#failure");
assert.equal(edges[3].target, "#success");
});
test("edgeLabel marks only an implicit fallback error route with error*", () => {
assert.equal(edgeLabel({ fallback_error: true }, "error"), "error*");
assert.equal(edgeLabel({ fallback_error: false }, "error"), "error");
assert.equal(edgeLabel({ fallback_error: true }, "success"), "success");
assert.equal(edgeLabel({}, "rejected"), "rejected");
});
test("nodeDisplayLabel keeps a stage key and reads Success/Failure for terminals", () => {
assert.equal(nodeDisplayLabel("#success"), "Success");
assert.equal(nodeDisplayLabel("#failure"), "Failure");
assert.equal(nodeDisplayLabel("ui_reviewer"), "ui_reviewer");
});
// ---------------------------------------------------------------------------
// Node kinds (GraphPalette)
// ---------------------------------------------------------------------------
test("graphNodeKind maps terminals and the effective stage type", () => {
assert.equal(graphNodeKind(true, "#failure", undefined), "TerminalFailure");
assert.equal(graphNodeKind(true, "#success", "model"), "TerminalSuccess");
assert.equal(graphNodeKind(false, "a", "ntfy"), "Ntfy");
assert.equal(graphNodeKind(false, "a", ""), "Model");
assert.equal(graphNodeKind(false, "a", undefined), "Model");
assert.equal(graphNodeKind(false, "a", "model"), "Model");
assert.equal(graphNodeKind(false, "a", "shell"), "Custom");
});
test("nodeKindClass names a distinct fill for every kind", () => {
const classes = ["TerminalSuccess", "TerminalFailure", "Model", "Ntfy", "Custom"].map(
nodeKindClass,
);
assert.equal(new Set(classes).size, classes.length);
assert.equal(nodeKindClass("Ntfy"), "graph-node-ntfy");
assert.equal(nodeKindClass("Custom"), "graph-node-custom");
});
// ---------------------------------------------------------------------------
// Layout
// ---------------------------------------------------------------------------
test("layoutGraph keeps stage nodes in declaration order on one row", () => {
const layout = layoutGraph(twoStageGraph());
const stages = layout.nodes.filter((node) => !node.terminal);
assert.deepEqual(
stages.map((node) => node.key),
["plan", "impl"],
);
assert.equal(stages[0].y, stages[1].y);
assert.ok(stages[0].x < stages[1].x);
assert.ok(layout.width > 0 && layout.height > 0);
});
test("layoutGraph puts the terminals on one lower row with Failure left of Success", () => {
const layout = layoutGraph(twoStageGraph());
const failure = layout.nodes.find((node) => node.key === "#failure");
const success = layout.nodes.find((node) => node.key === "#success");
const stage = layout.nodes.find((node) => node.key === "plan");
assert.ok(failure && success, "both terminals are laid out");
assert.equal(failure.y, success.y);
assert.ok(failure.y > stage.y, "the terminal row sits below the stage row");
assert.ok(failure.x < success.x, "Failure is left of Success");
assert.ok(failure.terminal && success.terminal);
assert.deepEqual(
layout.nodes.slice(-2).map((node) => node.key),
["#failure", "#success"],
);
});
test("layoutGraph spreads every non-forward edge onto its own lane in id order", () => {
const graph = {
stages: [
{ key: "a", edges: { success: "b", rejected: "#success" } },
{ key: "b", edges: { success: "#success", rejected: "a" } },
],
};
const layout = layoutGraph(graph);
const laned = layout.edges.filter((edge) => edge.laneIndex >= 0);
// a→#success, b→#success (top entries) and b→a (an across loop).
assert.equal(laned.length, 3);
assert.deepEqual(
laned.map((edge) => edge.laneIndex),
[0, 1, 2],
);
assert.equal(new Set(laned.map((edge) => edge.lane)).size, laned.length, "distinct lanes");
assert.deepEqual(
laned.map((edge) => edge.id),
[...laned.map((edge) => edge.id)].sort((x, y) => x - y),
"lanes are allocated in stable edge-id order",
);
// A straight forward route keeps a single horizontal segment.
const forward = layout.edges.find((edge) => edge.source === "a" && edge.outcome === "success");
assert.equal(forward.forward, true);
assert.equal(forward.laneIndex, -1);
assert.equal(forward.points.length, 2);
});
test("layoutGraph labels sit on the edge's own widest horizontal run", () => {
const layout = layoutGraph(twoStageGraph());
for (const edge of layout.edges) {
assert.ok(Number.isFinite(edge.labelPoint.x) && Number.isFinite(edge.labelPoint.y));
}
});
test("layoutGraph is empty and finite for a graph with no stages", () => {
const layout = layoutGraph({ stages: [] });
assert.deepEqual(layout.nodes, []);
assert.deepEqual(layout.edges, []);
assert.equal(layout.width, 0);
assert.equal(layout.height, 0);
});
test("hitTest returns the node key under a graph-space point, else null", () => {
const layout = layoutGraph(twoStageGraph());
const node = layout.nodes[0];
assert.equal(hitTest(layout, { x: node.x + 1, y: node.y + 1 }), node.key);
assert.equal(hitTest(layout, { x: -1000, y: -1000 }), null);
});
test("graphDescription names the stage count", () => {
assert.equal(graphDescription({ stages: [] }), "Empty workflow graph");
assert.equal(
graphDescription({ stages: [{ key: "a" }] }),
"Workflow graph with 1 stage. Stages can be opened for details.",
);
});
// ---------------------------------------------------------------------------
// Viewport maths (WorkflowGraph.kt)
// ---------------------------------------------------------------------------
test("fitScale shrinks oversized content, uses the tighter axis and never upscales", () => {
assert.equal(fitScale({ width: 1000, height: 400 }, { width: 2000, height: 400 }, 0), 0.5);
assert.equal(fitScale({ width: 1000, height: 800 }, { width: 2000, height: 2000 }, 0), 0.4);
assert.equal(fitScale({ width: 1000, height: 800 }, { width: 200, height: 100 }, 0), 1);
});
test("fitScale accounts for padding and floors no lower than MIN_SCALE", () => {
assert.equal(fitScale({ width: 1000, height: 400 }, { width: 2000, height: 400 }, 100), 0.4);
assert.equal(fitScale({ width: 100, height: 100 }, { width: 100000, height: 100000 }, 0), MIN_SCALE);
});
test("fitScale is finite for degenerate sizes", () => {
assert.equal(fitScale({ width: 0, height: 0 }, { width: 100, height: 100 }, 0), 1);
assert.equal(fitScale({ width: 100, height: 100 }, { width: 0, height: 0 }, 0), 1);
assert.equal(fitScale({ width: 100, height: 100 }, { width: -5, height: 10 }, 0), 1);
assert.ok(Number.isFinite(fitScale({ width: 100, height: 100 }, { width: 100, height: 100 }, 60)));
assert.ok(Number.isFinite(fitScale({}, {}, 0)));
});
test("clampOffset keeps content visible at every extreme", () => {
const content = { width: 400, height: 300 };
const viewport = { width: 1000, height: 800 };
const margin = 40;
const far = clampOffset({ x: -10000, y: -10000 }, content, viewport, margin);
assert.equal(far.x, margin - content.width);
assert.equal(far.y, margin - content.height);
const near = clampOffset({ x: 10000, y: 10000 }, content, viewport, margin);
assert.equal(near.x, viewport.width - margin);
assert.equal(near.y, viewport.height - margin);
});
test("clampOffset leaves a centred small graph unchanged", () => {
const content = { width: 400, height: 300 };
const viewport = { width: 1000, height: 800 };
const centred = { x: (viewport.width - content.width) / 2, y: (viewport.height - content.height) / 2 };
assert.deepEqual(clampOffset(centred, content, viewport, 40), centred);
});
test("clampOffset is symmetric and safe for degenerate sizes", () => {
const content = { width: 500, height: 500 };
const viewport = { width: 1000, height: 800 };
const left = clampOffset({ x: -99999, y: 0 }, content, viewport, 40).x;
const right = clampOffset({ x: 99999, y: 0 }, content, viewport, 40).x;
assert.equal(left, -content.width + 40);
assert.equal(right, viewport.width - 40);
assert.deepEqual(clampOffset({ x: 0, y: 0 }, { width: 0, height: 0 }, viewport, 40), {
x: 0,
y: 0,
});
assert.ok(Number.isFinite(clampOffset({ x: 1, y: 2 }, content, { width: 10, height: 10 }, 40).x));
assert.ok(Number.isFinite(clampOffset({ x: NaN, y: NaN }, content, viewport, 40).x));
});
test("zoomAbout keeps the content point under the centroid fixed", () => {
const result = zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 100 }, 1.6);
assert.equal(result.scale, 1.6);
assert.equal(result.offset.x, 50 - 50 * 1.6);
assert.equal(result.offset.y, 100 - 100 * 1.6);
});
test("zoomAbout clamps the scale to [0.3, 3.0] at both extremes", () => {
assert.equal(zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 50 }, 9).scale, MAX_SCALE);
assert.equal(zoomAbout({ x: 0, y: 0 }, 1, { x: 50, y: 50 }, 0.01).scale, MIN_SCALE);
assert.equal(MAX_SCALE, 3.0);
assert.equal(MIN_SCALE, 0.3);
});
test("zoomAbout is finite and unchanged for degenerate scale/zoom", () => {
const offset = { x: 20, y: 30 };
const degenerate = zoomAbout(offset, 0, { x: 100, y: 100 }, 1.5);
assert.deepEqual(degenerate.offset, offset);
assert.equal(degenerate.scale, 0);
const purePan = zoomAbout(offset, 0.5, { x: 80, y: 60 }, 1);
assert.ok(Number.isFinite(purePan.offset.x) && Number.isFinite(purePan.scale));
const negative = zoomAbout(offset, 0.5, { x: 80, y: 60 }, -2);
assert.deepEqual(negative.offset, offset);
assert.equal(negative.scale, 0.5);
});
test("toGraphPoint inverts the translate+scale transform", () => {
assert.deepEqual(toGraphPoint({ x: 150, y: 210 }, { x: 50, y: 10 }, 2), { x: 50, y: 100 });
assert.deepEqual(toGraphPoint({ x: 150, y: 210 }, { x: 50, y: 10 }, 0), { x: 0, y: 0 });
});
// ---------------------------------------------------------------------------
// Stage definition pane (StageDetailPane.kt)
// ---------------------------------------------------------------------------
test("stageDefinitionFields mirrors the app's labels and omits blanks", () => {
const fields = stageDefinitionFields({
type: "",
prompt: "",
output: "the result",
edges: { success: "#success", error: "#" },
fallback_error: true,
configs: { provider: "anthropic", empty: "" },
limits: { max_visits: 3, on: ["failed"] },
memory: { notes: "here" },
notify: { on: ["failed"], destination: "phone", artifacts: ["log"] },
blocks: { tools: "read, write" },
});
const labels = fields.map((entry) => entry.label);
assert.deepEqual(labels, [
"Type",
"Output",
"Outcomes",
"Provider",
"Tools",
"Max visits",
"Limit on",
"Memory",
"Notify on",
"Notify destination",
"Notify artifacts",
]);
assert.equal(fields[0].value, "model", "a blank type is the model stage");
const outcomes = fields.find((entry) => entry.label === "Outcomes");
assert.equal(outcomes.value, "success \u2192 SUCCESS (terminal)\nerror \u2192 FAILURE (terminal)");
assert.equal(outcomes.block, true);
assert.equal(fields.find((entry) => entry.label === "Memory").value, "notes: here");
assert.ok(!labels.includes("Empty"), "a blank config is omitted");
});
test("configLabel spells the app's config vocabulary", () => {
assert.equal(configLabel("provider"), "Provider");
assert.equal(configLabel("model"), "Model");
assert.equal(configLabel("retries"), "Retries");
assert.equal(configLabel("timeout"), "Timeout");
assert.equal(configLabel("budget_usd"), "Budget (USD)");
assert.equal(configLabel("budget_tokens"), "Budget (tokens)");
assert.equal(configLabel("harness"), "Harness");
assert.equal(configLabel("other"), "other");
});
test("terminalFields lists the incoming routes into a terminal", () => {
const fields = terminalFields(twoStageGraph(), "#success");
assert.equal(fields.length, 1);
assert.equal(fields[0].label, "Incoming routes");
assert.equal(fields[0].value, "impl \u00b7 success \u2192 SUCCESS");
assert.equal(fields[0].block, true);
assert.deepEqual(terminalFields(twoStageGraph(), "#nope"), []);
});
// ---------------------------------------------------------------------------
// Run-mode execution state (R5: GraphSemantics RunGraphState.from)
// ---------------------------------------------------------------------------
test("runGraphState resolves visited stages, taken routes and reached terminals", () => {
const run = {
executing: false,
current_stage: "committer",
steps: [
{ stage: "implementer", sequence: 1, status: "completed", outcome: "success", target: "reviewer" },
{ stage: "reviewer", sequence: 2, status: "completed", outcome: "rejected", target: "implementer" },
{ stage: "implementer", sequence: 3, status: "completed", outcome: "success", target: "reviewer" },
{ stage: "committer", sequence: 4, status: "completed", outcome: "success", target: "#success" },
],
};
const state = runGraphState(run);
assert.deepEqual(state.visitedStages, ["implementer", "reviewer", "committer", "#success"]);
assert.equal(state.currentStage, "committer");
assert.equal(state.executing, false);
assert.equal(state.currentStageStartedAt, null);
assert.deepEqual(state.takenRoutes, [
"implementer\u0000success\u0000reviewer",
"reviewer\u0000rejected\u0000implementer",
"committer\u0000success\u0000#success",
]);
});
test("runGraphState marks a terminal only when a visit resolved to it", () => {
// A `#` target resolves by outcome: error -> #failure, everything else -> #success.
const failed = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "error", target: "#" }],
});
assert.deepEqual(failed.visitedStages, ["impl", "#failure"]);
assert.equal(stageIsExecuted("#failure", failed), true);
assert.equal(stageIsExecuted("#success", failed), false);
const midRun = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "success", target: "review" }],
});
assert.equal(stageIsExecuted("#success", midRun), false);
assert.equal(stageIsExecuted("#failure", midRun), false);
assert.equal(stageIsExecuted("review", midRun), false, "a target is not visited until a step lands on it");
});
test("stageIsExecuted is true for a visited stage and for the definition view", () => {
const state = runGraphState({
executing: false,
steps: [{ stage: "impl", outcome: "success", target: "review" }],
});
assert.equal(stageIsExecuted("impl", state), true);
assert.equal(stageIsExecuted("review", state), false);
// The definition view passes no runState, so every stage is executed.
assert.equal(stageIsExecuted("review", null), true);
});
test("edgeIsExecuted is true only for a route a recorded visit produced", () => {
const state = runGraphState({
executing: false,
steps: [
{ stage: "impl", outcome: "success", target: "review" },
{ stage: "review", outcome: "error", target: "#" },
],
});
const taken = { source: "impl", outcome: "success", target: "review" };
const byFallback = { source: "review", outcome: "error", target: "#failure" };
const untaken = { source: "impl", outcome: "blocked", target: "#failure" };
assert.equal(edgeIsExecuted(taken, state), true);
assert.equal(edgeIsExecuted(byFallback, state), true, "a resolved fallback route counts");
assert.equal(edgeIsExecuted(untaken, state), false);
// The definition view draws every route executed.
assert.equal(edgeIsExecuted(untaken, null), true);
});
test("activeStage resolves only while the run is executing", () => {
const live = runGraphState({
executing: true,
current_stage: "review",
steps: [
{ stage: "review", status: "running", started_at: "2026-01-01T00:00:00Z" },
],
});
assert.equal(activeStage(live), "review");
assert.equal(live.currentStageStartedAt, "2026-01-01T00:00:00Z");
const settled = runGraphState({
executing: false,
current_stage: "review",
steps: [
{ stage: "review", status: "running", started_at: "2026-01-01T00:00:00Z" },
],
});
assert.equal(activeStage(settled), null, "a finished run has no active stage");
assert.equal(settled.currentStageStartedAt, null);
assert.equal(activeStage(null), null, "the definition view has no active stage");
});
test("runGraphState falls back to the last visit's stage, else null", () => {
const state = runGraphState({ executing: false, steps: [{ stage: "a" }, { stage: "b" }] });
assert.equal(state.currentStage, "b");
assert.equal(runGraphState({ executing: false, steps: [] }).currentStage, null);
assert.equal(runGraphState({}).currentStage, null);
});
// ---------------------------------------------------------------------------
// Wording, exports and the no-innerHTML contract
// ---------------------------------------------------------------------------
test("the empty-state and pane wording matches the app's sentences", () => {
assert.equal(RUN_GRAPH_MISSING, "This server did not include the run graph.");
assert.equal(PIPELINE_GRAPH_EMPTY, "This pipeline has no stages.");
assert.equal(NO_NODE_DETAILS, "No details recorded for this node.");
assert.equal(STAGE_DEFINITION_TITLE, "Stage definition");
});
test("mount is exported and returns an unmount handle", () => {
assert.equal(typeof mount, "function");
});
test("graph.js never uses innerHTML and writes server strings with textContent", () => {
const source = readFileSync(new URL("../src/graph.js", import.meta.url), "utf8");
assert.ok(!source.includes("innerHTML"), "the graph never assigns innerHTML");
assert.ok(!source.includes("outerHTML"), "the graph never assigns outerHTML");
assert.ok(!source.includes("insertAdjacentHTML"), "no HTML is parsed from a string");
});