Merge branch 'main' into web-run-tabs

This commit is contained in:
2026-10-19 03:32:34 +01:00
6 changed files with 2052 additions and 6 deletions
+2 -2
View File
@@ -23,10 +23,10 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu
| --- | --- | --- | --- | | --- | --- | --- | --- |
| P1 | Pipeline list | `list_pipelines` | done — row: name; `id {id} · v{version} · {N stages}`; `updated d MMM HH:mm`; last-run line joined from `list_runs` (status chip + `{ago} · {duration} · run {id}`, or `no runs recorded`) | | P1 | Pipeline list | `list_pipelines` | done — row: name; `id {id} · v{version} · {N stages}`; `updated d MMM HH:mm`; last-run line joined from `list_runs` (status chip + `{ago} · {duration} · run {id}`, or `no runs recorded`) |
| P2 | Filter + sort (status/name/updated) | client-side | done — Filter menu (name contains, Runs Any/Has runs/No runs, Last run status over the 7 server states, Clear filters) + Sort menu (Server order default, Name A–Z/Z–A, Most recent run, Fewest/Most stages, Reset); server order preserved | | P2 | Filter + sort (status/name/updated) | client-side | done — Filter menu (name contains, Runs Any/Has runs/No runs, Last run status over the 7 server states, Clear filters) + Sort menu (Server order default, Name A–Z/Z–A, Most recent run, Fewest/Most stages, Reset); server order preserved |
| P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | done — Summary/Graph/Source tabs; Summary shows content hash (monospace), latest version (`v{n}` or blank), created/updated, and a collapsed-by-default Versions section. Graph tab shows the browser guidance note only; the rendered graph is P6 | | P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | done — Summary/Graph/Source tabs; Summary shows content hash (monospace), latest version (`v{n}` or blank), created/updated, and a collapsed-by-default Versions section. Graph tab shows the browser guidance note plus the rendered workflow graph (P6) |
| P4 | Templates gallery + template detail | `list_templates`, `validate` | done | | P4 | Templates gallery + template detail | `list_templates`, `validate` | done |
| P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | todo | | P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | todo |
| P6 | Workflow graph rendering (nodes, edges, stage panes) | `get_pipeline` | todo | | P6 | Workflow graph rendering (nodes, edges, stage panes) | `get_pipeline` | done (captured 2026-10-19: nodes + labelled outcome edges + success/failure terminals, an opened stage definition pane and the expanded view — `captures/08-pipeline-graph.png`, `captures/08a-pipeline-graph-stage-pane.png`, `captures/08b-pipeline-graph-expanded.png`). Reusable `src/graph.js` (`mount` + pure helpers: layout, edges, `error*`, lanes, fit/clamp/zoom, hit-test, stage-definition fields); definition view only, so R5's run-detail Graph tab stays todo. Pane labels match the app's own vocabulary (`Outcomes`, `Tools`) rather than the checklist's category words |
## Runs ## Runs
| # | Feature | Protocol | Status | | # | Feature | Protocol | Status |
+28
View File
@@ -22,6 +22,10 @@ import {
sessionExportArtifact, sessionExportArtifact,
viewerIndexByUrl, viewerIndexByUrl,
} from "./artifacts.js"; } from "./artifacts.js";
import {
PIPELINE_GRAPH_EMPTY,
mount as mountGraph,
} from "./graph.js";
import { import {
PIPELINE_SORTS, PIPELINE_SORTS,
PIPELINE_DETAIL_TABS, PIPELINE_DETAIL_TABS,
@@ -134,6 +138,10 @@ const state = {
pipelineSort: "server_order", pipelineSort: "server_order",
pipelineMenu: null, pipelineMenu: null,
pipelineTab: "summary", pipelineTab: "summary",
// The mounted workflow graph (P6) and whether its panel is expanded. The
// handle is dropped on every re-render so its listeners can never leak.
pipelineGraph: null,
pipelineGraphExpanded: false,
versionsExpanded: false, versionsExpanded: false,
pipelinesLoaded: false, pipelinesLoaded: false,
runsLoaded: false, runsLoaded: false,
@@ -253,6 +261,13 @@ function render() {
} }
function renderContent() { function renderContent() {
// The graph owns wheel/pointer/resize listeners; drop the previous mount
// before rebuilding the DOM so a re-render, tab switch or view switch never
// leaves an observer or listener behind.
if (state.pipelineGraph) {
state.pipelineGraph.unmount();
state.pipelineGraph = null;
}
const nodes = []; const nodes = [];
if (state.error) { if (state.error) {
nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error)); nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error));
@@ -561,6 +576,19 @@ function renderPipelineDetail() {
); );
if (state.pipelineTab === "graph") { if (state.pipelineTab === "graph") {
pane.append(h("p", { class: "graph-note muted", text: graphNote() })); pane.append(h("p", { class: "graph-note muted", text: graphNote() }));
const stages = d.graph?.stages ?? [];
if (!stages.length) {
pane.append(h("div", { class: "muted pad", text: PIPELINE_GRAPH_EMPTY }));
return pane;
}
const host = h("div", { class: "graph-host" });
pane.append(host);
state.pipelineGraph = mountGraph(host, d.graph, {
expanded: state.pipelineGraphExpanded,
onExpandedChange: (value) => {
state.pipelineGraphExpanded = value;
},
});
return pane; return pane;
} }
if (state.pipelineTab === "source") { if (state.pipelineTab === "source") {
+1245
View File
File diff suppressed because it is too large Load Diff
+159
View File
@@ -506,6 +506,165 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
.graph-note { margin: 0; max-width: 60ch; } .graph-note { margin: 0; max-width: 60ch; }
/* The workflow graph (P6): a mounted, pannable/zoomable canvas of stage nodes,
labelled outcome edges and the success/failure terminals, plus the definition
pane opened from a node. Hand-written, dark-first, no runtime dependency. */
.graph-host { margin-top: 12px; }
.graph-panel { display: grid; gap: 12px; }
.graph-panel.expanded .graph-viewport { height: 78vh; }
.graph-viewport {
position: relative;
height: 440px;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface);
cursor: grab;
/* A drag pans the graph instead of scrolling the page or selecting text. */
touch-action: none;
user-select: none;
}
.graph-viewport:active { cursor: grabbing; }
/* One transformed layer: pan/zoom only rewrite this element's transform. */
.graph-content { position: absolute; top: 0; left: 0; will-change: transform; }
.graph-edges { position: absolute; top: 0; left: 0; overflow: visible; pointer-events: none; }
.graph-edge-path { stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.graph-edge-path.not-executed { stroke-width: 2.5; stroke-dasharray: 14 10; }
.graph-arrowhead path { fill: var(--text); fill: context-stroke; }
.graph-node-layer, .graph-label-layer { position: absolute; top: 0; left: 0; }
.graph-label-layer { pointer-events: none; }
.graph-node {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface-2);
color: var(--text);
font: inherit;
font-size: 13px;
font-weight: 600;
text-align: center;
overflow-wrap: anywhere;
cursor: pointer;
}
.graph-node:hover { border-color: var(--accent); }
.graph-node.selected { border-color: var(--accent); box-shadow: inset 0 0 0 2px var(--accent); }
/* Node fills convey type: model neutral, ntfy amber, other/custom green. */
.graph-node-ntfy {
background: color-mix(in srgb, var(--warn) 22%, var(--surface-2));
border-color: color-mix(in srgb, var(--warn) 42%, var(--border));
}
.graph-node-custom {
background: color-mix(in srgb, var(--ok) 18%, var(--surface-2));
border-color: color-mix(in srgb, var(--ok) 38%, var(--border));
}
/* Terminals are pills tinted by outcome, so they read as endpoints, not stages. */
.graph-node-terminal-success,
.graph-node-terminal-failure { border-radius: 999px; }
.graph-node-terminal-success {
background: color-mix(in srgb, var(--ok) 30%, var(--surface-2));
border-color: var(--ok);
color: var(--ok);
}
.graph-node-terminal-failure {
background: color-mix(in srgb, var(--bad) 30%, var(--surface-2));
border-color: var(--bad);
color: var(--bad);
}
/* Not executed (R5 only): hollow, dashed and muted, never a faded fill. */
.graph-node.not-executed {
background: transparent;
border-style: dashed;
color: var(--muted);
}
.graph-edge-label {
position: absolute;
transform: translate(-50%, -100%);
padding: 1px 6px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--surface-2);
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.graph-controls { position: absolute; top: 8px; right: 8px; z-index: 2; display: flex; gap: 6px; }
.graph-control {
padding: 4px 10px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface);
color: var(--text);
font-size: 12px;
}
.graph-control:hover { border-color: var(--accent); color: var(--accent); }
/* The definition pane opened from a node click. */
.graph-pane {
display: grid;
gap: 8px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--surface);
}
.graph-pane[hidden] { display: none; }
.graph-pane-head { display: flex; align-items: center; gap: 8px; }
.graph-pane-title { margin: 0; font-size: 15px; }
.graph-type-chip {
padding: 2px 8px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--surface-2);
color: var(--accent);
font-size: 11px;
}
.graph-pane-close { margin-left: auto; padding: 3px 10px; font-size: 12px; }
.graph-pane-empty { margin: 0; }
.graph-section-toggle {
display: flex;
gap: 8px;
align-items: center;
width: 100%;
padding: 8px 10px;
border: 0;
border-radius: 8px;
background: var(--surface-2);
color: var(--text);
font-weight: 600;
text-align: left;
}
.graph-section-body { display: grid; gap: 6px; padding: 8px 2px 0; }
.graph-field { display: grid; grid-template-columns: minmax(120px, 200px) 1fr; gap: 10px; align-items: baseline; }
.graph-field-label { color: var(--muted); font-size: 12px; }
.graph-field-value { font-size: 13px; overflow-wrap: anywhere; }
.graph-field-block { grid-template-columns: 1fr; }
.graph-block {
margin: 4px 0 0;
padding: 8px 10px;
max-height: 260px;
overflow: auto;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--surface-2);
color: var(--text);
font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
white-space: pre-wrap;
word-break: break-word;
}
/* The waiting / canceled / interrupted hues are set once above, next to the /* The waiting / canceled / interrupted hues are set once above, next to the
other status chips, so RunStatusPalette stays the single source of truth for other status chips, so RunStatusPalette stays the single source of truth for
every status word. */ every status word. */
+392
View File
@@ -0,0 +1,392 @@
// 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,
} from "../src/graph.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"), []);
});
// ---------------------------------------------------------------------------
// 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");
});
+226 -4
View File
@@ -54,6 +54,71 @@ async function shot(name) {
const text = (selector) => const text = (selector) =>
page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent ?? ""`); page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent ?? ""`);
// The mounted graph's current transform, read back so the pan/zoom clamp checks
// assert the real rendered state rather than a claim.
const graphState = () =>
page.evaluate(`(() => {
const content = document.querySelector(".graph-content");
const viewport = document.querySelector(".graph-viewport");
if (!content || !viewport) return null;
const m = /translate\\(([-0-9.]+)px, ([-0-9.]+)px\\) scale\\(([-0-9.]+)\\)/.exec(
content.style.transform,
);
if (!m) return null;
return {
tx: Number(m[1]),
ty: Number(m[2]),
scale: Number(m[3]),
width: parseFloat(content.style.width),
height: parseFloat(content.style.height),
viewportWidth: viewport.clientWidth,
viewportHeight: viewport.clientHeight,
};
})()`);
// Dispatch real wheel events at the viewport centre (the page handler is
// `{ passive: false }` and prevents default, so a synthetic event exercises the
// same clamp path a user gesture does).
const wheel = (deltaY, times) =>
page.evaluate(`(() => {
const viewport = document.querySelector(".graph-viewport");
const r = viewport.getBoundingClientRect();
for (let i = 0; i < ${times}; i += 1) {
viewport.dispatchEvent(new WheelEvent("wheel", {
bubbles: true,
cancelable: true,
deltaY: ${deltaY},
clientX: r.left + r.width / 2,
clientY: r.top + r.height / 2,
}));
}
return true;
})()`);
// Dispatch a real pointer drag across the viewport.
const drag = (dx, dy) =>
page.evaluate(`(() => {
const viewport = document.querySelector(".graph-viewport");
const r = viewport.getBoundingClientRect();
const fire = (type, x, y) => viewport.dispatchEvent(new PointerEvent(type, {
bubbles: true,
cancelable: true,
pointerId: 7,
button: 0,
buttons: type === "pointerup" ? 0 : 1,
clientX: x,
clientY: y,
}));
const startX = r.left + r.width / 2;
const startY = r.top + r.height / 2;
fire("pointerdown", startX, startY);
for (let i = 1; i <= 20; i += 1) {
fire("pointermove", startX + (${dx} * i) / 20, startY + (${dy} * i) / 20);
}
fire("pointerup", startX + ${dx}, startY + ${dy});
return true;
})()`);
try { try {
await mkdir(out, { recursive: true }); await mkdir(out, { recursive: true });
@@ -138,8 +203,22 @@ try {
await page.click("#filterToggle"); await page.click("#filterToggle");
// 5. Pipeline detail: Summary (name, subtitle, content hash, created/updated). // 5. Pipeline detail: Summary (name, subtitle, content hash, created/updated).
step("opening a pipeline detail (Summary)"); // Prefer a multi-stage pipeline so the Graph tab below has a real layout to
await page.click("#pipelineRows button.row"); // render; fall back to whatever the server lists first.
step("opening a multi-stage pipeline detail (Summary)");
const openedPipeline = await page.evaluate(`(() => {
const rows = [...document.querySelectorAll("#pipelineRows button.row")];
const wanted = rows.find((row) => row.textContent.includes("Plan and land")) ?? rows[0];
if (!wanted) return null;
wanted.setAttribute("data-test-click", "1");
return wanted.textContent.includes("Plan and land") ? "Plan and land" : "first row";
})()`);
if (!openedPipeline) throw new Error("no pipeline row to open");
console.log(` opened pipeline: ${openedPipeline}`);
await page.click("[data-test-click='1']");
await page.evaluate(
`document.querySelector("[data-test-click='1']")?.removeAttribute("data-test-click")`,
);
await page.waitForSelector(".detail h2"); await page.waitForSelector(".detail h2");
await page.waitForSelector(".monospace"); await page.waitForSelector(".monospace");
await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`); await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`);
@@ -159,12 +238,155 @@ try {
await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`); await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`);
await shot("07-pipeline-source.png"); await shot("07-pipeline-source.png");
// 8. Graph tab: the guidance note only; the rendered graph is P6. // 8. Graph tab (P6): the guidance note plus the rendered workflow graph —
step("opening the Graph tab (guidance note only)"); // stage nodes in declaration order, labelled outcome edges, the success and
// failure terminals — then an opened definition pane, the zoom/pan clamps and
// the expanded panel. Every assertion below is a real behaviour of the page.
step("opening the Graph tab: the rendered workflow graph (P6)");
await page.clickText(".detail-tabs button", "Graph"); await page.clickText(".detail-tabs button", "Graph");
await page.waitForSelector(".graph-note"); await page.waitForSelector(".graph-note");
await page.waitForSelector(".graph-viewport");
await page.waitForSelector(".graph-node");
// Auto-fit runs on the first layout (after the host is attached), so wait for
// the whole graph to sit inside the viewport before asserting.
await eventually(
async () => {
const current = await graphState();
if (!current || !(current.scale > 0)) return false;
const scaledWidth = current.width * current.scale;
const scaledHeight = current.height * current.scale;
return (
current.tx >= -0.5 &&
current.ty >= -0.5 &&
current.tx + scaledWidth <= current.viewportWidth + 0.5 &&
current.ty + scaledHeight <= current.viewportHeight + 0.5
);
},
{ what: "the graph to be auto-fitted into the viewport" },
);
const note = await text(".graph-note");
if (!note.includes("Mouse wheel to zoom, drag to pan, click a stage for details.")) {
throw new Error(`unexpected graph guidance note: ${note}`);
}
const graphCounts = await page.evaluate(`(() => ({
nodes: document.querySelectorAll(".graph-node").length,
stages: document.querySelectorAll(".graph-node:not([class*='terminal'])").length,
edges: document.querySelectorAll(".graph-edge-path").length,
labels: [...document.querySelectorAll(".graph-edge-label")].map((n) => n.textContent),
failure: !!document.querySelector(".graph-node-terminal-failure"),
success: !!document.querySelector(".graph-node-terminal-success"),
}))()`);
if (!graphCounts.stages || !graphCounts.edges || !graphCounts.labels.length) {
throw new Error(`the graph did not render nodes/edges/labels: ${JSON.stringify(graphCounts)}`);
}
if (!graphCounts.failure || !graphCounts.success) {
throw new Error(`the graph is missing a terminal: ${JSON.stringify(graphCounts)}`);
}
const fitted = await graphState();
if (!(fitted && fitted.scale > 0 && fitted.scale <= 1 + 1e-6)) {
throw new Error(`the graph was not auto-fitted: ${JSON.stringify(fitted)}`);
}
console.log(
` graph: ${graphCounts.stages} stages, ${graphCounts.edges} edges, ` +
`${graphCounts.nodes} nodes, labels ${graphCounts.labels.join(",")}; fitted at ${fitted.scale.toFixed(2)}`,
);
await shot("08-pipeline-graph.png"); await shot("08-pipeline-graph.png");
// Clicking empty space must do nothing; clicking a stage opens its pane.
step("checking empty-space click and opening a stage's definition pane");
await page.evaluate(`document.querySelector(".graph-viewport")?.click()`);
const paneOnEmpty = await page.evaluate(
`(() => { const p = document.querySelector(".graph-pane"); return !!p && !p.hidden; })()`,
);
if (paneOnEmpty) throw new Error("clicking empty space opened the stage pane");
await page.click(".graph-node-model");
await page.waitForSelector(".graph-pane:not([hidden])");
const pane = await page.evaluate(`(() => {
const p = document.querySelector(".graph-pane");
return {
text: p.textContent,
key: document.querySelector(".graph-node-model")?.dataset.key ?? "",
type: document.querySelector(".graph-type-chip")?.textContent ?? "",
fields: document.querySelectorAll(".graph-pane .graph-field").length,
};
})()`);
if (!pane.key || !pane.text.includes(pane.key)) {
throw new Error(`the pane did not name the stage key (${pane.key}): ${pane.text.slice(0, 120)}`);
}
if (!pane.type) throw new Error("the pane did not show the stage type");
if (!pane.text.includes("Stage definition") || !pane.fields) {
throw new Error(`the pane has no Stage definition fields: ${pane.text.slice(0, 120)}`);
}
await page.rect(".graph-pane");
await shot("08a-pipeline-graph-stage-pane.png");
console.log(` stage pane: ${pane.key} (${pane.type}), ${pane.fields} definition field(s)`);
// Wheel zoom clamps to [0.3, 3.0]; a drag can never leave an empty viewport.
step("exercising wheel-zoom clamps, drag clamping and Fit");
await wheel(400, 60);
const zoomedOut = await graphState();
if (!(Math.abs(zoomedOut.scale - 0.3) < 1e-6)) {
throw new Error(`zoom-out was not clamped to 0.3: ${zoomedOut.scale}`);
}
await wheel(-400, 60);
const zoomedIn = await graphState();
if (!(Math.abs(zoomedIn.scale - 3.0) < 1e-6)) {
throw new Error(`zoom-in was not clamped to 3.0: ${zoomedIn.scale}`);
}
await drag(4000, 3000);
const panned = await graphState();
const visibleX =
Math.min(panned.tx + panned.width * panned.scale, panned.viewportWidth) -
Math.max(panned.tx, 0);
const visibleY =
Math.min(panned.ty + panned.height * panned.scale, panned.viewportHeight) -
Math.max(panned.ty, 0);
if (visibleX < 39.5 || visibleY < 39.5) {
throw new Error(`panning left an empty viewport: visible ${visibleX}x${visibleY}`);
}
await page.clickText(".graph-control", "Fit graph to view");
const refitted = await graphState();
if (!(refitted.scale >= 0.3 && refitted.scale <= 1 + 1e-6)) {
throw new Error(`Fit did not re-fit the graph: ${refitted.scale}`);
}
console.log(
` zoom clamp 0.3..3.0 ok; after a 4000x3000 drag the viewport still shows ` +
`${Math.round(visibleX)}x${Math.round(visibleY)}px; Fit re-fitted to ${refitted.scale.toFixed(2)}`,
);
step("expanding the graph panel");
await page.clickText(".graph-control", "Expand graph");
await page.waitForText("Collapse graph");
const expandedHeight = await page.evaluate(
`document.querySelector(".graph-viewport").clientHeight`,
);
await page.rect(".graph-viewport");
await shot("08b-pipeline-graph-expanded.png");
console.log(` expanded graph viewport height: ${expandedHeight}px`);
await page.clickText(".graph-control", "Collapse graph");
step("checking a node with no stage shows the app's empty pane message");
const noDetails = await page.evaluate(`(async () => {
const { mount } = await import("/src/graph.js");
const host = document.createElement("div");
host.style.cssText = "position:fixed;left:-2400px;top:0;width:600px;height:300px";
document.body.append(host);
const graph = { stages: [{ key: "alpha", type: "model", edges: { success: "#success" } }] };
const handle = mount(host, graph, {});
host.querySelector(".graph-node-terminal-failure").click();
const text = host.querySelector(".graph-pane").textContent;
handle.unmount();
const emptyAfterUnmount = host.childElementCount === 0;
host.remove();
return { text, emptyAfterUnmount };
})()`);
if (!noDetails.text.includes("No details recorded for this node.")) {
throw new Error(`a stage-less node did not show the empty message: ${noDetails.text}`);
}
if (!noDetails.emptyAfterUnmount) throw new Error("unmount left the graph DOM behind");
console.log(" a node with no stage reads: No details recorded for this node.");
step("switching to Runs: day-grouped list + usage roll-up"); step("switching to Runs: day-grouped list + usage roll-up");
await page.clickText("nav.tabs button.tab", "Runs"); await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .day-header", { timeout: 25000 }); await page.waitForSelector(".list.runs .day-header", { timeout: 25000 });