web: open authored stage definitions in managed graph popup

This commit is contained in:
2026-10-20 17:35:13 +01:00
parent ae69e03157
commit f31806cfcb
18 changed files with 273 additions and 15 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+22
View File
@@ -32,6 +32,28 @@ through the real button at 1100px, and checks the rail remains hidden at
390/420px. Captures: `rail-collapsed-1100.png`, `rail-expanded-1100.png` in the 390/420px. Captures: `rail-collapsed-1100.png`, `rail-expanded-1100.png` in the
directory above. Mobile and the expanded rail are unchanged. directory above. Mobile and the expanded rail are unchanged.
### Stage definition popup follow-up (2026-10-20)
P6/R5 follow-up: **partial** against the live-server parity gate; verified with
the scratch-only `node test/ui-stage-definition.mjs ../.ui-stage-definition`
browser extension. Clicking a stage in either graph now opens the managed audit
popup, without replacing the current pane or changing its route. Timeline visit
panes remain available, and their Audit & debug Definition tab shares the viewer.
Rendered uses the existing Markdown/code renderer; Raw is the exact authored
stage source slice (including whitespace, custom blocks and shorthand), not a
serialization of the normalized graph. Run definitions request `get_pipeline`
with the recorded pipeline id/version, never latest. Missing source and load
errors are explicit; terminal nodes have no authored stage definition.
Scratch captures: `.ui-stage-definition/01-run-definition-rendered.png`,
`02-run-definition-raw.png`, `03-pipeline-definition-rendered.png`,
`04-visit-definition-nested.png`, `05-definition-missing-source.png`,
`06-definition-load-failed.png`, `07-definition-terminal.png`, and
`08-definition-narrow.png`, `09-definition-loading.png`, and
`10-definition-missing-version.png`. Real browser assertions cover exact source, pinned
version, unchanged route, nested-pane preservation, Tab trapping and Escape/focus
restoration. No deployed service, live workflow or device was used.
### Chat audit follow-up (2026-10-20, partial — fresh UI captures pending) ### Chat audit follow-up (2026-10-20, partial — fresh UI captures pending)
Codex model follow-up (partial, fixture-tested; fresh UI captures pending): Codex model follow-up (partial, fixture-tested; fresh UI captures pending):
+21
View File
@@ -0,0 +1,21 @@
// Exact source ranges, following internal/pipeline/definition.go's block rules.
// Never reserialize graph fields: defaults and authored spelling differ.
export function stageSource(source, key) {
if (typeof source !== "string") return null;
let active = false;
let start = null;
let offset = 0;
for (const line of source.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
const trim = line.trim();
if (active) {
if (trim === "```") active = false;
} else if (trim.startsWith("# stage ")) {
if (start !== null) return source.slice(start, offset);
if (trim.slice(8).trim() === key) start = offset;
} else if (trim.startsWith("```")) {
active = true;
}
offset += line.length;
}
return start === null ? null : source.slice(start);
}
+12
View File
@@ -4,6 +4,7 @@
import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact } from "../dom.js"; import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact } from "../dom.js";
import { changeKindTone, describeError } from "../format.js"; import { changeKindTone, describeError } from "../format.js";
import { definitionDocument } from "./stageDefinition.js";
import { import {
BINARY_DIFF_MESSAGE, BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE, NO_LINE_CHANGES_MESSAGE,
@@ -826,6 +827,16 @@ function openArtifactViewer(viewable, startIndex, trigger = null) {
}); });
} }
/** Graph inspection reuses the audit viewer without touching pane/route state. */
function openStageDefinition(detail, stageKey, subtitle = "") {
openStageAudit({
title: `${stageKey} definition`,
subtitle,
tabs: [{ key: "definition", label: "Definition", body: () =>
definitionDocument(detail, stageKey, (text) => rt.views.chat.renderMarkdown(text)) }],
});
}
/** /**
* The Audit & debug dialog: a stage's turn-owned evidence behind vertical tabs * The Audit & debug dialog: a stage's turn-owned evidence behind vertical tabs
* (Input, Output, Memory, Session, Stage definition), the chosen section's body * (Input, Output, Memory, Session, Stage definition), the chosen section's body
@@ -927,6 +938,7 @@ function openStageAudit({ title = "Audit", subtitle = "", tabs = [], trigger = n
} }
return { return {
openStageDefinition,
closeChangeViewer, closeChangeViewer,
openChangeViewer, openChangeViewer,
openDecisionSheet, openDecisionSheet,
+1
View File
@@ -576,6 +576,7 @@ function renderPipelineDetail() {
pane.append(host); pane.append(host);
state.pipelineGraph = mountGraph(host, d.graph, { state.pipelineGraph = mountGraph(host, d.graph, {
expanded: state.pipelineGraphExpanded, expanded: state.pipelineGraphExpanded,
onStageTap: (key) => rt.views.dialogs.openStageDefinition(d, key, `${d.name || "Pipeline"} · v${d.version}`),
selectedKey: state.pipelineGraphSelection, selectedKey: state.pipelineGraphSelection,
onSelectionChange: (key) => { onSelectionChange: (key) => {
// The graph has already opened or closed its own definition pane; record // The graph has already opened or closed its own definition pane; record
+16 -15
View File
@@ -9,6 +9,7 @@ import { resolveArtifactUrl } from "../serverUrl.js";
import { runStateOf, runStatusLabel } from "../runs.js"; import { runStateOf, runStatusLabel } from "../runs.js";
import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, mount as mountGraph } from "../graph.js"; import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, mount as mountGraph } from "../graph.js";
import { writeGraphExpanded } from "../graphPrefs.js"; import { writeGraphExpanded } from "../graphPrefs.js";
import { definitionDocument } from "./stageDefinition.js";
import { import {
RENDERED_RUN_TABS, RENDERED_RUN_TABS,
EMPTY_INPUT_MESSAGE, EMPTY_INPUT_MESSAGE,
@@ -26,8 +27,6 @@ import {
headlineFields, headlineFields,
runStepFields, runStepFields,
stageSectionSpecs, stageSectionSpecs,
stageDefinitionFields,
terminalFields,
clampVisitIndex, clampVisitIndex,
referencedVerdictArtifacts, referencedVerdictArtifacts,
verdictReasonSegments, verdictReasonSegments,
@@ -174,8 +173,8 @@ function renderRunDetail(now = Date.now()) {
* The Graph tab (R5): the run's own guidance note plus the shared workflow graph * The Graph tab (R5): the run's own guidance note plus the shared workflow graph
* mounted in run mode, or the app's exact missing-graph sentence when the server * mounted in run mode, or the app's exact missing-graph sentence when the server
* sent no stages. The active stage pulses with its elapsed time while the run * sent no stages. The active stage pulses with its elapsed time while the run
* executes; clicking a stage opens the existing visit pane at that stage's most * executes; clicking a stage opens its authored definition without navigating.
* recent visit. The mount handle is tracked in `state.runGraph` so a re-render * The mount handle is tracked in `state.runGraph` so a re-render
* (or a tab/run change) always unmounts the previous wheel/pointer/resize * (or a tab/run change) always unmounts the previous wheel/pointer/resize
* listeners and the elapsed timer. * listeners and the elapsed timer.
*/ */
@@ -191,7 +190,9 @@ function renderRunGraphTab(d) {
state.runGraph = mountGraph(host, d.graph, { state.runGraph = mountGraph(host, d.graph, {
runState: runGraphState(d), runState: runGraphState(d),
expanded: state.runGraphExpanded, expanded: state.runGraphExpanded,
onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)), onStageTap: (key) => rt.views.dialogs.openStageDefinition(
runDefinition(d), key, `Run ${d.id} · pipeline ${d.pipeline_id} · v${d.version}`,
),
onExpandedChange: (value) => { onExpandedChange: (value) => {
state.runGraphExpanded = value; state.runGraphExpanded = value;
writeGraphExpanded(value); writeGraphExpanded(value);
@@ -212,8 +213,6 @@ function latestVisitIndex(d, key) {
/** Open the audit dialog for one visit: its turn files, session and definition. */ /** Open the audit dialog for one visit: its turn files, session and definition. */
function openAuditFor(d, step, stageKey, visitIndex) { function openAuditFor(d, step, stageKey, visitIndex) {
if (!step) return; if (!step) return;
const graph = d.graph ?? { stages: [] };
const stage = (graph.stages ?? []).find((candidate) => candidate.key === stageKey) ?? null;
showStageAudit({ showStageAudit({
title: `${nodeLabel(stageKey)} audit`, title: `${nodeLabel(stageKey)} audit`,
subtitle: `Visit ${visitIndex + 1} · ${runLabelFor(d)}`, subtitle: `Visit ${visitIndex + 1} · ${runLabelFor(d)}`,
@@ -222,7 +221,9 @@ function openAuditFor(d, step, stageKey, visitIndex) {
{ key: "output", label: "Output", body: () => auditArtifact(step, "output.md", EMPTY_OUTPUT_MESSAGE) }, { key: "output", label: "Output", body: () => auditArtifact(step, "output.md", EMPTY_OUTPUT_MESSAGE) },
{ key: "memory", label: "Memory", body: () => auditArtifact(step, "memory.md", "No memory recorded for this visit.") }, { key: "memory", label: "Memory", body: () => auditArtifact(step, "memory.md", "No memory recorded for this visit.") },
{ key: "session", label: "Session", body: () => auditSession(step) }, { key: "session", label: "Session", body: () => auditSession(step) },
{ key: "definition", label: "Definition", body: () => auditDefinition(stage, stageKey, graph) }, { key: "definition", label: "Definition", body: () => definitionDocument(
runDefinition(d), stageKey, (text) => rt.views.chat.renderMarkdown(text),
) },
], ],
}); });
} }
@@ -341,13 +342,13 @@ function auditSession(step) {
return wrap; return wrap;
} }
/** The stage's own definition (prompt, tools, configs, edges) in the audit. */ /** Load authored source for exactly the run's recorded version. */
function auditDefinition(stage, stageKey, graph) { function runDefinition(d) {
const fields = stage ? stageDefinitionFields(stage) : terminalFields(graph, stageKey); // Never fall back to latest: a run must show the version it executed.
if (!fields.length) return h("div", { class: "muted", text: NO_STAGE_DETAILS_MESSAGE }); if (!(Number(d.pipeline_id) > 0 && Number(d.version) > 0)) {
const body = h("div", { class: "audit-definition" }); return Promise.reject(new Error("The run did not include its pipeline version."));
for (const field of fields) body.append(renderStageField(field)); }
return body; return repo.getPipeline(d.pipeline_id, d.version);
} }
/** The Summary tab: identity, key/value rows, diagnostic and the sections. */ /** The Summary tab: identity, key/value rows, diagnostic and the sections. */
+44
View File
@@ -0,0 +1,44 @@
import { h } from "../dom.js";
import { describeError } from "../format.js";
import { stageSource } from "../stageDefinition.js";
/** Both modes use the same authored source, including unknown/custom blocks. */
export function definitionDocument(detail, key, renderMarkdown) {
const wrap = h("div", { class: "audit-doc stage-definition-document" });
const toggle = h("div", { class: "audit-doc-toggle", role: "group", "aria-label": "Definition view" });
const out = h("div", { class: "audit-doc-body", "aria-live": "polite" });
let mode = "rendered";
let source = null;
const buttons = ["rendered", "raw"].map((value) => h("button", {
class: "audit-doc-mode",
type: "button",
text: value === "raw" ? "Raw" : "Rendered",
onclick: () => { mode = value; draw(); },
}));
const draw = () => {
buttons.forEach((button, index) => {
const selected = mode === ["rendered", "raw"][index];
button.classList.toggle("active", selected);
button.setAttribute("aria-pressed", String(selected));
});
if (source === null) return;
out.replaceChildren(mode === "raw"
? h("pre", { class: "field-block" }, h("code", { text: source }))
: h("div", { class: "field-markdown" }, renderMarkdown(source)));
};
toggle.append(...buttons);
wrap.append(h("div", { class: "audit-doc-bar" }, toggle), out);
out.append(h("div", { class: "muted", text: "Loading stage definition…" }));
draw();
Promise.resolve(detail).then((pipeline) => {
source = stageSource(pipeline?.source, key);
if (source === null) {
out.replaceChildren(h("div", { class: "muted", text: key.startsWith("#")
? "Terminal nodes have no authored stage definition."
: "The server did not include source for this stage. No definition has been reconstructed." }));
} else draw();
}).catch((error) => {
out.replaceChildren(h("div", { class: "muted", text: `Could not load stage definition: ${describeError(error)}` }));
});
return wrap;
}
+23
View File
@@ -0,0 +1,23 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { stageSource } from "../src/stageDefinition.js";
test("source slices preserve authored CRLF, whitespace, custom blocks and shorthand", () => {
const first = " # stage one\r\n\r\n```custom\r\nhello\r\n```\r\n```edges\r\nsuccess -> #\r\n```\r\n\r\n";
const last = "# stage two\r\n```prompt\r\nlast\r\n```";
assert.equal(stageSource(first + last, "one"), first);
assert.equal(stageSource(first + last, "two"), last);
});
test("stage-like lines inside blocks do not terminate or create source ranges", () => {
const source = "# stage one\n```prompt\n# stage two\n```js\ntext\n```\n\n";
assert.equal(stageSource(source + "# stage two\n", "one"), source);
assert.equal(stageSource(source, "two"), null);
});
test("missing source, absent stages and terminals never produce guessed definitions", () => {
for (const source of [undefined, null, "", "# stage one\n"]) {
assert.equal(stageSource(source, "missing"), null);
assert.equal(stageSource(source, "#success"), null);
}
});
+134
View File
@@ -0,0 +1,134 @@
// Scratch-only browser proof: real views/modal/graph, deterministic get_pipeline
// fixture. No deployed service, socket, workflow, model or device is contacted.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
const out = resolve(process.argv[2] || ".ui-stage-definition");
await mkdir(out, { recursive: true });
const source = "# stage review\n\n```prompt\nReview **the change**.\n# stage not-a-node\n```\n\n```custom\nPreserve this authored block.\n```\n\n```edges\nsuccess -> #\n```\n\n";
const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Stage definition scratch proof</title>
${["design/tokens/tokens", "base", "shell", "lists", "run-detail", "chat", "graph", "dialogs"].map(name => `<link rel="stylesheet" href="/${name}.css">`).join("")}
<div class="app-root" id="root" style="display:block;padding:24px"><h1 id="detailTitle" tabindex="-1">Scratch stage definition proof</h1><main id="pane-main"></main></div><div id="modalLayer"></div>
<script type="module">
import { createModalController } from '/src/modal.js';
import { createDialogsView } from '/src/views/dialogs.js';
import { createRunDetailView } from '/src/views/runDetail.js';
import { createPipelinesView } from '/src/views/pipelines.js';
import { createChatView } from '/src/views/chat.js';
const source = ${JSON.stringify(source)};
const graph = {stages:[{key:'review', type:'model', prompt:'Review the change.', edges:{success:'#success'}, configs:{}}]};
const detail = {id:7,name:'Review pipeline',version:3,source,graph};
const run = {id:42,pipeline_id:7,version:3,name:'Review pipeline',status:'succeeded',graph,steps:[{stage:'review',sequence:1,status:'succeeded',outcome:'success'}]};
const state = {runDetail:run,pipelineDetail:detail,pipelineTab:'graph',runStageSections:new Set(),runStagePane:{stageKey:'review',visitIndex:0}};
const modal = createModalController();
window.requests = []; window.routes = [];
const rt = {state,modal,views:{},repo:{getPipeline:async(id,version)=>{requests.push({id,version}); if(window.fail) throw new Error('fixture refusal'); if(window.delay) await new Promise(resolve => window.release=resolve); return window.missing ? {...detail,source:null} : detail;}},pushRoute:(r)=>routes.push(r)};
rt.views.chat=createChatView(rt);rt.views.dialogs=createDialogsView(rt);rt.views.runDetail=createRunDetailView(rt);rt.views.pipelines=createPipelinesView(rt);
window.show = (kind) => {
modal.closeAll();state.runGraph?.unmount();state.pipelineGraph?.unmount();
const host=document.querySelector('main');
host.replaceChildren(kind==='pipeline' ? rt.views.pipelines.renderPipelineDetail() : rt.views.runDetail.renderRunGraphTab(run));
};
window.pane = () => {document.querySelector('main').append(rt.views.runDetail.renderStagePane(run));modal.reconcile();};
window.expectedSource=source;window.rt=rt;show('run');
</script>`;
const server = createServer(async (req, res) => {
try {
if (req.url === "/") { res.setHeader("content-type", "text/html"); res.end(html); return; }
const path = resolve(root, `.${new URL(req.url, "http://scratch").pathname}`);
if (!path.startsWith(root)) { res.writeHead(403); res.end(); return; }
res.setHeader("content-type", extname(path) === ".css" ? "text/css" : "text/javascript");
res.end(await readFile(path));
} catch { res.writeHead(404); res.end(); }
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
let browser;
try {
browser = await launchChrome();
const page = await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
const capture = async (name) => {
await page.evaluate('Promise.all(document.getAnimations().filter(a => a.effect.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {})))');
await page.screenshot(resolve(out, name));
};
await page.waitForSelector('.graph-node[data-key="review"]');
const clickNode = async () => {
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await page.waitForSelector('.stage-definition-document .field-markdown');
};
await clickNode();
assert.deepEqual(await page.evaluate('requests'), [{ id: 7, version: 3 }]);
assert.equal(await page.evaluate('document.querySelector(".app-root").inert'), true);
await capture("01-run-definition-rendered.png");
await page.clickText('.audit-doc-mode', 'Raw');
assert.equal(await page.evaluate('document.querySelector(".stage-definition-document code").textContent === expectedSource'), true);
assert.equal(await page.evaluate('document.activeElement.textContent'), 'Raw');
await capture("02-run-definition-raw.png");
for (let i = 0; i < 8; i++) {
await page.pressKey('Tab');
assert.equal(await page.evaluate('document.querySelector(".audit-viewer").contains(document.activeElement)'), true);
}
await page.pressKey('Escape');
assert.equal(await page.evaluate('document.activeElement.dataset.key'), 'review');
assert.equal(await page.evaluate('location.pathname'), '/');
assert.deepEqual(await page.evaluate('routes'), []);
await page.evaluate("show('pipeline')");
await clickNode();
assert.deepEqual(await page.evaluate('routes'), []);
assert.equal(await page.evaluate('requests.length'), 1);
await capture("03-pipeline-definition-rendered.png");
await page.click('.audit-close');
await page.evaluate("show('run');pane()");
await page.click('.audit-open');
await page.click('[data-audit-tab="definition"]');
await page.waitForSelector('.stage-definition-document .field-markdown');
assert.deepEqual(await page.evaluate('rt.modal.stackIds()'), ['stage-pane','stage-audit']);
await capture("04-visit-definition-nested.png");
await page.pressKey('Escape');
assert.equal(await page.evaluate('!!document.querySelector(".stage-pane")'), true);
assert.equal(await page.evaluate('document.activeElement.classList.contains("audit-open")'), true);
await page.evaluate("show('run');window.missing=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await page.waitForText('No definition has been reconstructed.');
await capture("05-definition-missing-source.png");
await page.evaluate("show('run');window.missing=false;window.fail=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await page.waitForText('fixture refusal');
await capture("06-definition-load-failed.png");
await page.evaluate("show('run');window.fail=false");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="#success"]');
await page.waitForText('Terminal nodes have no authored stage definition.');
await capture("07-definition-terminal.png");
await page.evaluate("show('run')");
await clickNode();
await page.resize(390, 844);
await capture("08-definition-narrow.png");
await page.resize(1440, 900);
await page.evaluate("show('run');window.delay=true");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await page.waitForText('Loading stage definition…');
await capture("09-definition-loading.png");
await page.clickText('.audit-doc-mode', 'Raw');
await page.evaluate('release()');
await page.waitForSelector('.stage-definition-document code');
assert.equal(await page.evaluate('document.querySelector(".stage-definition-document code").textContent === expectedSource'), true);
await page.evaluate("show('run');window.delay=false;rt.state.runDetail.version=0;window.beforeRequests=requests.length");
await page.evaluate('new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))');
await page.click('.graph-node[data-key="review"]');
await page.waitForText('The run did not include its pipeline version.');
assert.equal(await page.evaluate('requests.length === beforeRequests'), true);
await capture("10-definition-missing-version.png");
console.log(`PASS: run/pipeline node popup, exact source, keyboard focus/escape, nested stage preservation, missing/error states; captures ${out}`);
} finally {
await browser?.close();
await new Promise(resolve => server.close(resolve));
}