Merge branch 'main' into web-connection

Integrate main's run-detail Changes (R4) and Graph (R5) work with the
connection banner/reconnect/foreground-recovery/live-badge work (T3/T4/T5).

Conflicts resolved by keeping both independent additions:
- web/styles.css: the .conn-*/.live-* rules and the .change-*/.diff-* rules
  are separate blocks; both retained under their own comment headers.
- web/test/ui-smoke.mjs: both capture sequences retained (T3/T4/T5 writes
  28-connected-banner/29-disconnected-banner/30-reconnect-recovered; R4/R5
  writes its own distinct 28-34 run-change captures), so no filename collides.

Checks after the merge: node --check on all touched JS/MJS; node --test test/
225 pass / 0 fail; node test/ui-smoke.mjs --out <worktree>/captures UI SMOKE
PASS against ws://127.0.0.1:8080/connect, including the connected banner +
build line + live badge, the disconnected retry banner, the online-event
recovery, and main's R4/R5 captures.
This commit is contained in:
2026-10-19 04:11:50 +01:00
10 changed files with 2381 additions and 37 deletions
+13 -5
View File
@@ -26,16 +26,16 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu
| 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 |
| P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | 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 |
| 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); the definition view (every route executed, no legend) plus, since R5, a run-mode view driven by `runState` (executed/not-executed stages and routes, the Executed / Not executed legend, the live halo/elapsed badge). Pane labels match the app's own vocabulary (`Outcomes`, `Tools`) rather than the checklist's category words |
## Runs
| # | Feature | Protocol | Status |
| --- | --- | --- | --- |
| R1 | Run history list with status roll-up | `list_runs` | done |
| R2 | Filter by status, sort, "needs you" markers | client-side | partial (status/pipeline/time filter + sort implemented and captured; the per-row "needs you" mark has no Android counterpart and its wording is deferred to R15, still todo) |
| R3 | Run detail: run fields, steps/visits, targets, sessions | `get_run` | done — tabbed Summary / Input / Output / Timeline; the Timeline opens a per-visit stage pane with the headline rows (Status, Outcome, Duration, Visit `{v} / {max}`, Model target, Target, Session), the Verdict block (option chip + reason with inline artifact links) and the visit sections Artifacts / Session / Output / Input / This run / Stage definition. Captured 2026-10-19: `captures/20-run-430-summary.png`, `captures/23-run-430-timeline.png`, `captures/24-run-430-stage-artifacts.png`, `captures/25-run-440-verdict.png` |
| R4 | Summary tab incl. collapsible **Changes** viewer (raw + rendered diff) | `get_run` file changes | todo |
| R5 | Graph tab (per-stage panes, verdicts) | `get_run` | todo |
| R3 | Run detail: run fields, steps/visits, targets, sessions | `get_run` | done — tabbed Summary / Graph / Input / Output / Timeline; the Timeline opens a per-visit stage pane with the headline rows (Status, Outcome, Duration, Visit `{v} / {max}`, Model target, Target, Session), the Verdict block (option chip + reason with inline artifact links) and the visit sections Artifacts / Session / Output / Input / This run / Stage definition. Captured 2026-10-19: `captures/20-run-430-summary.png`, `captures/23-run-430-timeline.png`, `captures/24-run-430-stage-artifacts.png`, `captures/25-run-440-verdict.png` |
| R4 | Summary tab incl. collapsible **Changes** viewer (raw + rendered diff) | `get_run` file changes | done — a collapsed-by-default **Changes** section in the Summary tab (`{N} file(s) changed · ±stat · partial capture`; the empty variants read `Changes · capture unavailable` / `capture pending` / `partial capture` / `not recorded for this run` / `capture incomplete` / `no changes observed`) whose rows open a full-screen diff viewer with **Rendered** (each `@@` hunk header on a raised surface, old/new gutter numbers, the shared `+`/`-`/space line language) and **Raw patch** forms, Previous/Next file paging (disabled at the ends), a raw-patch copy control, Escape/backdrop/Close close, and honest binary/truncated/no-patch messages instead of a fabricated diff. Pure logic in `src/changes.js`. Captured 2026-10-19: `captures/28-run-438-changes-collapsed.png`, `captures/29-run-438-changes-expanded.png`, `captures/30-run-438-changes-diff-rendered.png`, `captures/31-run-438-changes-diff-raw.png`, `captures/32-run-442-changes-binary.png`, `captures/33-run-450-changes-truncated.png`, `captures/34-run-455-changes-pending.png` |
| R5 | Graph tab (per-stage panes, verdicts) | `get_run` | done — the run detail's Graph tab (between Summary and Input) mounts the shared `src/graph.js` renderer in run mode with the app's run note: a visited stage is executed (solid fill + border), an unvisited one hollow with a dashed muted border, a terminal executed only when a visit resolved to it, a route executed only when a visit produced that outcome (solid with an arrowhead; success first, error last, others alphabetical, `error*` for a fallback error route), the Executed / Not executed legend (runs only, never the definition view), and — while executing — the current stage's pulsing halo + elapsed badge (a static ring under `prefers-reduced-motion`; nothing for a finished run). Clicking a stage opens the existing visit pane at that stage's latest visit with its Verdict; Back/Escape close it and restore focus. The empty state is the exact `This server did not include the run graph.` (unit-tested; no live run currently carries a graph-less payload). Captured 2026-10-19: `captures/28-run-438-graph.png` (finished run 438: legend + executed styling + dashed untaken routes), `captures/29-run-438-graph-pane.png` (a graph-opened stage pane showing a Verdict), `captures/30-run-440-graph.png` (failed run 440: hollow/dashed not-executed stages) |
| R6 | Input / Output field sections per stage | `get_run` | done — one collapsed section per recorded entry, expanded as a monospace block (primitives verbatim, arrays `, `-joined, objects `k=v` `, `-joined), empty states "No input recorded." / "No output recorded.". Captured 2026-10-19: `captures/21-run-430-input.png`, `captures/22-run-430-output.png`, `captures/27-run-output-empty.png` |
| R7 | Timeline | `get_run` | done — one compact row per visit (`{stage} · visit {n}`, stage-outcome chip, paperclip when artifacts recorded, duration, description = first non-blank diagnostic line else `→ {target}`); empty state "No visits recorded.". Captured 2026-10-19: `captures/23-run-430-timeline.png`, `captures/26-run-428-timeline-empty.png` |
| R8 | Artifacts gallery + full-screen viewer (images inline, others download/open) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/04-run-430-artifacts.png`, `captures/05-artifact-viewer.png`) |
@@ -52,7 +52,15 @@ choice: the visit's exported session is titled **Session** (the item text said
"Session export"; Android's `STAGE_SESSION_TITLE` is `Session`), and the step's
`session_id` renders as a **headline** row (Status, Outcome, Duration, Visit,
Model target, Target, Session), so it is not repeated in the "This run" evidence
section. R5 (Graph tab) deliberately leaves the tab's body unimplemented.
section. R5's Graph tab now renders that same shared graph in run mode (see the
row above), reusing the visit pane this section describes.
One wording decision from R4, recorded here as the app-authoritative choice: the
Changes disclosure's title **is** `runChangesHeader`, so a run that recorded files
reads `{N} file(s) changed · ±stat · …` with no `Changes · ` prefix — only the
empty-capture variants carry the `Changes · ` prefix — while the expanded body's
own summary line repeats the count and stat. The header is rendered verbatim, not
re-composed.
## Search
| # | Feature | Protocol | Status |
+388 -14
View File
@@ -34,6 +34,8 @@ import {
} from "./artifacts.js";
import {
PIPELINE_GRAPH_EMPTY,
RUN_GRAPH_MISSING,
RUN_GRAPH_NOTE,
mount as mountGraph,
} from "./graph.js";
import {
@@ -97,6 +99,7 @@ import {
runLabelFor,
runDurationText,
runTimeline,
runGraphState,
nodeLabel,
headlineFields,
runStepFields,
@@ -107,6 +110,29 @@ import {
outcomeColorToken,
stateGlyph,
} from "./runDetail.js";
import {
BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE,
TRUNCATED_PATCH_NOTE,
ChangeKind,
changeKindLabel,
changeKindTitle,
changePositionLabel,
changeRowMeta,
changeStat,
changesListSummary,
diffLineClass,
diffLineSymbol,
entryHasPatch,
gutterText,
gutterWidth,
noChangeDetail,
parseUnifiedPatch,
patchUnavailableReason,
runChanges,
runChangesHeader,
runChangesNote,
} from "./changes.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
@@ -156,6 +182,10 @@ const state = {
// handle is dropped on every re-render so its listeners can never leak.
pipelineGraph: null,
pipelineGraphExpanded: false,
// The mounted run-mode graph (R5) on the run detail's Graph tab. Dropped on
// every re-render and on a run change, so its wheel/pointer/resize listeners
// and its elapsed timer can never leak.
runGraph: null,
versionsExpanded: false,
pipelinesLoaded: false,
runsLoaded: false,
@@ -311,6 +341,10 @@ function renderContent() {
state.pipelineGraph.unmount();
state.pipelineGraph = null;
}
if (state.runGraph) {
state.runGraph.unmount();
state.runGraph = null;
}
const nodes = [];
if (state.error) {
nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error));
@@ -1135,12 +1169,13 @@ function closeMenu() {
}
/**
* The run detail: a tab strip (Summary / Input / Output / Timeline) over the
* selected tab's body, wired from the pure helpers in runDetail.js. Summary is
* the default and carries the run's identity, key/value rows and diagnostic;
* Input/Output are one collapsed section per recorded field; the Timeline is one
* compact row per visit that opens the stage pane. Every server string is set
* with textContent, never innerHTML.
* The run detail: a tab strip (Summary / Graph / Input / Output / Timeline) over
* the selected tab's body, wired from the pure helpers in runDetail.js. Summary
* is the default and carries the run's identity, key/value rows and diagnostic;
* the Graph tab mounts the shared workflow graph in run mode; Input/Output are
* one collapsed section per recorded field; the Timeline is one compact row per
* visit that opens the stage pane. Every server string is set with textContent,
* never innerHTML.
*/
function renderRunDetail() {
const d = state.runDetail;
@@ -1165,7 +1200,9 @@ function renderRunDetail() {
),
),
);
if (state.runTab === "input") {
if (state.runTab === "graph") {
pane.append(renderRunGraphTab(d));
} else if (state.runTab === "input") {
pane.append(renderRunFieldTab(d.input, "input", EMPTY_INPUT_MESSAGE));
} else if (state.runTab === "output") {
pane.append(renderRunFieldTab(d.output, "output", EMPTY_OUTPUT_MESSAGE));
@@ -1178,6 +1215,41 @@ function renderRunDetail() {
return pane;
}
/**
* 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
* 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
* recent visit. The mount handle is tracked in `state.runGraph` so a re-render
* (or a tab/run change) always unmounts the previous wheel/pointer/resize
* listeners and the elapsed timer.
*/
function renderRunGraphTab(d) {
const wrap = h("div", { class: "run-tab-body" });
const stages = d.graph?.stages ?? [];
if (!stages.length) {
wrap.append(h("div", { class: "run-empty muted", text: RUN_GRAPH_MISSING }));
return wrap;
}
wrap.append(h("p", { class: "graph-note muted", text: RUN_GRAPH_NOTE }));
const host = h("div", { class: "graph-host" });
wrap.append(host);
state.runGraph = mountGraph(host, d.graph, {
runState: runGraphState(d),
onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)),
});
return wrap;
}
/**
* The visit index the graph opens for a stage: its most recent recorded visit
* (`visits.size - 1`, never negative), exactly as RunGraphTab computes it.
*/
function latestVisitIndex(d, key) {
const visits = runTimeline(d.steps ?? []).visitsByStage.get(key) ?? [];
return Math.max(0, visits.length - 1);
}
/** The Summary tab: identity, chip row, key/value rows, diagnostic and gallery. */
function renderRunSummaryTab(d) {
const wrap = h("div", { class: "run-tab-body" });
@@ -1207,6 +1279,14 @@ function renderRunSummaryTab(d) {
renderArtifactGallery(d.steps ?? []),
),
);
// The run-level Changes (parity R4), collapsed by default like the Android
// summary: the observed workspace diff. Its header alone states the file count
// and aggregate stat until expanded, and every file row opens the diff viewer.
const changes = runChanges(d.steps ?? []);
wrap.append(
renderCollapsible("summary-changes", runChangesHeader(changes), () => renderChangesBody(changes)),
);
return wrap;
}
@@ -1299,6 +1379,285 @@ function renderCollapsible(key, title, bodyFn) {
return wrap;
}
// --- Changes (parity R4) ---------------------------------------------------
/**
* The Changes section body: the file-list summary line, the honest capture note
* (when the capture was not complete) and then either the no-change detail or
* one clickable row per changed file in first-seen order. Every server string is
* set as text, never as markup.
*/
function renderChangesBody(changes) {
const body = h("div", { class: "changes" });
body.append(h("div", { class: "changes-summary", text: changesListSummary(changes) }));
const note = runChangesNote(changes);
if (note.trim() !== "") body.append(h("div", { class: "changes-note muted", text: note }));
if (changes.files.length === 0) {
body.append(h("div", { class: "changes-empty muted", text: noChangeDetail(changes) }));
return body;
}
const list = h("div", { class: "changes-list" });
changes.files.forEach((entry, index) => list.append(renderChangeRow(entry, index, changes.files)));
body.append(list);
return body;
}
/** The tone class for a file's kind: added green, deleted red, else neutral. */
function changeKindTone(kind) {
if (kind === ChangeKind.Added) return "ok";
if (kind === ChangeKind.Deleted) return "bad";
return "muted";
}
/**
* One changed-file row: the kind word in its hue, the path in monospace, the
* `+N -M` stat and the `changed by …` meta line. Clicking (or Enter/Space) opens
* the diff viewer on this file, whose position there confirms which row it is.
*/
function renderChangeRow(entry, index, files) {
const open = () => openChangeViewer(files, index);
const row = h("div", {
class: "change-row",
role: "button",
tabindex: "0",
"data-change-index": String(index),
"aria-label": `Open ${entry.path}`,
});
row.addEventListener("click", open);
row.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
open();
}
});
row.append(h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindLabel(entry.kind) }));
const main = h("div", { class: "change-main" });
main.append(h("div", { class: "change-path monospace", text: entry.path }));
main.append(h("div", { class: "change-meta muted", text: changeRowMeta(entry) }));
row.append(main);
const stat = h("div", { class: "change-stat" });
if (entry.added > 0) stat.append(h("span", { class: "stat-add", text: `+${entry.added}` }));
if (entry.removed > 0) stat.append(h("span", { class: "stat-del", text: `-${entry.removed}` }));
row.append(stat);
return row;
}
let changeViewerOverlay = null;
let changeViewerKeydown = null;
let changeViewerIndex = null;
/** Close the diff viewer, returning focus to the row that opened it. */
function closeChangeViewer() {
if (changeViewerKeydown) {
document.removeEventListener("keydown", changeViewerKeydown);
changeViewerKeydown = null;
}
const index = changeViewerIndex;
changeViewerOverlay?.remove();
changeViewerOverlay = null;
changeViewerIndex = null;
if (index != null) {
document.querySelector(`.change-row[data-change-index="${index}"]`)?.focus();
}
}
/**
* The full-screen diff viewer for one changed file. It pages through the run's
* changed files exactly as the artifact viewer pages through a gallery's media
* (one shared index, previous/next affordances, Escape/the close button/backdrop
* dismissing), and shows both forms the brief requires, switchable from one
* control row: the **Rendered** reading (each hunk's `@@` header, the shared
* diff line language and the old/new gutter numbers) and the **Raw patch** (the
* server's unified patch verbatim in monospace). A file the server could not
* give a patch for (binary, truncated, or a capture that recorded none) shows the
* honest reason in place of a diff rather than a fabricated one.
*/
function openChangeViewer(files, startIndex) {
closeChangeViewer();
if (!files?.length) return;
let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1);
let form = "rendered";
const overlay = h("div", {
class: "change-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Diff viewer",
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeChangeViewer();
});
const renderViewer = () => {
const entry = files[index];
changeViewerIndex = index;
const stat = changeStat(entry.added, entry.removed);
const hasPatch = entryHasPatch(entry);
const titles = h("div", { class: "change-viewer-titles" });
const titleRow = h("div", { class: "change-viewer-title-row" });
titleRow.append(
h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindTitle(entry.kind) }),
);
if (stat !== "") titleRow.append(h("span", { class: "change-viewer-stat monospace", text: stat }));
titles.append(titleRow);
titles.append(h("div", { class: "change-viewer-path monospace", text: entry.path }));
titles.append(
h("div", {
class: "change-viewer-position muted",
text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`,
}),
);
const head = h(
"div",
{ class: "change-viewer-head" },
titles,
h("button", {
class: "change-viewer-copy",
type: "button",
text: "Copy raw patch",
disabled: !hasPatch,
onclick: () => copyText(entry.patch ?? ""),
}),
h("button", {
class: "change-viewer-close",
type: "button",
text: "Close diff",
onclick: closeChangeViewer,
}),
);
const controls = h(
"div",
{ class: "change-viewer-controls" },
h("button", {
class: `change-form${form === "rendered" ? " active" : ""}`,
type: "button",
"data-form": "rendered",
text: "Rendered",
disabled: form === "rendered",
onclick: () => {
form = "rendered";
renderViewer();
},
}),
h("button", {
class: `change-form${form === "raw" ? " active" : ""}`,
type: "button",
"data-form": "raw",
text: "Raw patch",
disabled: !hasPatch,
onclick: () => {
form = "raw";
renderViewer();
},
}),
h("div", { class: "change-viewer-spacer" }),
h("button", {
class: "change-page",
type: "button",
"data-page": "prev",
text: "Previous file",
disabled: index === 0,
onclick: () => {
index = Math.max(index - 1, 0);
form = "rendered";
renderViewer();
},
}),
h("button", {
class: "change-page",
type: "button",
"data-page": "next",
text: "Next file",
disabled: index === files.length - 1,
onclick: () => {
index = Math.min(index + 1, files.length - 1);
form = "rendered";
renderViewer();
},
}),
);
const body = h("div", { class: "change-viewer-body" });
if (entry.binary || !hasPatch) {
body.append(
h("div", {
class: "change-honest muted",
text: entry.binary ? BINARY_DIFF_MESSAGE : patchUnavailableReason(entry),
}),
);
} else if (form === "raw") {
body.append(h("pre", { class: "change-raw monospace", text: entry.patch ?? "" }));
} else {
body.append(renderRenderedDiff(entry));
}
overlay.replaceChildren(head, controls, body);
};
renderViewer();
document.body.append(overlay);
changeViewerOverlay = overlay;
changeViewerKeydown = (event) => {
if (event.key === "Escape") closeChangeViewer();
};
document.addEventListener("keydown", changeViewerKeydown);
}
/** The rendered reading: the stat line, an optional truncation note, each hunk. */
function renderRenderedDiff(entry) {
const wrap = h("div", { class: "change-diff" });
const parsed = parseUnifiedPatch(entry.patch);
const statLine = h("div", { class: "change-diff-stat" });
if (parsed.added > 0) statLine.append(h("span", { class: "stat-add", text: `+${parsed.added}` }));
if (parsed.removed > 0) statLine.append(h("span", { class: "stat-del", text: `-${parsed.removed}` }));
if (parsed.added === 0 && parsed.removed === 0) {
statLine.append(h("span", { class: "muted", text: NO_LINE_CHANGES_MESSAGE }));
}
wrap.append(statLine);
if (entry.truncated) wrap.append(h("div", { class: "change-diff-note muted", text: TRUNCATED_PATCH_NOTE }));
for (const hunk of parsed.hunks) wrap.append(renderHunk(hunk));
return wrap;
}
/**
* One `@@` hunk: its header on a raised surface, then its lines in a
* horizontally scrollable container, each with its old/new gutter numbers (blank
* on the absent side and on a `\ No newline` marker) and the shared
* `{symbol} {text}` coloured by kind.
*/
function renderHunk(hunk) {
const width = gutterWidth(hunk);
const wrap = h("div", { class: "change-hunk" });
wrap.append(h("div", { class: "change-hunk-head", text: hunk.header }));
const lines = h("div", { class: "change-hunk-lines" });
for (const line of hunk.lines) {
const gutter = line.noNewlineMarker
? " ".repeat(width * 2 + 1)
: `${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}`;
lines.append(
h(
"div",
{ class: "change-line" },
h("span", { class: "change-gutter", text: gutter }),
h("span", { class: `change-text ${diffLineClass(line.kind)}`, text: `${diffLineSymbol(line.kind)} ${line.text}` }),
),
);
}
wrap.append(lines);
return wrap;
}
/** Copy arbitrary text (the raw patch) to the clipboard, best effort. */
async function copyText(text) {
if (!text || !canCopyLink()) return;
try {
await navigator.clipboard.writeText(text);
} catch {
// Clipboard permission may be denied; the patch is still readable.
}
}
/** The Timeline tab: one compact row per visit, in step order. */
function renderRunTimelineTab(d) {
const wrap = h("div", { class: "run-tab-body" });
@@ -1543,7 +1902,14 @@ function closeStagePane() {
const row = [...document.querySelectorAll(".timeline-row")].find(
(node) => node.dataset.stageKey === closing.stageKey && node.dataset.visitIndex === String(closing.visitIndex),
);
row?.focus();
// A pane opened from the Timeline returns to its row; one opened from the Graph
// returns to the stage node that opened it (there is no timeline row then).
const focusTarget =
row ??
[...document.querySelectorAll(".graph-node")].find(
(candidate) => candidate.dataset.key === closing.stageKey,
);
focusTarget?.focus();
}
/** Whether the configured server URL can resolve a server-relative artifact. */
@@ -2065,9 +2431,12 @@ async function selectPipeline(summary) {
async function selectRun(id, { silent = false } = {}) {
state.selectedRunId = id;
if (!silent) {
state.runDetail = null;
// A different run reseeds the detail: Summary tab, every section closed and
// no stage pane left over from the run the operator navigated away from.
// no stage pane left over from the run the operator navigated away from. Drop
// the mounted run graph first so a live run's timer can never outlive it.
state.runGraph?.unmount();
state.runGraph = null;
state.runDetail = null;
state.runTab = "summary";
state.runSections = new Set();
state.runStagePane = null;
@@ -2172,11 +2541,16 @@ client.addEventListener("state", (event) => {
render();
});
// The stage pane is a modal dialog: Escape closes it (the artifact viewer, when
// it is stacked above, owns Escape first). Registered once; it is a no-op when
// no pane is open.
// The stage pane is a modal dialog: Escape closes it (a stacked overlay — the
// artifact viewer or the diff viewer, when either is above — owns Escape first).
// Registered once; it is a no-op when no pane is open.
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && state.runStagePane && !document.querySelector(".artifact-viewer")) {
if (
event.key === "Escape" &&
state.runStagePane &&
!document.querySelector(".artifact-viewer") &&
!document.querySelector(".change-viewer")
) {
event.preventDefault();
closeStagePane();
}
+554
View File
@@ -0,0 +1,554 @@
// Pure, DOM-free logic for the run summary's Changes section and its diff
// viewer, ported from the Android client so the browser says and shows exactly
// the same things:
// ui/changes/RunChanges.kt changeKind, changeKindLabel, parseUnifiedPatch,
// runChanges, runChangesHeader, runChangesNote,
// changesListSummary, noChangeDetail,
// patchUnavailableReason, changeEntryTags,
// changeRowMeta, changePositionLabel, gutterWidth
// ui/changes/ChangeDiffViewer.kt the file row, the viewer header/controls/body
// and the honest no-diff/reason wording
// ui/chat/ChatDiffCard.kt diffLineSymbol / diffLineColor (the one diff
// line language shared with the chat edit card)
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and patch parsing can be unit-tested without a
// browser. The section/viewer 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.
// ---------------------------------------------------------------------------
// Change kind
// ---------------------------------------------------------------------------
/** The three recorded kinds plus the safe `other` fallback for anything else. */
export const ChangeKind = Object.freeze({
Added: "added",
Modified: "modified",
Deleted: "deleted",
Other: "other",
});
/**
* Maps the server's kind token to a ChangeKind. The token is trimmed and
* lowercased; an unrecognised or blank kind stays `other` rather than being
* guessed, so a future server value is shown read-only instead of mislabelled.
* Pure.
*/
export function changeKind(kind) {
switch (str(kind).trim().toLowerCase()) {
case "added":
return ChangeKind.Added;
case "modified":
return ChangeKind.Modified;
case "deleted":
return ChangeKind.Deleted;
default:
return ChangeKind.Other;
}
}
/** The word a file's kind is named by in the list and the diff header. */
export function changeKindLabel(kind) {
switch (kind) {
case ChangeKind.Added:
return "added";
case ChangeKind.Modified:
return "modified";
case ChangeKind.Deleted:
return "deleted";
default:
return "changed";
}
}
/** The kind word as the viewer header shows it, first letter capitalised. */
export function changeKindTitle(kind) {
const label = changeKindLabel(kind);
return label.charAt(0).toUpperCase() + label.slice(1);
}
// ---------------------------------------------------------------------------
// Unified patch parsing
// ---------------------------------------------------------------------------
/** Which kind of line this is within a unified patch. */
export const ChangeLineKind = Object.freeze({
Context: "context",
Add: "add",
Remove: "remove",
});
/**
* Parses a server-recorded unified patch into hunks, lines, line numbers and
* the true `+N -M` stat. The server builds these patches with a Go unified-diff
* writer (internal/filediff), so the shape is a standard `---`/`+++` header,
* optional metadata lines, `@@ -a,b +c,d @@` hunk headers and a ` `/`+`/`-`
* body. Anything unrecognised (a truncated tail, an exotic header) is carried
* verbatim in `headerLines` when it sits before the first hunk, and otherwise
* kept as an unnumbered context line, so the raw view always has the exact
* source while the rendered view shows only lines it can stand behind. A blank
* patch parses to an empty result rather than a fabricated one.
*/
export function parseUnifiedPatch(patch) {
const text = patch == null ? "" : String(patch);
if (text.trim() === "") {
return { raw: "", headerLines: [], hunks: [], added: 0, removed: 0 };
}
const rawLines = text.split("\n");
const headers = [];
const hunks = [];
let current = null;
for (const line of rawLines) {
const hunkStart = parseHunkHeader(line);
if (hunkStart != null) {
if (current) hunks.push(current.build());
current = new HunkBuilder(line, hunkStart.oldStart, hunkStart.oldCount, hunkStart.newStart, hunkStart.newCount);
} else if (line.startsWith("--- ") || line.startsWith("+++ ")) {
// An aggregated entry can contain one complete patch from each
// contributing stage. A new file header closes the preceding hunk
// instead of being rendered as an unnumbered context line in it.
if (current) {
hunks.push(current.build());
current = null;
}
headers.push(line);
} else if (current == null) {
headers.push(line);
} else {
current.lines.push(parseBodyLine(line, current));
}
}
if (current) hunks.push(current.build());
let added = 0;
let removed = 0;
for (const hunk of hunks) {
for (const line of hunk.lines) {
if (line.kind === ChangeLineKind.Add) added++;
else if (line.kind === ChangeLineKind.Remove) removed++;
}
}
return { raw: text, headerLines: headers, hunks, added, removed };
}
/**
* Mutable accumulator for one hunk as it is parsed, carrying the running old/new
* line counters so each body line gets its gutter numbers without a second pass.
*/
class HunkBuilder {
constructor(header, oldStart, oldCount, newStart, newCount) {
this.header = header;
this.oldStart = oldStart;
this.oldCount = oldCount;
this.newStart = newStart;
this.newCount = newCount;
this.lines = [];
this.oldLine = oldStart;
this.newLine = newStart;
}
build() {
return {
header: this.header,
oldStart: this.oldStart,
oldCount: this.oldCount,
newStart: this.newStart,
newCount: this.newCount,
lines: this.lines,
};
}
nextOld() {
return this.oldLine++;
}
nextNew() {
return this.newLine++;
}
}
/**
* The parsed `@@ -oldStart,oldCount +newStart,newCount @@` of a hunk header, or
* null when `line` is not one. A missing count defaults to 1 (the unified-diff
* rule) so a single-line hunk header is still read exactly. Pure.
*/
function parseHunkHeader(line) {
if (!line.startsWith("@@")) return null;
const end = line.indexOf("@@", 2);
if (end < 0) return null;
const ranges = tokenizeRanges(line.substring(2, end));
return ranges == null ? null : { oldStart: ranges[0], oldCount: ranges[1], newStart: ranges[2], newCount: ranges[3] };
}
/** The four numbers of a hunk header's range text, or null when malformed. Pure. */
function tokenizeRanges(body) {
const plus = body.indexOf("+");
const old = plus === -1 ? body : body.slice(0, plus);
const next = plus === -1 ? "" : body.slice(plus + 1);
if (old === "" || next === "") return null;
const oldRange = parseRange(old);
if (oldRange == null) return null;
const newRange = parseRange(next);
if (newRange == null) return null;
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
}
/** One `-start,count` / `+start,count` side of a hunk header. Pure. */
function parseRange(text) {
let trimmed = text.trim();
if (trimmed.startsWith("-")) trimmed = trimmed.slice(1);
else if (trimmed.startsWith("+")) trimmed = trimmed.slice(1);
if (trimmed === "") return null;
const comma = trimmed.indexOf(",");
const startText = (comma === -1 ? trimmed : trimmed.slice(0, comma)).trim();
const start = intOrNull(startText);
if (start == null) return null;
const countText = (comma === -1 ? "" : trimmed.slice(comma + 1)).trim();
const count = countText === "" ? 1 : intOrNull(countText);
if (count == null) return null;
return [start, count];
}
/** One body line of a hunk, tagged and numbered from `builder`'s counters. */
function parseBodyLine(line, builder) {
if (line.startsWith("+")) {
return { kind: ChangeLineKind.Add, text: line.slice(1), oldLine: 0, newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line.startsWith("-")) {
return { kind: ChangeLineKind.Remove, text: line.slice(1), oldLine: builder.nextOld(), newLine: 0, noNewlineMarker: false };
}
if (line.startsWith("\\")) {
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: true };
}
if (line.startsWith(" ")) {
return { kind: ChangeLineKind.Context, text: line.slice(1), oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line === "") {
return { kind: ChangeLineKind.Context, text: "", oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
// A truncated tail or an unexpected marker: keep the text, don't number it.
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: false };
}
/** The widest line number in a hunk, so its gutter lines up across every row. */
export function gutterWidth(hunk) {
let widest = 0;
for (const line of hunk?.lines ?? []) {
widest = Math.max(widest, Math.max(line.oldLine, line.newLine));
}
return String(Math.max(widest, 1)).length;
}
/** One gutter number padded to `width`; 0 means no number on that side. */
export function gutterText(value, width) {
return value > 0 ? String(value).padStart(width) : " ".repeat(width);
}
// ---------------------------------------------------------------------------
// Change aggregation (ui/changes/RunChanges.kt runChanges)
// ---------------------------------------------------------------------------
/**
* Aggregates a run's stage steps into its Changes state. Pure and total over its
* input: a null `file_changes` on a step is a historical (or non-capturing) step
* and contributes nothing (it is never "no changes"); a present capture with no
* files is a real, observed no-change. Files are keyed by path and keep
* first-seen order, so a path several steps changed is one entry naming all of
* them. Later steps win the kind unless they only say "other", added/removed
* line counts sum, binary/truncated are OR'd, before_mode is first-seen and
* after_mode last-seen.
*/
export function runChanges(steps) {
const entries = new Map();
let stepsWithChanges = 0;
let stepsPending = 0;
let partial = false;
let unavailable = false;
let missingCaptures = 0;
let skipped = 0;
let omitted = 0;
const diagnostics = new Set();
for (const step of steps ?? []) {
const changes = step?.file_changes;
if (changes == null) {
if (step?.status === "running" || step?.status === "waiting") stepsPending++;
else missingCaptures++;
continue;
}
stepsWithChanges++;
if (changes.status === "unavailable") unavailable = true;
if (changes.status === "partial") partial = true;
if (str(changes.diagnostic).trim() !== "") diagnostics.add(str(changes.diagnostic).trim());
skipped += Number(changes.skipped) || 0;
omitted += Number(changes.omitted) || 0;
const stageText = str(step?.stage);
const stage = stageText.trim() === "" ? "stage" : stageText;
for (const file of changes.files ?? []) {
const path = str(file?.path);
if (path.trim() === "") continue;
const kind = changeKind(file?.kind);
const parsed = parseUnifiedPatch(file?.patch);
const existing = entries.get(path);
const mergedSteps = existing ? [...existing.steps] : [];
if (!mergedSteps.includes(stage)) mergedSteps.push(stage);
const patchParts = [];
if (existing && existing.patch != null) patchParts.push(existing.patch);
if (typeof file?.patch === "string" && file.patch.trim() !== "") patchParts.push(file.patch);
const joinedPatch = patchParts.join("\n");
entries.set(path, {
path,
// A later step wins the kind: it is the observed state the run left.
kind: existing == null || kind !== ChangeKind.Other ? kind : existing.kind,
added: (existing?.added ?? 0) + parsed.added,
removed: (existing?.removed ?? 0) + parsed.removed,
binary: existing?.binary === true || file?.binary === true,
truncated: existing?.truncated === true || file?.truncated === true,
// Keep the first-seen before-mode and the last-seen after-mode, so the
// pair describes the run's net effect on the file.
beforeMode: existing && existing.beforeMode != null ? existing.beforeMode : nullable(file?.before_mode),
afterMode: file?.after_mode != null ? file.after_mode : existing?.afterMode ?? null,
otherModeChange:
existing?.otherModeChange === true ||
(file?.before_mode != null &&
file?.after_mode != null &&
file.before_mode !== file.after_mode &&
!file.binary &&
parsed.added === 0 &&
parsed.removed === 0),
steps: mergedSteps,
// Preserve every recorded textual patch for a path. A file may be
// changed by several stages, and retaining only the first one would
// make the displayed hunks disagree with the aggregate stat.
patch: joinedPatch.trim() !== "" ? joinedPatch : null,
});
}
}
const files = [...entries.values()];
const pending = stepsWithChanges === 0 && stepsPending > 0;
const totalPartial = partial || files.some((file) => file.truncated) || omitted > 0;
return {
files,
stepsWithChanges,
stepsPending,
added: files.reduce((sum, file) => sum + file.added, 0),
removed: files.reduce((sum, file) => sum + file.removed, 0),
partial: totalPartial,
unavailable,
pending,
missingCaptures,
skipped,
omitted,
diagnostic: [...diagnostics].join(" "),
};
}
// ---------------------------------------------------------------------------
// Entry helpers (FileChangeEntry derived properties)
// ---------------------------------------------------------------------------
/** True when a patch the operator can read is present. */
export function entryHasPatch(entry) {
return !!(entry && entry.patch != null && entry.patch.trim() !== "" && !entry.binary);
}
/** True when the recorded permissions differ and no content change explains it. */
export function entryModeChanged(entry) {
return !!(entry && entry.beforeMode != null && entry.afterMode != null && entry.beforeMode !== entry.afterMode);
}
/** The number of stages that changed this file. */
export function entryStepCount(entry) {
return (entry?.steps ?? []).length;
}
// ---------------------------------------------------------------------------
// Wording (ui/changes/RunChanges.kt + ChangeDiffViewer.kt)
// ---------------------------------------------------------------------------
/**
* The Changes section header's one-line summary: the observed file count, the
* total `+N -M`, and the honest capture caveats. Wording never implies the
* server proved authorship — it reports the workspace change it observed. A run
* with no recorded change, an unavailable capture and a still-running one each
* say exactly that rather than showing a fabricated zero.
*/
export function runChangesHeader(changes) {
if (changes.unavailable) return "Changes · capture unavailable";
if (changes.files.length === 0) {
if (changes.pending) return "Changes · capture pending";
if (changes.partial) return "Changes · partial capture";
if (changes.stepsWithChanges === 0) return "Changes · not recorded for this run";
if (changes.missingCaptures > 0) return "Changes · capture incomplete";
return "Changes · no changes observed";
}
const stat = changeStat(changes.added, changes.removed);
const count = changes.files.length;
const label =
stat === ""
? `${count} ${count === 1 ? "file" : "files"} changed`
: `${count} ${count === 1 ? "file" : "files"} changed · ${stat}`;
if (changes.partial) return `${label} · partial capture`;
if (changes.missingCaptures > 0) return `${label} · capture incomplete`;
return label;
}
/**
* The honest one-line note under the header for a capture that is not complete,
* or "" when the capture was. The wording distinguishes an unavailable capture, a
* partial one (with its counts) and a capture that has recorded nothing yet.
*/
export function runChangesNote(changes) {
if (changes.unavailable) {
return str(changes.diagnostic).trim() !== ""
? str(changes.diagnostic)
: "The workspace snapshot could not be compared; the changes below may be incomplete.";
}
let out = "";
if (changes.partial) {
out = "Partial capture: some changes may be missing.";
const caveats = [];
if (changes.skipped > 0) caveats.push(`${changes.skipped} files skipped`);
if (changes.omitted > 0) caveats.push(`${changes.omitted} omitted`);
const truncated = changes.files.filter((file) => file.truncated).length;
if (truncated > 0) caveats.push(`${truncated} truncated`);
if (caveats.length > 0) out += ` (${caveats.join(", ")})`;
if (str(changes.diagnostic).trim() !== "") out += ` ${str(changes.diagnostic)}`;
}
if (changes.missingCaptures > 0) {
if (out !== "") out += " ";
out += `Missing capture: ${changes.missingCaptures} `;
out += changes.missingCaptures === 1 ? "stage did" : "stages did";
out += " not record changes.";
}
return out.trim();
}
/** The `+N -M` stat, or "" when both counts are zero. Shared by header and row. */
export function changeStat(added, removed) {
let out = "";
if (added > 0) out += `+${added}`;
if (removed > 0) {
if (out !== "") out += " ";
out += `-${removed}`;
}
return out;
}
/**
* The tags shown beside a file row: the traits that change how the entry must be
* read (binary, truncated, a mode-only change), never a fabricated diff.
*/
export function changeEntryTags(entry) {
const tags = [];
if (entry?.binary) tags.push("binary");
if (entry?.truncated) tags.push("truncated");
if (entry?.otherModeChange && !entry.binary) tags.push("mode change");
return tags;
}
/** The row's secondary line: which stage(s) changed it, and how to read it. */
export function changeRowMeta(entry) {
let out = `changed by ${(entry?.steps ?? []).join(" → ")}`;
for (const tag of changeEntryTags(entry)) out += ` · ${tag}`;
if (entryModeChanged(entry) && !entry.binary) {
out += ` · mode ${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}`;
}
return out;
}
/**
* The file list's own summary line: the observed file count and the aggregate
* stat, with the same ambiguity-free wording as the header.
*/
export function changesListSummary(changes) {
const count = `${changes.files.length} ${changes.files.length === 1 ? "file" : "files"} changed`;
const stat = changeStat(changes.added, changes.removed);
return stat === "" ? count : `${count} · ${stat}`;
}
/** Why no change is listed: a pending capture, an unavailable one, or a recorded none. */
export function noChangeDetail(changes) {
if (changes.pending) return "The capture runs after the stage finishes; nothing is recorded yet.";
if (changes.unavailable) return "The workspace snapshot could not be compared, so no changes can be shown.";
if (changes.stepsWithChanges === 0) {
return "This run recorded no change capture (a historical step, or a stage that does not capture).";
}
return "The captured snapshots were identical: the workspace was unchanged.";
}
/** Why a file has no patch to render, in the entry's own recorded terms. */
export function patchUnavailableReason(entry) {
if (entry?.truncated) {
return "The server truncated this file's patch at its capture limit; no diff text was recorded.";
}
if (entry?.otherModeChange) {
return `Only the file's mode changed (${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}); the server recorded no text diff.`;
}
return "The server recorded this change without a patch.";
}
/** The `N of M` position label the viewer shows for its open file. Pure. */
export function changePositionLabel(index, count) {
return `${index + 1} of ${count}`;
}
// The viewer's honest messages, exported so the renderer and the tests share one
// spelling of each.
export const BINARY_DIFF_MESSAGE =
"This is a binary file: the server recorded the change but has no textual diff to show.";
export const TRUNCATED_PATCH_NOTE =
"The server truncated this patch at its capture limit; the raw text is the whole record.";
export const NO_LINE_CHANGES_MESSAGE = "no line changes recorded";
// ---------------------------------------------------------------------------
// Diff line language (ui/chat/ChatDiffCard.kt diffLineSymbol/diffLineColor)
// ---------------------------------------------------------------------------
/** The gutter symbol one line kind is drawn with (`+`/`-`/space). Pure. */
export function diffLineSymbol(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "+";
case ChangeLineKind.Remove:
return "-";
default:
return " ";
}
}
/**
* The CSS class one line kind is drawn in: the app's success hue for an addition,
* its failure hue for a removal and the secondary on-surface role for context.
* The one place a diff line's class is decided, shared by every renderer.
*/
export function diffLineClass(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "diff-add";
case ChangeLineKind.Remove:
return "diff-remove";
default:
return "diff-context";
}
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** An integer parsed from a strictly-numeric string, or null. */
function intOrNull(text) {
return /^[+-]?\d+$/.test(text) ? Number.parseInt(text, 10) : null;
}
/** A value kept as itself when present, else null (`?:` over nullable fields). */
function nullable(value) {
return value == null ? null : value;
}
/** A nullable value as a string ("" for null/undefined), for blank checks. */
function str(value) {
return value == null ? "" : String(value);
}
+112 -9
View File
@@ -26,6 +26,7 @@
import { Protocol, isTerminal, resolveTarget } from "./protocol.js";
import { effectiveStageType } from "./templates.js";
import { formatDuration, secondsSince } from "./runs.js";
// Re-exported so a caller (and the unit tests) can reach the shared "blank is
// the model stage" rule from the graph module it belongs to without a second
@@ -61,6 +62,19 @@ const DRAG_THRESHOLD = 4;
/** The run tab's empty state when the server omitted the run graph (R5). */
export const RUN_GRAPH_MISSING = "This server did not include the run graph.";
/**
* The run tab's guidance note: the browser adaptation of RunGraphTab's own
* sentence, so the app's pinch/tap become mouse wheel/click while everything
* else (the live pulse, the settled finish, the executed/not-executed shapes)
* stays verbatim.
*/
export const RUN_GRAPH_NOTE =
"The running stage pulses with its elapsed time and executed routes flow; " +
"a finished run settles, and with animations off the running stage stays marked. " +
"Solid means executed, dashed and outlined not executed; executed success and " +
"failure routes are drawn thickest. Mouse wheel to zoom, drag to pan, " +
"click a stage for details.";
/**
* The pipeline detail's empty state when the parsed definition declares no
* stages. The template gallery has its own Android-authored analogue
@@ -203,6 +217,18 @@ export function edgeIsExecuted(edge, runState) {
return inSet(runState.takenRoutes, edge) || inSet(runState.takenRoutes, edge.id);
}
/**
* The key of the stage a run is executing right now, else null. Only a live run
* (still `executing`) has an active stage, so a finished run never carries a
* halo or an elapsed badge. Pure: drawing, the elapsed badge and the tests share
* one definition of "active".
*/
export function activeStage(runState) {
if (runState == null || !runState.executing) return null;
const key = runState.currentStage;
return key == null || key === "" ? null : key;
}
// ---------------------------------------------------------------------------
// Pure viewport maths (WorkflowGraph.kt)
// ---------------------------------------------------------------------------
@@ -895,19 +921,38 @@ function pathFromPoints(points) {
* space does nothing.
*
* Options:
* runState — omitted for the definition view (every route executed);
* R5 passes `{ visitedStages, takenRoutes }` to dash the
* routes a run did not take.
* runState — omitted for the definition view (every route executed and
* no legend); R5 passes the `runGraphState(run)` shape
* ({ visitedStages, takenRoutes, currentStage, executing,
* currentStageStartedAt }) to render the run: executed nodes
* solid, unvisited ones hollow/dashed, executed routes
* arrowed, the live stage's halo + elapsed badge and the
* Executed / Not executed legend.
* animationsEnabled — honour the caller's animation gate. Defaults to the
* page's `prefers-reduced-motion` setting; when false the
* active stage keeps a static ring instead of pulsing.
* expanded — start with the taller panel.
* onStageTap — called with the node key on a node click.
* onStageTap — called with the node key on a node click. When supplied
* (the run tab), the click opens the caller's own stage
* pane and no definition pane is drawn.
* onExpandedChange — called with the new expanded flag on toggle.
* metrics — layout metrics override (tests).
*
* Returns `{ unmount }`; call it before discarding the container so the wheel,
* pointer and resize listeners never leak.
* pointer, resize and elapsed-timer handles never leak.
*/
export function mount(container, graph, options = {}) {
const runState = options.runState ?? null;
const activeKey = activeStage(runState);
const reducedMotion =
typeof window !== "undefined" &&
typeof window.matchMedia === "function" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// The caller may force animations off; otherwise the page's motion preference
// decides. A finished run never animates regardless (activeKey is null then).
const animationsEnabled =
options.animationsEnabled === undefined ? !reducedMotion : Boolean(options.animationsEnabled);
const pulse = activeKey != null && animationsEnabled;
const layout = layoutGraph(graph, options.metrics);
const stagesByKey = new Map((graph?.stages ?? []).map((stage) => [stage.key, stage]));
@@ -983,6 +1028,7 @@ export function mount(container, graph, options = {}) {
// Node layer: real buttons, positioned in graph space.
const nodeLayer = el("div", "graph-node-layer");
let elapsedBadge = null;
for (const node of layout.nodes) {
const kind = graphNodeKind(node.terminal, node.key, stagesByKey.get(node.key)?.type);
const button = el("button", `graph-node ${nodeKindClass(kind)}`, node.label);
@@ -998,13 +1044,25 @@ export function mount(container, graph, options = {}) {
? `${node.label}, open details`
: `Stage ${node.key}, ${node.type}, open details`,
);
if (!stageIsExecuted(node.key, runState)) button.classList.add("not-executed");
const executed = stageIsExecuted(node.key, runState);
if (runState != null) button.classList.add(executed ? "executed" : "not-executed");
if (node.key === activeKey) {
button.classList.add("active");
if (pulse) button.classList.add("pulsing");
const badge = el("span", "graph-elapsed");
badge.setAttribute("aria-hidden", "true");
button.append(badge);
elapsedBadge = badge;
}
button.addEventListener("click", (event) => {
if (dragged) {
event.preventDefault();
return;
}
selectNode(node.key);
// The run tab owns its own stage pane (the shared timeline visit pane), so
// a supplied handler replaces the definition pane rather than stacking on it.
if (typeof options.onStageTap === "function") options.onStageTap(node.key);
else selectNode(node.key);
});
nodeLayer.append(button);
}
@@ -1026,7 +1084,27 @@ export function mount(container, graph, options = {}) {
controls.append(fitButton, expandButton);
viewport.append(controls);
// The definition pane, hidden until a node is clicked.
// The legend, only under a run (never the definition-only view): a solid,
// arrowed swatch means "executed", a dashed, arrowless one "not executed",
// matching what the graph draws.
if (runState != null) {
const legend = el("div", "graph-legend");
legend.setAttribute("role", "note");
legend.setAttribute("aria-label", "Executed and not executed routes");
for (const entry of [
{ label: "Executed", executed: true },
{ label: "Not executed", executed: false },
]) {
const item = el("span", "graph-legend-entry");
item.append(el("span", `graph-legend-swatch ${entry.executed ? "executed" : "not-executed"}`));
item.append(el("span", "graph-legend-label", entry.label));
legend.append(item);
}
viewport.append(legend);
}
// The definition pane, hidden until a node is clicked (definition view only;
// the run tab opens its own pane through onStageTap instead).
const pane = el("div", "graph-pane");
pane.hidden = true;
root.append(viewport, pane);
@@ -1122,7 +1200,28 @@ export function mount(container, graph, options = {}) {
pane.replaceChildren(...children);
pane.hidden = false;
if (typeof options.onStageTap === "function") options.onStageTap(key);
}
// --- Elapsed badge (live run only) ---------------------------------------
function updateElapsed() {
if (!elapsedBadge) return;
const seconds = secondsSince(runState?.currentStageStartedAt, Date.now());
elapsedBadge.textContent = seconds == null ? "" : formatDuration(seconds);
}
let elapsedTimer = null;
if (elapsedBadge != null) {
updateElapsed();
// Tick only while the graph has a live stage with a known start; a still
// ring (reduced motion) and a finished run never wake up once a second.
if (
pulse &&
typeof setInterval === "function" &&
String(runState?.currentStageStartedAt ?? "").trim() !== ""
) {
elapsedTimer = setInterval(updateElapsed, 1000);
}
}
// --- Interactions --------------------------------------------------------
@@ -1230,6 +1329,10 @@ export function mount(container, graph, options = {}) {
return {
unmount() {
if (elapsedTimer != null) {
clearInterval(elapsedTimer);
elapsedTimer = null;
}
resizeObserver?.disconnect();
viewport.removeEventListener("pointerdown", onPointerDown);
viewport.removeEventListener("pointermove", onPointerMove);
+65 -5
View File
@@ -36,9 +36,9 @@ import { effectiveStageType } from "./templates.js";
/**
* The run-detail tabs, Summary first so it is the default selection. The Graph
* tab is present (Android `runDetailTabs`) but has no rendered body yet — it is
* the R5 item — so the renderer filters it out until then. The timeline keeps
* Android's stable key `steps` with the visible title `Timeline`.
* 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" },
@@ -48,8 +48,8 @@ export const RUN_DETAIL_TABS = [
{ key: "steps", label: "Timeline" },
];
/** The tabs the browser currently renders (the Graph body is the R5 item). */
export const RENDERED_RUN_TABS = RUN_DETAIL_TABS.filter((tab) => tab.key !== "graph");
/** The tabs the browser renders: all of them, including the Graph body (R5). */
export const RENDERED_RUN_TABS = RUN_DETAIL_TABS;
// The empty-state sentences, exactly as the app spells them.
export const EMPTY_INPUT_MESSAGE = "No input recorded.";
@@ -330,6 +330,66 @@ export function graphEdges(graph) {
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)
// ---------------------------------------------------------------------------
+166
View File
@@ -610,6 +610,74 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
}
.graph-control:hover { border-color: var(--accent); color: var(--accent); }
/* The run-mode legend (R5), pinned top-start opposite the Fit/expand controls.
A solid, arrowed swatch means "executed"; a dashed, arrowless one "not
executed". Never shown for the definition-only view. */
.graph-legend {
position: absolute;
top: 8px;
left: 8px;
z-index: 2;
display: flex;
gap: 12px;
align-items: center;
padding: 4px 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: color-mix(in srgb, var(--surface) 85%, transparent);
font-size: 12px;
color: var(--muted);
}
.graph-legend-entry { display: inline-flex; gap: 6px; align-items: center; }
.graph-legend-swatch {
position: relative;
width: 26px;
border-top: 3px solid var(--muted);
}
.graph-legend-swatch.executed { border-top-color: var(--text); }
/* A small filled arrowhead on the executed swatch, matching the drawn head. */
.graph-legend-swatch.executed::after {
content: "";
position: absolute;
top: -6px;
right: -1px;
border-left: 7px solid var(--text);
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
}
.graph-legend-swatch.not-executed { border-top-style: dashed; }
/* The live active stage (R5): a ring around the node plus a soft glow, pulsing
while the run executes and static when the user prefers reduced motion. */
.graph-node.active {
border-color: var(--accent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 40%, transparent);
}
.graph-node.active.pulsing { animation: graph-halo-pulse 1.6s ease-in-out infinite; }
@keyframes graph-halo-pulse {
0%,
100% { box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 55%, transparent); }
50% { box-shadow: 0 0 0 7px color-mix(in srgb, var(--accent) 20%, transparent); }
}
@media (prefers-reduced-motion: reduce) {
.graph-node.active.pulsing { animation: none; }
}
/* The live elapsed-time badge on the active node. */
.graph-elapsed {
position: absolute;
bottom: -9px;
right: 6px;
padding: 0 5px;
border: 1px solid color-mix(in srgb, var(--accent) 45%, var(--border));
border-radius: 999px;
background: var(--surface);
color: var(--accent);
font-size: 10px;
font-weight: 600;
line-height: 16px;
}
/* The definition pane opened from a node click. */
.graph-pane {
display: grid;
@@ -862,3 +930,101 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
.live-reconnecting .live-dot { opacity: 0.4; }
.live-not-live { color: var(--muted); }
.live-not-live .live-dot { opacity: 0.4; }
/* ---------------------------------------------------------------------------
Run summary Changes (parity R4): the observed-file list and the full-screen
rendered/raw diff viewer. Hand-written, the app's dark palette.
--------------------------------------------------------------------------- */
.changes { display: grid; gap: 8px; }
.changes-summary { color: var(--accent); font-weight: 600; font-size: 13px; }
.changes-note { font-size: 12px; }
.changes-empty { font-size: 13px; }
.changes-list { display: grid; gap: 4px; }
.change-row {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 6px 8px;
border-radius: 8px;
cursor: pointer;
}
.change-row:hover { background: var(--surface-2); }
.change-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.change-kind { font-weight: 600; font-size: 12px; min-width: 62px; }
.change-main { flex: 1; min-width: 0; display: grid; gap: 2px; }
.change-path { overflow-wrap: anywhere; }
.change-meta { font-size: 12px; }
.change-stat { display: flex; gap: 6px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
.stat-add { color: var(--ok); }
.stat-del { color: var(--bad); }
/* Full-screen diff viewer overlay (the artifact-viewer idiom). */
.change-viewer {
position: fixed;
inset: 0;
z-index: 30;
display: flex;
flex-direction: column;
gap: 12px;
padding: 20px;
background: rgba(0, 0, 0, 0.86);
}
.change-viewer-head { display: flex; gap: 12px; align-items: flex-start; }
.change-viewer-titles { flex: 1; min-width: 0; display: grid; gap: 2px; }
.change-viewer-title-row { display: flex; gap: 10px; align-items: baseline; flex-wrap: wrap; }
.change-viewer-stat { font-size: 13px; }
.change-viewer-path { overflow-wrap: anywhere; }
.change-viewer-position { font-size: 12px; }
.change-viewer-controls { display: flex; gap: 8px; align-items: center; }
.change-viewer-spacer { flex: 1; }
.change-form { font-size: 12px; }
.change-form.active { border-color: var(--accent); color: var(--accent); }
.change-form:disabled { opacity: 0.45; }
.change-page:disabled { opacity: 0.4; cursor: not-allowed; }
.change-viewer-body { flex: 1; min-height: 0; overflow: auto; display: grid; gap: 16px; align-content: start; }
.change-honest {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
padding: 32px;
text-align: center;
}
.change-raw {
margin: 0;
padding: 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--surface-2);
font-size: 12px;
white-space: pre;
overflow: auto;
}
.change-diff { display: grid; gap: 12px; align-content: start; }
.change-diff-stat { display: flex; gap: 8px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
.change-diff-note { font-size: 12px; }
.change-hunk { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
.change-hunk-head {
padding: 4px 8px;
background: var(--surface-2);
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
}
.change-hunk-lines { overflow-x: auto; background: var(--surface); padding: 6px 0; }
.change-line {
display: flex;
gap: 10px;
padding: 0 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 12px;
white-space: pre;
}
.change-gutter { color: var(--muted); user-select: none; }
.diff-add { color: var(--ok); }
.diff-remove { color: var(--bad); }
.diff-context { color: var(--muted); }
+562
View File
@@ -0,0 +1,562 @@
// Pure unit tests for the run summary's Changes section and its diff viewer:
// the kind mapping and labels, the unified-patch parser (hunks, line numbers,
// stat counts, the `\ No newline` marker and header closing), the cross-step
// aggregation (kind merge, stat sums, binary/truncated OR, mode first/last),
// every header/note/detail wording variant and the row/viewer helpers.
// No server, no DOM.
import { test } from "node:test";
import assert from "node:assert/strict";
import {
ChangeKind,
ChangeLineKind,
BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE,
TRUNCATED_PATCH_NOTE,
changeEntryTags,
changeKind,
changeKindLabel,
changeKindTitle,
changePositionLabel,
changeRowMeta,
changeStat,
changesListSummary,
diffLineClass,
diffLineSymbol,
entryHasPatch,
entryModeChanged,
gutterText,
gutterWidth,
noChangeDetail,
parseUnifiedPatch,
patchUnavailableReason,
runChanges,
runChangesHeader,
runChangesNote,
} from "../src/changes.js";
// A step file-change with sane defaults, overridable per test.
function file(overrides = {}) {
return { path: "a.txt", kind: "modified", patch: "", ...overrides };
}
// A run step with a file_changes capture, overridable per test.
function step(overrides = {}) {
return { stage: "s", status: "completed", sequence: 1, file_changes: null, ...overrides };
}
// ---------------------------------------------------------------------------
// Kind mapping
// ---------------------------------------------------------------------------
test("changeKind trims and lowercases, never inventing a kind", () => {
assert.equal(changeKind("added"), ChangeKind.Added);
assert.equal(changeKind(" Deleted "), ChangeKind.Deleted);
assert.equal(changeKind("MODIFIED"), ChangeKind.Modified);
assert.equal(changeKind("copied"), ChangeKind.Other);
assert.equal(changeKind(""), ChangeKind.Other);
assert.equal(changeKind(null), ChangeKind.Other);
});
test("changeKindLabel and changeKindTitle spell the app's words", () => {
assert.equal(changeKindLabel(ChangeKind.Added), "added");
assert.equal(changeKindLabel(ChangeKind.Modified), "modified");
assert.equal(changeKindLabel(ChangeKind.Deleted), "deleted");
assert.equal(changeKindLabel(ChangeKind.Other), "changed");
assert.equal(changeKindTitle(ChangeKind.Added), "Added");
assert.equal(changeKindTitle(ChangeKind.Other), "Changed");
});
// ---------------------------------------------------------------------------
// changeStat and changesListSummary
// ---------------------------------------------------------------------------
test("changeStat omits a zero side and is blank when both are zero", () => {
assert.equal(changeStat(3, 2), "+3 -2");
assert.equal(changeStat(3, 0), "+3");
assert.equal(changeStat(0, 2), "-2");
assert.equal(changeStat(0, 0), "");
});
test("changesListSummary keeps the file(s) wording and appends the stat", () => {
const one = { files: [{}], added: 2, removed: 0 };
assert.equal(changesListSummary(one), "1 file changed · +2");
assert.equal(changesListSummary({ files: [{}, {}], added: 0, removed: 0 }), "2 files changed");
});
// ---------------------------------------------------------------------------
// parseUnifiedPatch
// ---------------------------------------------------------------------------
test("parseUnifiedPatch treats a blank patch as an empty diff", () => {
for (const blank of ["", " ", "\n", null, undefined]) {
assert.deepEqual(parseUnifiedPatch(blank), {
raw: "",
headerLines: [],
hunks: [],
added: 0,
removed: 0,
});
}
});
test("parseUnifiedPatch numbers a single hunk and counts the body", () => {
const patch = [
"--- a/x.txt",
"+++ b/x.txt",
"@@ -1,3 +1,3 @@",
" ctx",
"-old",
"+new",
" tail",
].join("\n");
const parsed = parseUnifiedPatch(patch);
assert.equal(parsed.raw, patch);
assert.deepEqual(parsed.headerLines, ["--- a/x.txt", "+++ b/x.txt"]);
assert.equal(parsed.hunks.length, 1);
const hunk = parsed.hunks[0];
assert.equal(hunk.header, "@@ -1,3 +1,3 @@");
assert.deepEqual([hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], [1, 3, 1, 3]);
assert.deepEqual(
hunk.lines.map((line) => [line.kind, line.text, line.oldLine, line.newLine]),
[
[ChangeLineKind.Context, "ctx", 1, 1],
[ChangeLineKind.Remove, "old", 2, 0],
[ChangeLineKind.Add, "new", 0, 2],
[ChangeLineKind.Context, "tail", 3, 3],
],
);
assert.equal(parsed.added, 1);
assert.equal(parsed.removed, 1);
});
test("parseUnifiedPatch defaults a missing count to 1", () => {
const parsed = parseUnifiedPatch("@@ -5 +7 @@\n-old\n+new");
const hunk = parsed.hunks[0];
assert.deepEqual([hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount], [5, 1, 7, 1]);
assert.equal(parsed.added, 1);
assert.equal(parsed.removed, 1);
});
test("parseUnifiedPatch flags a `\\ No newline` marker without numbering it", () => {
const parsed = parseUnifiedPatch(
["@@ -1 +1 @@", "-one", "\\ No newline at end of file", "+two"].join("\n"),
);
const lines = parsed.hunks[0].lines;
assert.equal(lines[1].noNewlineMarker, true);
assert.equal(lines[1].text, "\\ No newline at end of file");
assert.equal(lines[1].oldLine, 0);
assert.equal(lines[1].newLine, 0);
assert.equal(lines[1].kind, ChangeLineKind.Context);
});
test("a `---`/`+++` header closes the current hunk instead of numbering into it", () => {
const parsed = parseUnifiedPatch(
[
"--- a/x",
"+++ b/x",
"@@ -1 +1 @@",
"-old",
"+new",
"--- a/y",
"+++ b/y",
"@@ -1 +1 @@",
"-alt",
"+neu",
].join("\n"),
);
assert.equal(parsed.hunks.length, 2);
assert.deepEqual(
parsed.hunks[0].lines.map((line) => line.text),
["old", "new"],
);
assert.deepEqual(
parsed.hunks[1].lines.map((line) => line.text),
["alt", "neu"],
);
assert.equal(parsed.headerLines.filter((line) => line.startsWith("--- ")).length, 2);
assert.equal(parsed.added, 2);
assert.equal(parsed.removed, 2);
});
test("an unrecognised tail is kept as unnumbered context and header lines before a hunk are kept", () => {
const parsed = parseUnifiedPatch(
["index abc..def 100644", "--- a/x", "+++ b/x", "@@ -1 +1 @@", "-old", "+new", "trailing junk"].join("\n"),
);
assert.equal(parsed.headerLines[0], "index abc..def 100644");
const tail = parsed.hunks[0].lines.at(-1);
assert.equal(tail.kind, ChangeLineKind.Context);
assert.equal(tail.text, "trailing junk");
assert.equal(tail.oldLine, 0);
assert.equal(tail.newLine, 0);
});
test("a trailing newline becomes a numbered empty context line", () => {
const parsed = parseUnifiedPatch("@@ -1 +1 @@\n ctx\n");
const lines = parsed.hunks[0].lines;
assert.equal(lines.length, 2);
assert.deepEqual([lines[1].text, lines[1].oldLine, lines[1].newLine], ["", 2, 2]);
});
// ---------------------------------------------------------------------------
// Aggregation
// ---------------------------------------------------------------------------
test("a null capture that is running/waiting is pending, otherwise a missing capture", () => {
const running = runChanges([step({ status: "running" }), step({ status: "waiting" })]);
assert.equal(running.pending, true);
assert.equal(running.missingCaptures, 0);
assert.equal(running.stepsWithChanges, 0);
const missing = runChanges([step({ status: "completed" }), step({ status: "failed" })]);
assert.equal(missing.pending, false);
assert.equal(missing.missingCaptures, 2);
});
test("a present capture with no files is a captured no-change", () => {
const changes = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [] } }),
]);
assert.equal(changes.stepsWithChanges, 1);
assert.deepEqual(changes.files, []);
assert.equal(changes.partial, false);
assert.equal(runChangesHeader(changes), "Changes · no changes observed");
assert.equal(noChangeDetail(changes), "The captured snapshots were identical: the workspace was unchanged.");
});
test("the later step wins the kind, but `other` never downgrades it", () => {
const changes = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [file({ path: "x", kind: "modified" })] } }),
step({ stage: "b", file_changes: { status: "complete", files: [file({ path: "x", kind: "added" })] } }),
]);
assert.equal(changes.files.length, 1);
assert.equal(changes.files[0].kind, ChangeKind.Added);
assert.deepEqual(changes.files[0].steps, ["a", "b"]);
const downgrade = runChanges([
step({ stage: "a", file_changes: { status: "complete", files: [file({ path: "x", kind: "added" })] } }),
step({ stage: "b", file_changes: { status: "complete", files: [file({ path: "x", kind: "copied" })] } }),
]);
assert.equal(downgrade.files[0].kind, ChangeKind.Added);
});
test("stat sums, binary/truncated OR and mode first/last-seen across steps", () => {
const changes = runChanges([
step({
stage: "a",
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "@@ -1 +1 @@\n-old\n+new",
before_mode: "0644",
after_mode: "0644",
}),
],
},
}),
step({
stage: "b",
file_changes: {
status: "complete",
files: [
file({
path: "x",
kind: "modified",
patch: "@@ -1 +1 @@\n-gone\n+kept",
binary: true,
truncated: true,
before_mode: "0755",
after_mode: "0755",
}),
],
},
}),
]);
const entry = changes.files[0];
assert.equal(entry.added, 2);
assert.equal(entry.removed, 2);
assert.equal(entry.binary, true);
assert.equal(entry.truncated, true);
assert.equal(entry.beforeMode, "0644"); // first-seen
assert.equal(entry.afterMode, "0755"); // last-seen
assert.equal(entryModeChanged(entry), true);
assert.equal(entryHasPatch(entry), false); // binary hides the patch
assert.equal(changes.added, 2);
assert.equal(changes.removed, 2);
});
test("changed-by lists the stage names in run order, deduped", () => {
const changes = runChanges([
step({ stage: "implementer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
step({ stage: "reviewer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
step({ stage: "implementer", file_changes: { status: "complete", files: [file({ path: "x" })] } }),
]);
assert.deepEqual(changes.files[0].steps, ["implementer", "reviewer"]);
assert.equal(changeRowMeta(changes.files[0]), "changed by implementer → reviewer");
});
test("a blank stage name falls back to `stage` and blank paths are skipped", () => {
const changes = runChanges([
step({ stage: " ", file_changes: { status: "complete", files: [file({ path: "x" }), file({ path: " " })] } }),
]);
assert.equal(changes.files.length, 1);
assert.deepEqual(changes.files[0].steps, ["stage"]);
});
test("partial is OR'd from the capture status, a truncated file or any omitted count", () => {
assert.equal(
runChanges([step({ file_changes: { status: "partial", files: [] } })]).partial,
true,
);
assert.equal(
runChanges([step({ file_changes: { status: "complete", files: [file({ truncated: true })] } })]).partial,
true,
);
assert.equal(
runChanges([step({ file_changes: { status: "complete", files: [], omitted: 2 } })]).partial,
true,
);
});
test("diagnostics from several captures are joined with a space, deduped", () => {
const changes = runChanges([
step({ file_changes: { status: "partial", files: [], diagnostic: "why one" } }),
step({ file_changes: { status: "partial", files: [], diagnostic: "why one" } }),
step({ file_changes: { status: "partial", files: [], diagnostic: "why two" } }),
]);
assert.equal(changes.diagnostic, "why one why two");
});
// ---------------------------------------------------------------------------
// Header, note and detail wording
// ---------------------------------------------------------------------------
test("runChangesHeader covers every empty-capture variant", () => {
assert.equal(
runChangesHeader({ unavailable: true, files: [], partial: false, pending: false, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · capture unavailable",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: true, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · capture pending",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: true, pending: false, stepsWithChanges: 1, missingCaptures: 0 }),
"Changes · partial capture",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 0, missingCaptures: 0 }),
"Changes · not recorded for this run",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 1, missingCaptures: 1 }),
"Changes · capture incomplete",
);
assert.equal(
runChangesHeader({ unavailable: false, files: [], partial: false, pending: false, stepsWithChanges: 2, missingCaptures: 0 }),
"Changes · no changes observed",
);
});
test("runChangesHeader counts files, omits a zero stat side and appends the caveats", () => {
const one = { unavailable: false, partial: false, pending: false, stepsWithChanges: 1, missingCaptures: 0, added: 4, removed: 0, files: [{}] };
assert.equal(runChangesHeader(one), "1 file changed · +4");
const many = { ...one, added: 0, removed: 0, files: [{}, {}] };
assert.equal(runChangesHeader(many), "2 files changed");
const partial = { ...one, partial: true, added: 4, removed: 2, files: [{}, {}] };
assert.equal(runChangesHeader(partial), "2 files changed · +4 -2 · partial capture");
const incomplete = { ...one, added: 4, removed: 2, files: [{}, {}], missingCaptures: 1 };
assert.equal(runChangesHeader(incomplete), "2 files changed · +4 -2 · capture incomplete");
});
test("runChangesNote spells the partial, missing and unavailable notes", () => {
assert.equal(
runChangesNote({ unavailable: true, diagnostic: "" }),
"The workspace snapshot could not be compared; the changes below may be incomplete.",
);
assert.equal(
runChangesNote({ unavailable: true, diagnostic: "server says so" }),
"server says so",
);
assert.equal(
runChangesNote({
unavailable: false,
partial: true,
skipped: 8,
omitted: 0,
diagnostic: "Excluded protected files.",
files: [],
missingCaptures: 1,
}),
"Partial capture: some changes may be missing. (8 files skipped) Excluded protected files. " +
"Missing capture: 1 stage did not record changes.",
);
assert.equal(
runChangesNote({
unavailable: false,
partial: true,
skipped: 0,
omitted: 3,
diagnostic: "",
files: [{ truncated: true }, { truncated: true }],
missingCaptures: 2,
}),
"Partial capture: some changes may be missing. (3 omitted, 2 truncated) " +
"Missing capture: 2 stages did not record changes.",
);
assert.equal(runChangesNote({ unavailable: false, partial: false, missingCaptures: 0 }), "");
assert.equal(
runChangesNote({ unavailable: false, partial: false, missingCaptures: 1 }),
"Missing capture: 1 stage did not record changes.",
);
});
test("noChangeDetail distinguishes pending, unavailable, not-recorded and unchanged", () => {
assert.equal(
noChangeDetail({ pending: true }),
"The capture runs after the stage finishes; nothing is recorded yet.",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: true }),
"The workspace snapshot could not be compared, so no changes can be shown.",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: false, stepsWithChanges: 0 }),
"This run recorded no change capture (a historical step, or a stage that does not capture).",
);
assert.equal(
noChangeDetail({ pending: false, unavailable: false, stepsWithChanges: 2 }),
"The captured snapshots were identical: the workspace was unchanged.",
);
});
test("changeEntryTags and changeRowMeta spell the tags and mode exactly", () => {
const binary = { binary: true, truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755", steps: ["a"] };
assert.deepEqual(changeEntryTags(binary), ["binary"]);
assert.equal(changeRowMeta(binary), "changed by a · binary");
const truncated = { binary: false, truncated: true, otherModeChange: false, steps: ["a", "b"] };
assert.deepEqual(changeEntryTags(truncated), ["truncated"]);
assert.equal(changeRowMeta(truncated), "changed by a → b · truncated");
const modeOnly = { binary: false, truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755", steps: ["a"] };
assert.deepEqual(changeEntryTags(modeOnly), ["mode change"]);
assert.equal(changeRowMeta(modeOnly), "changed by a · mode change · mode 0644→0755");
});
test("patchUnavailableReason names the truncation, the mode-only change, else the bare record", () => {
assert.equal(
patchUnavailableReason({ truncated: true }),
"The server truncated this file's patch at its capture limit; no diff text was recorded.",
);
assert.equal(
patchUnavailableReason({ truncated: false, otherModeChange: true, beforeMode: "0644", afterMode: "0755" }),
"Only the file's mode changed (0644→0755); the server recorded no text diff.",
);
assert.equal(
patchUnavailableReason({ truncated: false, otherModeChange: false }),
"The server recorded this change without a patch.",
);
});
test("the viewer's honest messages are the app's exact wording", () => {
assert.equal(
BINARY_DIFF_MESSAGE,
"This is a binary file: the server recorded the change but has no textual diff to show.",
);
assert.equal(
TRUNCATED_PATCH_NOTE,
"The server truncated this patch at its capture limit; the raw text is the whole record.",
);
assert.equal(NO_LINE_CHANGES_MESSAGE, "no line changes recorded");
});
// ---------------------------------------------------------------------------
// Viewer helpers
// ---------------------------------------------------------------------------
test("changePositionLabel and gutterWidth line up", () => {
assert.equal(changePositionLabel(0, 3), "1 of 3");
assert.equal(changePositionLabel(2, 3), "3 of 3");
assert.equal(gutterWidth({ lines: [] }), 1);
assert.equal(gutterWidth({ lines: [{ oldLine: 9, newLine: 0 }, { oldLine: 0, newLine: 12 }] }), 2);
assert.equal(gutterText(0, 2), " ");
assert.equal(gutterText(7, 2), " 7");
});
test("diffLineSymbol and diffLineClass are the app's one diff language", () => {
assert.equal(diffLineSymbol(ChangeLineKind.Add), "+");
assert.equal(diffLineSymbol(ChangeLineKind.Remove), "-");
assert.equal(diffLineSymbol(ChangeLineKind.Context), " ");
assert.equal(diffLineClass(ChangeLineKind.Add), "diff-add");
assert.equal(diffLineClass(ChangeLineKind.Remove), "diff-remove");
assert.equal(diffLineClass(ChangeLineKind.Context), "diff-context");
});
// ---------------------------------------------------------------------------
// A full aggregate matches the section it renders
// ---------------------------------------------------------------------------
test("runChanges derives run 438's shape: 22 files, partial, one missing capture", () => {
// Six steps, 23 recorded file rows for 22 unique paths, one step without a
// capture, every capture partial with a diagnostic.
const diag = "Excluded protected, symlinked, oversized or unreadable files; this is not a complete workspace diff.";
const patch = "@@ -1 +1 @@\n-old\n+new";
const steps = [
step({
stage: "implementer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: [
file({ path: "docs/notes.md", kind: "added", patch }),
file({ path: "internal/server/retry_test.go", kind: "modified", patch }),
file({ path: "internal/server/runner.go", kind: "modified", patch }),
],
},
}),
step({ stage: "reviewer", file_changes: { status: "partial", skipped: 2, diagnostic: diag, files: [] } }),
step({
stage: "implementer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: [file({ path: "internal/server/retry_test.go", kind: "modified", patch })],
},
}),
step({ stage: "reviewer", file_changes: { status: "partial", skipped: 2, diagnostic: diag, files: [] } }),
step({ stage: "ui_reviewer" }),
step({
stage: "committer",
file_changes: {
status: "partial",
skipped: 2,
diagnostic: diag,
files: Array.from({ length: 19 }, (_, i) => file({ path: `android/file${i}.kt`, kind: "modified", patch })),
},
}),
];
const changes = runChanges(steps);
assert.equal(changes.files.length, 22);
assert.equal(changes.stepsWithChanges, 5);
assert.equal(changes.missingCaptures, 1);
assert.equal(changes.partial, true);
assert.equal(changes.unavailable, false);
assert.equal(changes.pending, false);
assert.equal(changes.skipped, 10);
assert.equal(changes.files.find((f) => f.path === "internal/server/retry_test.go").added, 2);
assert.equal(
runChangesHeader(changes),
`22 files changed · +23 -23 · partial capture`,
);
assert.ok(runChangesNote(changes).startsWith("Partial capture: some changes may be missing. (10 files skipped)"));
assert.ok(runChangesNote(changes).endsWith("Missing capture: 1 stage did not record changes."));
});
+112
View File
@@ -14,6 +14,7 @@ import {
MAX_SCALE,
PIPELINE_GRAPH_EMPTY,
RUN_GRAPH_MISSING,
RUN_GRAPH_NOTE,
NO_NODE_DETAILS,
STAGE_DEFINITION_TITLE,
configLabel,
@@ -33,7 +34,11 @@ import {
clampOffset,
fitScale,
zoomAbout,
stageIsExecuted,
edgeIsExecuted,
activeStage,
} from "../src/graph.js";
import { runGraphState } from "../src/runDetail.js";
// ---------------------------------------------------------------------------
// Fixtures
@@ -369,12 +374,119 @@ test("terminalFields lists the incoming routes into a terminal", () => {
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.ok(RUN_GRAPH_NOTE.includes("pulses"));
assert.ok(RUN_GRAPH_NOTE.includes("Mouse wheel to zoom"));
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");
+2 -2
View File
@@ -79,10 +79,10 @@ test("RUN_DETAIL_TABS is the Android order, Summary first, Timeline keyed 'steps
RUN_DETAIL_TABS.map((tab) => tab.label),
["Summary", "Graph", "Input", "Output", "Timeline"],
);
// The Graph body is the R5 item; only the other four render today.
// The Graph body (R5) now renders too, so every tab is present.
assert.deepEqual(
RENDERED_RUN_TABS.map((tab) => tab.label),
["Summary", "Input", "Output", "Timeline"],
["Summary", "Graph", "Input", "Output", "Timeline"],
);
});
+407 -2
View File
@@ -635,11 +635,14 @@ try {
await page.waitForSelector(".list.runs .run-row", { timeout: 25000 });
await openRunDetail(430);
// The run-detail tabs, in the app's order (the Graph body is the R5 item).
// The run-detail tabs, in the app's order (Summary / Graph / Input / Output /
// Timeline; the Graph body is R5 and now rendered).
const runTabs = await page.evaluate(
`[...document.querySelectorAll(".detail .detail-tabs .detail-tab")].map((n) => n.textContent)`,
);
if (JSON.stringify(runTabs) !== JSON.stringify(["Summary", "Input", "Output", "Timeline"])) {
if (
JSON.stringify(runTabs) !== JSON.stringify(["Summary", "Graph", "Input", "Output", "Timeline"])
) {
throw new Error(`run tabs are wrong: ${runTabs.join(",")}`);
}
console.log(` run tabs: ${runTabs.join(" / ")}`);
@@ -827,6 +830,137 @@ try {
console.log(` timeline empty state: ${emptyTimeline}`);
shots.push(await page.screenshot(`${out}/26-run-428-timeline-empty.png`));
// R5: the run-detail Graph tab — the shared workflow graph in run mode. Run 438
// is a finished run with several visits and the full outcome set: its graph
// shows the Executed / Not executed legend, solid executed nodes and arrowed
// executed routes, and dashed untaken routes. Clicking a stage opens the
// existing visit pane (with its Verdict) at that stage's latest visit. Run 440
// shows the hollow, dashed nodes for the stages the failed run never reached.
step("opening run 438 and capturing its Graph tab (R5)");
await page.click('.list.runs .run-row-meta[data-run-id="438"]');
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await page.clickText(".detail .detail-tabs .detail-tab", "Graph");
await page.waitForSelector(".run-detail .graph-note", { timeout: 15000 });
const runGraphNote = await text(".run-detail .graph-note");
if (!runGraphNote.includes("pulses with its elapsed time")) {
throw new Error(`unexpected run graph note: ${runGraphNote}`);
}
await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 });
await eventually(async () => {
const current = await graphState();
return current != null && current.scale > 0;
}, { what: "the run graph to lay out" });
const legend = await page.evaluate(
`[...document.querySelectorAll(".run-detail .graph-legend .graph-legend-label")].map((n) => n.textContent)`,
);
if (JSON.stringify(legend) !== JSON.stringify(["Executed", "Not executed"])) {
throw new Error(`the run graph legend is wrong: ${JSON.stringify(legend)}`);
}
const graph438 = await page.evaluate(`(() => ({
executedNodes: document.querySelectorAll(".run-detail .graph-node.executed").length,
notExecutedNodes: document.querySelectorAll(".run-detail .graph-node.not-executed").length,
executedEdges: document.querySelectorAll(".run-detail .graph-edge-path.executed").length,
notExecutedEdges: document.querySelectorAll(".run-detail .graph-edge-path.not-executed").length,
arrowedEdges: document.querySelectorAll('.run-detail .graph-edge-path[marker-end]').length,
active: document.querySelectorAll(".run-detail .graph-node.active").length,
}))()`);
if (!graph438.executedNodes || !graph438.executedEdges || !graph438.notExecutedEdges) {
throw new Error(`run 438 should show executed stages and both executed/untaken routes: ${JSON.stringify(graph438)}`);
}
if (graph438.arrowedEdges !== graph438.executedEdges) {
throw new Error(`only executed routes carry an arrowhead: ${JSON.stringify(graph438)}`);
}
if (graph438.active !== 0) {
throw new Error(`a finished run must have no active halo: ${JSON.stringify(graph438)}`);
}
console.log(
` run 438 graph: ${graph438.executedNodes} executed / ${graph438.notExecutedNodes} not-executed nodes, ` +
`${graph438.executedEdges} arrowed / ${graph438.notExecutedEdges} dashed routes, legend ${legend.join("/")}`,
);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/28-run-438-graph.png`));
step("opening a stage's visit pane from the run 438 graph");
await page.evaluate(
`document.querySelector('.run-detail .graph-node[data-key="ui_reviewer"]').click()`,
);
await page.waitForSelector(".stage-pane", { timeout: 15000 });
await page.waitForText("Verdict", { timeout: 15000 });
const graphPane = await page.evaluate(`(() => ({
title: document.querySelector(".stage-pane-title")?.textContent ?? "",
verdict: document.querySelector(".stage-pane .verdict .outcome-chip")?.textContent ?? "",
}))()`);
if (graphPane.title !== "ui_reviewer") {
throw new Error(`the graph-opened pane named the wrong stage: ${graphPane.title}`);
}
if (!graphPane.verdict) throw new Error("the graph-opened pane did not show a verdict");
console.log(` graph-opened pane: ${graphPane.title} — verdict ${graphPane.verdict}`);
await page.rect(".stage-pane-sheet");
shots.push(await page.screenshot(`${out}/29-run-438-graph-pane.png`));
await page.click(".stage-pane-back");
await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), {
timeout: 5000,
what: "the graph stage pane to close",
});
step("opening run 440 to capture the hollow, not-executed stages (R5)");
await page.click('.list.runs .run-row-meta[data-run-id="440"]');
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await page.clickText(".detail .detail-tabs .detail-tab", "Graph");
await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 });
const graph440 = await page.evaluate(`(() => ({
executedNodes: document.querySelectorAll(".run-detail .graph-node.executed").length,
notExecutedNodes: document.querySelectorAll(".run-detail .graph-node.not-executed").length,
hollow: [...document.querySelectorAll(".run-detail .graph-node.not-executed")].every(
(n) => getComputedStyle(n).borderStyle === "dashed",
),
}))()`);
if (!graph440.executedNodes || !graph440.notExecutedNodes) {
throw new Error(`run 440 should show visited and unvisited stages: ${JSON.stringify(graph440)}`);
}
if (!graph440.hollow) {
throw new Error(`an unvisited node is not hollow/dashed: ${JSON.stringify(graph440)}`);
}
console.log(` run 440 graph: ${graph440.executedNodes} executed / ${graph440.notExecutedNodes} not-executed (dashed) nodes`);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/30-run-440-graph.png`));
// R5: a live run's Graph tab — the current stage carries the pulsing halo and
// a ticking elapsed badge; a finished run (above) carries neither. Best effort:
// the run may stop before we look, so skip rather than fail if none is running.
step("opening a live run's Graph tab (R5: halo + elapsed badge)");
const liveRunId = await page.evaluate(`(() => {
const row = [...document.querySelectorAll(".list.runs .run-row")].find((n) => n.querySelector(".chip-running"));
const meta = row?.querySelector(".run-row-meta[data-run-id]");
return meta ? Number(meta.getAttribute("data-run-id")) : null;
})()`);
if (liveRunId == null) {
console.log(" -- no running run available; skipped the live graph halo capture");
} else {
await page.click(`.list.runs .run-row-meta[data-run-id="${liveRunId}"]`);
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await page.clickText(".detail .detail-tabs .detail-tab", "Graph");
await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 });
const live = await eventually(
async () =>
page.evaluate(`(() => {
const active = document.querySelector(".run-detail .graph-node.active");
if (!active) return null;
return {
activeKey: active.dataset.key ?? "",
pulsing: active.classList.contains("pulsing"),
badge: active.querySelector(".graph-elapsed")?.textContent ?? "",
};
})()`),
{ timeout: 15000, what: "the live run's active stage" },
);
if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`);
console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/31-run-live-graph.png`));
}
// The Output empty state, on the running run that has not produced output yet.
step("opening the Output tab on a run with no output recorded");
const runningId = await page.evaluate(`(() => {
@@ -920,6 +1054,277 @@ try {
console.log(` recovered banner after window online: ${recoveredText}`);
await shot("30-reconnect-recovered.png");
// R4: the run Summary's collapsible Changes section and its rendered/raw diff
// viewer. Run 438 changed 22 unique files across 6 steps with every capture
// partial, so the header/row count are asserted against each other rather than
// against a hardcoded total.
const changesToggle = () =>
page.evaluate(`(() => {
const t = [...document.querySelectorAll(".run-detail .collapsible .section-toggle")]
.find((n) => /\\d+ files? changed/.test(n.querySelector(".section-title")?.textContent ?? ""));
if (!t) return null;
return {
title: t.querySelector(".section-title")?.textContent ?? "",
expanded: t.getAttribute("aria-expanded"),
rows: t.parentElement?.querySelectorAll(".change-row").length ?? 0,
};
})()`);
const expandChanges = async () => {
const marked = await page.evaluate(`(() => {
const t = [...document.querySelectorAll(".run-detail .collapsible .section-toggle")]
.find((n) => /\\d+ files? changed/.test(n.querySelector(".section-title")?.textContent ?? ""));
if (!t) return false;
t.scrollIntoView({ block: "center" });
t.setAttribute("data-test-changes-toggle", "1");
return true;
})()`);
if (!marked) throw new Error("no Changes section toggle rendered");
await page.click("[data-test-changes-toggle='1']");
await page.evaluate(
`document.querySelector("[data-test-changes-toggle='1']")?.removeAttribute("data-test-changes-toggle")`,
);
await page.waitForSelector(".run-detail .changes-list .change-row", { timeout: 15000 });
};
const closeChangeViewer = async (how) => {
if (how === "escape") {
await page.evaluate(
`document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))`,
);
} else if (how === "backdrop") {
await page.evaluate(`document.querySelector(".change-viewer").click()`);
} else {
await page.click(".change-viewer-close");
}
await eventually(() => page.evaluate(`!document.querySelector(".change-viewer")`), {
timeout: 5000,
what: `the diff viewer to close (${how})`,
});
};
step("opening run 438: the collapsed Changes section (R4)");
await page.click('.list.runs .run-row-meta[data-run-id="438"]');
await page.waitForText("run 438 ·", { timeout: 25000 });
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
const collapsed = await changesToggle();
if (!collapsed) throw new Error("run 438's Summary rendered no Changes section");
if (collapsed.expanded !== "false") {
throw new Error(`the Changes section is not collapsed on first render: ${collapsed.expanded}`);
}
if (collapsed.rows !== 0) throw new Error(`a collapsed Changes section drew ${collapsed.rows} row(s)`);
const changesCount = Number((/^(\d+) files? changed/.exec(collapsed.title) ?? [])[1] ?? 0);
if (!changesCount) throw new Error(`the Changes header has no file count: ${collapsed.title}`);
if (!collapsed.title.includes("partial capture")) {
throw new Error(`run 438's Changes header should note the partial capture: ${collapsed.title}`);
}
console.log(` collapsed changes header: ${collapsed.title}`);
shots.push(await page.screenshot(`${out}/28-run-438-changes-collapsed.png`));
step("expanding the Changes section: the observed-file rows");
await expandChanges();
const expanded = await page.evaluate(`(() => ({
summary: document.querySelector(".run-detail .changes-summary")?.textContent ?? "",
note: document.querySelector(".run-detail .changes-note")?.textContent ?? "",
rows: document.querySelectorAll(".run-detail .changes-list .change-row").length,
kinds: [...document.querySelectorAll(".run-detail .changes-list .change-kind")].map((n) => n.textContent),
expanded: [...document.querySelectorAll(".run-detail .collapsible .section-toggle")]
.find((n) => /\\d+ files? changed/.test(n.querySelector(".section-title")?.textContent ?? ""))
?.getAttribute("aria-expanded"),
}))()`);
if (expanded.expanded !== "true") throw new Error("the Changes section did not expand");
if (expanded.rows !== changesCount) {
throw new Error(`the Changes section drew ${expanded.rows} rows for a header count of ${changesCount}`);
}
if (!expanded.note.startsWith("Partial capture: some changes may be missing.")) {
throw new Error(`the partial-capture note is missing: ${expanded.note}`);
}
console.log(` expanded: ${expanded.summary} — ${expanded.rows} row(s)`);
console.log(` note: ${expanded.note}`);
console.log(` kinds: ${[...new Set(expanded.kinds)].join(", ")}`);
await page.evaluate(`document.querySelector(".run-detail .changes-list .change-row")?.scrollIntoView({ block: "center" })`);
shots.push(await page.screenshot(`${out}/29-run-438-changes-expanded.png`));
step("opening the rendered diff viewer on the first changed file");
await page.click(".run-detail .changes-list .change-row");
await page.waitForSelector(".change-viewer", { timeout: 15000 });
const rendered = await page.evaluate(`(() => ({
kind: document.querySelector(".change-viewer .change-kind")?.textContent ?? "",
path: document.querySelector(".change-viewer-path")?.textContent ?? "",
position: document.querySelector(".change-viewer-position")?.textContent ?? "",
renderedActive: document.querySelector('.change-form[data-form="rendered"]')?.classList.contains("active") ?? false,
renderedDisabled: document.querySelector('.change-form[data-form="rendered"]')?.disabled ?? null,
rawDisabled: document.querySelector('.change-form[data-form="raw"]')?.disabled ?? null,
hunks: document.querySelectorAll(".change-viewer .change-hunk").length,
lines: document.querySelectorAll(".change-viewer .change-line").length,
gutter: document.querySelector(".change-viewer .change-gutter")?.textContent ?? "",
adds: document.querySelectorAll(".change-viewer .change-text.diff-add").length,
removes: document.querySelectorAll(".change-viewer .change-text.diff-remove").length,
prevDisabled: document.querySelector('.change-page[data-page="prev"]')?.disabled ?? null,
}))()`);
if (!rendered.renderedActive || rendered.renderedDisabled !== true) {
throw new Error(`Rendered is not the default selected form: ${JSON.stringify(rendered)}`);
}
if (!rendered.path || !rendered.position.includes("of ")) {
throw new Error(`the viewer did not identify its file: ${JSON.stringify(rendered)}`);
}
if (!rendered.hunks || !rendered.lines) {
throw new Error(`the rendered viewer drew no hunks/lines: ${JSON.stringify(rendered)}`);
}
if (rendered.gutter.trim() === "") throw new Error("the rendered viewer drew no gutter numbers");
if (rendered.prevDisabled !== true) throw new Error("Previous should be disabled on the first file");
console.log(
` rendered: ${rendered.kind} ${rendered.path} — ${rendered.position}; ` +
`${rendered.hunks} hunk(s), ${rendered.lines} line(s), ${rendered.adds}+/${rendered.removes}-`,
);
shots.push(await page.screenshot(`${out}/30-run-438-changes-diff-rendered.png`));
step("switching the diff viewer to the Raw patch");
await page.evaluate(`document.querySelector('.change-form[data-form="raw"]').click()`);
await page.waitForSelector(".change-viewer .change-raw", { timeout: 15000 });
const raw = await page.evaluate(`(() => ({
rawActive: document.querySelector('.change-form[data-form="raw"]')?.classList.contains("active") ?? false,
renderedDisabled: document.querySelector('.change-form[data-form="rendered"]')?.disabled ?? null,
text: document.querySelector(".change-viewer .change-raw")?.textContent ?? "",
}))()`);
if (!raw.rawActive) throw new Error("Raw patch did not become the selected form");
if (!raw.text.includes("@@")) {
throw new Error(`the raw patch does not look like a unified diff: ${raw.text.slice(0, 80)}`);
}
console.log(` raw patch: ${raw.text.split("\n")[0]} (${raw.text.length} chars)`);
shots.push(await page.screenshot(`${out}/31-run-438-changes-diff-raw.png`));
step("paging between files: Next to the last, then Previous");
await page.evaluate(`document.querySelector('.change-page[data-page="next"]').click()`);
await eventually(
async () => (await page.evaluate(`document.querySelector(".change-viewer-position")?.textContent ?? ""`)).startsWith("2 of "),
{ what: "the viewer to page to file 2" },
);
await page.evaluate(`(() => {
for (let i = 0; i < 500; i += 1) {
const next = document.querySelector('.change-page[data-page="next"]');
if (!next || next.disabled) break;
next.click();
}
})()`);
const last = await page.evaluate(`(() => ({
position: document.querySelector(".change-viewer-position")?.textContent ?? "",
nextDisabled: document.querySelector('.change-page[data-page="next"]')?.disabled ?? null,
prevDisabled: document.querySelector('.change-page[data-page="prev"]')?.disabled ?? null,
}))()`);
if (last.nextDisabled !== true) throw new Error("Next is not disabled on the last file");
if (!last.position.startsWith(`${changesCount} of `)) {
throw new Error(`the viewer did not reach the last file: ${last.position}`);
}
console.log(` paged to the last file: ${last.position}`);
await page.evaluate(`document.querySelector('.change-page[data-page="prev"]').click()`);
await eventually(
async () => (await page.evaluate(`document.querySelector(".change-viewer-position")?.textContent ?? ""`)).startsWith(`${changesCount - 1} of `),
{ what: "the viewer to page back" },
);
step("closing the diff viewer with Escape returns focus to the row");
await closeChangeViewer("escape");
const restoredFocus = await page.evaluate(
`document.activeElement?.getAttribute?.("data-change-index") ?? ""`,
);
// The viewer was paged back one file just before closing, so focus returns to
// that row (index changesCount - 2).
if (restoredFocus !== String(changesCount - 2)) {
throw new Error(`focus did not return to the opened row: ${restoredFocus}`);
}
console.log(` focus returned to change row ${restoredFocus}`);
step("reopening and closing the diff viewer by a backdrop click");
await page.click(".run-detail .changes-list .change-row");
await page.waitForSelector(".change-viewer", { timeout: 15000 });
await closeChangeViewer("backdrop");
// A binary capture: the honest message in place of a diff, and Raw disabled.
step("opening a binary capture (run 442): the honest message and a disabled Raw patch");
await page.click('.list.runs .run-row-meta[data-run-id="442"]');
await page.waitForText("run 442 ·", { timeout: 25000 });
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await expandChanges();
await page.click(".run-detail .changes-list .change-row");
await page.waitForSelector(".change-viewer .change-honest", { timeout: 15000 });
const binary = await page.evaluate(`(() => ({
message: document.querySelector(".change-viewer .change-honest")?.textContent ?? "",
rawDisabled: document.querySelector('.change-form[data-form="raw"]')?.disabled ?? null,
hunks: document.querySelectorAll(".change-viewer .change-hunk").length,
}))()`);
if (
binary.message !==
"This is a binary file: the server recorded the change but has no textual diff to show."
) {
throw new Error(`the binary message is wrong: ${binary.message}`);
}
if (binary.rawDisabled !== true) throw new Error("Raw patch should be disabled for a binary file");
if (binary.hunks !== 0) throw new Error("a binary file must not render a fabricated diff");
console.log(` binary: ${binary.message}`);
shots.push(await page.screenshot(`${out}/32-run-442-changes-binary.png`));
await closeChangeViewer("close");
// A truncated capture: the truncation reason, still no fabricated diff.
step("opening a truncated capture (run 450): the truncation reason");
await page.click('.list.runs .run-row-meta[data-run-id="450"]');
await page.waitForText("run 450 ·", { timeout: 25000 });
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await expandChanges();
const openedTruncated = await page.evaluate(`(() => {
const row = [...document.querySelectorAll(".run-detail .changes-list .change-row")]
.find((n) => (n.querySelector(".change-meta")?.textContent ?? "").includes("truncated"));
if (!row) return false;
row.click();
return true;
})()`);
if (!openedTruncated) throw new Error("run 450's Changes list showed no truncated row");
await page.waitForSelector(".change-viewer .change-honest", { timeout: 15000 });
const truncated = await page.evaluate(
`document.querySelector(".change-viewer .change-honest")?.textContent ?? ""`,
);
if (
truncated !==
"The server truncated this file's patch at its capture limit; no diff text was recorded."
) {
throw new Error(`the truncation reason is wrong: ${truncated}`);
}
console.log(` truncated: ${truncated}`);
shots.push(await page.screenshot(`${out}/33-run-450-changes-truncated.png`));
await closeChangeViewer("close");
// A still-running run: its Changes header must be one of the two valid shapes
// for an in-flight capture (the empty `Changes · …` variant, or a file-count
// header), never a fabricated complete diff. Its live state decides which, so
// the probe accepts either rather than pinning one.
step("opening a running run's Changes header");
const pendingRunId = await page.evaluate(`(() => {
const row = [...document.querySelectorAll(".list.runs .run-row")]
.find((n) => n.querySelector(".chip-running"));
const meta = row?.querySelector(".run-row-meta[data-run-id]");
return meta ? Number(meta.getAttribute("data-run-id")) : null;
})()`);
if (pendingRunId == null) {
console.log(" -- no running run available; skipped the pending Changes header");
} else {
await page.click(`.list.runs .run-row-meta[data-run-id="${pendingRunId}"]`);
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
const pendingToggle = await page.evaluate(`(() => {
// A running run's Changes header has one of two valid shapes: the
// empty-capture form (Changes · capture pending / partial capture /
// capture incomplete) before any step has recorded files, or the
// file-count form ({N} file(s) changed · ±stat · …) once one has. Which
// one appears depends on how far the live capture has progressed, so the
// probe accepts either rather than assuming the empty variant.
return [...document.querySelectorAll(".run-detail .collapsible .section-toggle .section-title")]
.map((n) => n.textContent ?? "")
.find((t) => /^Changes · /.test(t) || /^\\d+ files? changed/.test(t)) ?? "";
})()`);
if (!/^Changes · /.test(pendingToggle) && !/^\d+ files? changed/.test(pendingToggle)) {
throw new Error(`a running run's Changes header is wrong: ${pendingToggle}`);
}
console.log(` running run ${pendingRunId} changes header: ${pendingToggle}`);
shots.push(await page.screenshot(`${out}/34-run-${pendingRunId}-changes-pending.png`));
}
console.log("\nUI SMOKE PASS");
for (const shot of shots) console.log(` ${shot}`);
} catch (error) {