From 06965933f447e7458ae908140e24eff5e1a0951b Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 03:32:32 +0100 Subject: [PATCH] web: tabbed run detail with summary, IO fields and timeline (R3/R6/R7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser run detail becomes a tab strip — Summary, Input, Output, Timeline — over the selected tab's body, with the Graph tab key reserved for the R5 item. - Summary: run label, status chip + outcome, the run identity line, the key/value rows (Pipeline, Stage, waiting-for-resource line, Workspace, content hash, Started, Finished, live Duration, Retry of, Diagnostic) and the collapsed run artifacts gallery. - Input / Output: one collapsed section per recorded map entry, the value as a monospace block; empty states match the app. - Timeline: one row per visit with the stage-outcome glyph, `{stage} · visit {n}`, an outcome chip, a paperclip when artifacts were recorded, the duration and the description; a row opens the per-visit stage pane. - Stage pane: headline rows, the Verdict block with inline artifact links and the Artifacts / Session / Output / Input / This run / Stage definition sections, all closable with Escape. All new logic is the pure, DOM-free src/runDetail.js ported from the Android sources; app.js keeps only the wiring and every server string is set with textContent. PARITY.md: R3, R6 and R7 marked done with their captures. --- web/PARITY.md | 13 +- web/src/app.js | 576 ++++++++++++++++++++++----- web/src/runDetail.js | 767 ++++++++++++++++++++++++++++++++++++ web/styles.css | 141 +++++++ web/test/runDetail.test.mjs | 507 ++++++++++++++++++++++++ web/test/ui-smoke.mjs | 208 +++++++++- 6 files changed, 2096 insertions(+), 116 deletions(-) create mode 100644 web/src/runDetail.js create mode 100644 web/test/runDetail.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index c3bb4fd9..4b989582 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -33,11 +33,11 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | --- | --- | --- | --- | | 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` | partial (fields + steps) | +| 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 | -| R6 | Input / Output field sections per stage | `get_run` | todo | -| R7 | Timeline | `get_run` | todo | +| 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`) | | R9 | Session export link (read-only `session.html`) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/06-session-export-link.png`) | | R10 | Live run updates: subscribe/unsubscribe + event fold | `subscribe`, `unsubscribe`, `run_event` | todo | @@ -47,6 +47,13 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | R14 | Rename a run | `set_run_title` | todo | | R15 | Attention / "Needs you" surface: counts, open, individual dismiss, clear all | derived from `list_runs` + run events | todo | +Two wording decisions in R3's stage pane, recorded here as the app-authoritative +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. + ## Search | # | Feature | Protocol | Status | | --- | --- | --- | --- | diff --git a/web/src/app.js b/web/src/app.js index 8d9ec23a..b8f456f6 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -71,6 +71,28 @@ import { templateStageSummary, TEMPLATE_UNPARSED_SOURCE_NOTE, } from "./templates.js"; +import { + RENDERED_RUN_TABS, + EMPTY_INPUT_MESSAGE, + EMPTY_OUTPUT_MESSAGE, + EMPTY_TIMELINE_MESSAGE, + NO_STAGE_DETAILS_MESSAGE, + fieldSections, + summaryRows, + runIdentityLine, + runLabelFor, + runDurationText, + runTimeline, + nodeLabel, + headlineFields, + runStepFields, + stageSectionSpecs, + clampVisitIndex, + referencedVerdictArtifacts, + verdictReasonSegments, + outcomeColorToken, + stateGlyph, +} from "./runDetail.js"; const STORAGE_KEY = "pipelines.web.serverUrl.v2"; @@ -127,6 +149,14 @@ const state = { runFilters: defaultRunFilters(), runSort: DEFAULT_RUN_SORT, openMenu: null, + // Run detail: the selected tab (Summary by default) and the per-run + // expand/collapse choices for the input/output field sections and the summary + // artifacts section. The stage pane is the timeline's per-visit panel; its + // section expansion is reseeded each time a pane is opened. + runTab: "summary", + runSections: new Set(), + runStagePane: null, + runStageSections: new Set(), }; let runPoll = null; @@ -138,6 +168,12 @@ let runPoll = null; let listClock = null; let listNow = Date.now(); +// The run detail's own live clock: it ticks only while the shown run is +// executing, updating just the Duration row in place (never a full re-render, so +// an open stage pane is not torn down), exactly as the runs list does. +let detailClock = null; +let detailNow = Date.now(); + // --------------------------------------------------------------------------- // DOM helpers // --------------------------------------------------------------------------- @@ -159,36 +195,6 @@ function h(tag, props = {}, ...children) { return node; } -function fmtSeconds(total) { - const s = Math.max(0, Math.round(total)); - const hh = Math.floor(s / 3600); - const mm = Math.floor((s % 3600) / 60); - const ss = s % 60; - if (hh > 0) return `${hh}h ${mm}m ${ss}s`; - if (mm > 0) return `${mm}m ${ss}s`; - return `${ss}s`; -} - -function fmtTime(iso) { - if (!iso) return "—"; - const ms = Date.parse(iso); - return Number.isNaN(ms) ? iso : new Date(ms).toLocaleString(); -} - -function fmtDuration(startIso, finishIso) { - if (!startIso) return "—"; - const start = Date.parse(startIso); - if (Number.isNaN(start)) return "—"; - const end = finishIso ? Date.parse(finishIso) : Date.now(); - if (Number.isNaN(end)) return "—"; - // A future start (clock skew) reads as 0s, matching the Android client. - return fmtSeconds(Math.max(0, (end - start) / 1000)); -} - -function statusClass(status) { - return `chip chip-${String(status || "unknown").toLowerCase()}`; -} - function isExecuting(run) { return Boolean(run && run.executing); } @@ -273,8 +279,13 @@ function renderContent() { } nodes.push(split); content.replaceChildren(...nodes); - if (state.view === "runs") refreshListClock(); - else stopListClock(); + if (state.view === "runs") { + refreshListClock(); + refreshDetailClock(); + } else { + stopListClock(); + stopDetailClock(); + } } function tabButton(view, label) { @@ -1041,77 +1052,415 @@ function closeMenu() { renderContent(); } +/** + * 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. + */ function renderRunDetail() { const d = state.runDetail; - const pane = h("div", { class: "detail" }); + const pane = h("div", { class: "detail run-detail" }); if (!d) { pane.append(h("div", { class: "muted pad", text: "Select a run." })); return pane; } pane.append( - h( - "h2", - {}, - d.title || d.name || `run ${d.id}`, - h("span", { class: statusClass(d.status), text: d.status || "unknown" }), - ), h( "div", - { class: "kv" }, - kv("Run ID", `#${d.id}`), - kv("Pipeline", `#${d.pipeline_id} @ v${d.version}`), - kv("Outcome", d.outcome || "—"), - kv("Current stage", d.current_stage || "—"), - kv("Started", fmtTime(d.created_at)), - kv("Duration", isExecuting(d) ? `${fmtDuration(d.created_at, "")} (running)` : fmtDuration(d.created_at, d.finished_at)), - kv("Completed steps", String(d.completed_steps ?? 0)), - d.diagnostic ? kv("Diagnostic", d.diagnostic) : null, + { class: "detail-tabs" }, + ...RENDERED_RUN_TABS.map((tab) => + h("button", { + class: `detail-tab${state.runTab === tab.key ? " active" : ""}`, + text: tab.label, + onclick: () => { + state.runTab = tab.key; + renderContent(); + }, + }), + ), ), ); - - const steps = d.steps ?? []; - const executing = isExecuting(d); - - // Run-level artifacts gallery (parity R8). The header is the run summary line - // and the gallery below it draws one group per (stage, visit); all derivation - // lives in artifacts.js so the count can never disagree with the tiles. - pane.append(h("h3", { class: "artifacts-header", text: artifactsHeader(steps, executing) })); - pane.append(renderArtifactGallery(steps)); - - pane.append(h("h3", { text: `Steps (${steps.length})` })); - if (!steps.length) { - pane.append(h("div", { class: "muted pad", text: "No steps recorded yet." })); - return pane; + 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)); + } else if (state.runTab === "steps") { + pane.append(renderRunTimelineTab(d)); + } else { + pane.append(renderRunSummaryTab(d)); } - const list = h("div", { class: "steps" }); - for (const s of steps) { - list.append( - h( - "div", - { class: "step" }, - h( - "div", - { class: "step-head" }, - h("code", { text: `${s.sequence}. ${s.stage}` }), - h("span", { class: statusClass(s.status), text: s.status || "unknown" }), - s.outcome ? h("span", { class: "chip", text: s.outcome }) : null, - h("span", { class: "muted", text: fmtDuration(s.started_at, s.finished_at) }), - ), - h( - "div", - { class: "kv tight" }, - kv("Target", s.target || "—"), - kv("Visit", s.control ? `${s.control.visit}/${s.control.max_visits}` : "—"), - kv("Session", s.session_id || "—"), - s.diagnostic ? kv("Diagnostic", s.diagnostic) : null, - ), - renderVisitArtifacts(s), - renderSessionExport(s), + if (state.runStagePane) pane.append(renderStagePane(d)); + return pane; +} + +/** The Summary tab: identity, chip row, key/value rows, diagnostic and gallery. */ +function renderRunSummaryTab(d) { + const wrap = h("div", { class: "run-tab-body" }); + wrap.append(h("h2", { class: "run-detail-title", text: runLabelFor(d) })); + const status = runStateOf(d.status); + const chips = h("div", { class: "run-chip-row" }); + chips.append(h("span", { class: `chip chip-${status}`, text: d.status || status })); + if (String(d.outcome ?? "").trim()) chips.append(h("span", { class: "muted", text: `outcome ${d.outcome}` })); + if (d.executing) chips.append(h("span", { class: "muted", text: "executing" })); + wrap.append(chips); + wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) })); + + const rows = h("div", { class: "kv" }); + for (const row of summaryRows(d, detailNow)) { + if (row.kind === "wait") rows.append(h("div", { class: "run-wait", text: row.value })); + else if (row.kind === "duration") rows.append(renderDurationRow(d, row)); + else if (row.kind === "block") rows.append(renderCodeBlock(row.key, row.value)); + else rows.append(renderKvRow(row)); + } + wrap.append(rows); + + // The run-level artifacts gallery (parity R8), collapsed by default like the + // Android summary. Its header alone says what was captured until expanded. + wrap.append( + renderCollapsible("summary-artifacts", artifactsHeader(d.steps ?? [], isExecuting(d)), () => + renderArtifactGallery(d.steps ?? []), + ), + ); + return wrap; +} + +/** The Duration row, tagged so the detail clock can update it in place. */ +function renderDurationRow(d, row) { + return h( + "div", + { class: "kv-row" }, + h("span", { class: "kv-key", text: row.key }), + h("span", { class: "kv-val run-duration", "data-run-id": String(d.id), text: row.value }), + ); +} + +/** One key/value row from a summary row model. */ +function renderKvRow(row) { + return h( + "div", + { class: "kv-row" }, + h("span", { class: "kv-key", text: row.key }), + h("span", { class: `kv-val${row.monospace ? " monospace" : ""}`, text: row.value }), + ); +} + +/** A themed monospace block with a label header. */ +function renderCodeBlock(label, text) { + return h( + "div", + { class: "codeblock" }, + h("div", { class: "codeblock-label", text: label }), + h("pre", { class: "codeblock-body", text }), + ); +} + +/** One stage-pane field as either the code card (blocks) or a key/value row. */ +function renderStageField(field) { + if (field.block) return renderCodeBlock(field.label, field.value); + return h( + "div", + { class: "kv-row" }, + h("span", { class: "kv-key", text: field.label }), + h("span", { class: `kv-val${field.mono ? " monospace" : ""}`, text: field.value }), + ); +} + +/** One collapsible input/output field section (expanded body is a code block). */ +function renderRunFieldTab(map, keyPrefix, emptyMessage) { + const wrap = h("div", { class: "run-tab-body" }); + const sections = fieldSections(map, keyPrefix); + if (!sections.length) { + wrap.append(h("div", { class: "run-empty muted", text: emptyMessage })); + return wrap; + } + for (const section of sections) { + const key = `${keyPrefix}-${section.key}`; + wrap.append( + renderCollapsible(key, section.title, () => + h("pre", { class: "field-block" }, h("code", { text: section.value })), ), ); } - pane.append(list); - return pane; + return wrap; +} + +/** + * One collapsible section of the run detail's field/summary body. Expanded state + * is keyed in `state.runSections`, so the operator's choices survive a re-render. + */ +function renderCollapsible(key, title, bodyFn) { + const expanded = state.runSections.has(key); + const wrap = h("div", { class: "collapsible" }); + wrap.append( + h( + "button", + { + class: "section-toggle", + type: "button", + "aria-expanded": expanded ? "true" : "false", + onclick: () => { + state.runSections = new Set(state.runSections); + if (state.runSections.has(key)) state.runSections.delete(key); + else state.runSections.add(key); + renderContent(); + }, + }, + h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), + h("span", { class: "section-title", text: title }), + ), + ); + if (expanded) wrap.append(h("div", { class: "section-body" }, bodyFn())); + return wrap; +} + +/** The Timeline tab: one compact row per visit, in step order. */ +function renderRunTimelineTab(d) { + const wrap = h("div", { class: "run-tab-body" }); + const timeline = runTimeline(d.steps ?? []); + if (!timeline.entries.length) { + wrap.append(h("div", { class: "run-empty muted", text: EMPTY_TIMELINE_MESSAGE })); + return wrap; + } + const list = h("div", { class: "timeline" }); + for (const entry of timeline.entries) list.append(renderTimelineRow(entry)); + wrap.append(list); + return wrap; +} + +/** + * One timeline row: a stage-outcome glyph, the `{stage} · visit {n}` line with + * the outcome chip, a paperclip when the visit recorded artifacts, the duration, + * and the one-line description. Clicking (or Enter/Space) opens the stage pane. + */ +function renderTimelineRow(entry) { + const state_ = runStateOf(entry.outcomeLabel); + const chipLabel = entry.outcomeLabel || state_.label; + const tone = outcomeClass(entry.step.outcome, entry.step.status); + const open = () => openStagePane(entry.stageKey, entry.visitIndex); + const row = h("div", { + class: "timeline-row", + role: "button", + tabindex: "0", + "data-stage-key": entry.stageKey, + "data-visit-index": String(entry.visitIndex), + }); + row.addEventListener("click", open); + row.addEventListener("keydown", (event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + open(); + } + }); + row.append(h("span", { class: `timeline-glyph ${tone}`, text: stateGlyph(state_) })); + const head = h("div", { class: "timeline-head" }); + head.append(h("span", { class: "timeline-title", text: `${entry.stageKey} · visit ${entry.visit}` })); + head.append(h("span", { class: `outcome-chip ${tone}`, text: chipLabel })); + if (entry.hasArtifacts) { + head.append( + h("span", { class: "timeline-paperclip", title: "Recorded artifacts", "aria-label": "has recorded artifacts", text: "\u{1F4CE}" }), + ); + } + if (entry.duration) head.append(h("span", { class: "timeline-duration muted", text: entry.duration })); + const body = h("div", { class: "timeline-main" }, head); + if (entry.description) body.append(h("span", { class: "timeline-desc muted", text: entry.description })); + row.append(body); + return row; +} + +/** A CSS class naming a stage-outcome colour (status palette, else flow). */ +function outcomeClass(outcome, status) { + const [kind, value] = outcomeColorToken(outcome, status).split(" "); + return `outcome-${kind}-${value}`; +} + +// --- Stage pane ------------------------------------------------------------ + +/** + * The stage pane: a closable dialog for one visit, opened from a timeline row. + * It leads with the verdict block (when the server recorded one), then the + * always-visible headline rows, then the visit's collapsible sections in the + * Android order (Artifacts, Session, Output, Input, This run, Stage definition). + * Escape, the Back button and a backdrop click close it. + */ +function renderStagePane(d) { + const stageKey = state.runStagePane.stageKey; + const timeline = runTimeline(d.steps ?? []); + const runSteps = timeline.visitsByStage.get(stageKey) ?? []; + const visitIndex = clampVisitIndex(state.runStagePane.visitIndex, runSteps.length); + const step = runSteps[visitIndex] ?? null; + const graph = d.graph ?? { stages: [] }; + const specs = stageSectionSpecs(stageKey, graph, runSteps, visitIndex, true); + const fields = step ? runStepFields(step) : []; + const headline = headlineFields(fields); + + const overlay = h("div", { + class: "stage-pane", + role: "dialog", + "aria-modal": "true", + "aria-label": nodeLabel(stageKey), + }); + overlay.addEventListener("click", (event) => { + if (event.target === overlay) closeStagePane(); + }); + const bar = h( + "div", + { class: "stage-pane-bar" }, + h("button", { + class: "stage-pane-back", + type: "button", + "aria-label": "Back", + text: "\u2190 Back", + onclick: closeStagePane, + }), + h( + "div", + { class: "stage-pane-titles" }, + h("span", { class: "stage-pane-title", text: nodeLabel(stageKey) }), + h("span", { class: "stage-pane-run muted", text: runLabelFor(d) }), + ), + ); + + const body = h("div", { class: "stage-pane-body" }); + if (step) { + const verdict = renderVerdictBlock(step); + if (verdict) body.append(verdict); + } + for (const field of headline) body.append(renderStageField(field)); + if (headline.length === 0 && specs.length === 0) { + body.append(h("div", { class: "run-empty muted", text: NO_STAGE_DETAILS_MESSAGE })); + } + for (const spec of specs) body.append(renderStageSection(spec, step)); + overlay.append(h("div", { class: "stage-pane-sheet" }, bar, body)); + return overlay; +} + +/** One stage-pane section, using the pane's own expansion state. */ +function renderStageSection(spec, step) { + const expanded = state.runStageSections.has(spec.key); + const wrap = h("div", { class: "collapsible stage-section" }); + wrap.append( + h( + "button", + { + class: "section-toggle", + type: "button", + "aria-expanded": expanded ? "true" : "false", + onclick: () => { + state.runStageSections = new Set(state.runStageSections); + if (state.runStageSections.has(spec.key)) state.runStageSections.delete(spec.key); + else state.runStageSections.add(spec.key); + renderContent(); + }, + }, + h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), + h("span", { class: "section-title", text: spec.title }), + ), + ); + if (!expanded) return wrap; + const body = h("div", { class: "section-body" }); + if (spec.artifacts && step) body.append(renderVisitArtifacts(step)); + else if (spec.session && step) body.append(renderSessionExport(step)); + else for (const field of spec.fields) body.append(renderStageField(field)); + wrap.append(body); + return wrap; +} + +/** + * The verdict block: heading "Verdict", the option as an outcome-coloured chip, + * the reason as body text with inline artifact links, and the referenced + * artifacts as compact chips. Nothing renders when the server recorded no + * option and no reason. + */ +function renderVerdictBlock(step) { + const verdict = step.verdict; + if (!verdict) return null; + const option = String(verdict.option ?? ""); + const reason = String(verdict.reason ?? ""); + if (option.trim() === "" && reason.trim() === "") return null; + + const wrap = h("div", { class: "verdict" }); + const head = h("div", { class: "verdict-head" }, h("span", { class: "verdict-title", text: "Verdict" })); + if (option.trim() !== "") { + head.append(h("span", { class: `outcome-chip ${outcomeClass(step.outcome, step.status)}`, text: option })); + } + wrap.append(head); + + const references = referencedVerdictArtifacts(verdict, presentedArtifacts(step)); + if (reason.trim() !== "") { + const body = h("p", { class: "verdict-reason" }); + for (const segment of verdictReasonSegments(reason, references)) { + if (!segment.artifact) body.append(document.createTextNode(segment.text)); + else body.append(renderVerdictLink(segment.text, segment.artifact, step)); + } + wrap.append(body); + } + if (references.length) { + const refs = h("div", { class: "verdict-refs" }); + for (const artifact of references) refs.append(renderVerdictRef(artifact, step)); + wrap.append(refs); + } + return wrap; +} + +/** One inline artifact reference in a verdict reason (media opens the viewer). */ +function renderVerdictLink(text, artifact, step) { + const resolved = resolvedArtifactUrl(artifact, state.url); + if (!resolved) return h("span", { class: "verdict-link disabled", text }); + const link = h("a", { class: "verdict-link", href: resolved, target: "_blank", rel: "noreferrer", text }); + link.addEventListener("click", (event) => { + event.preventDefault(); + openArtifactFromVerdict(artifact, step, resolved); + }); + return link; +} + +/** One compact chip naming a referenced artifact. */ +function renderVerdictRef(artifact, step) { + const resolved = resolvedArtifactUrl(artifact, state.url); + const chip = h("button", { + class: "verdict-ref", + type: "button", + text: artifact.name || "(unnamed artifact)", + }); + chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved)); + return chip; +} + +/** Open a referenced artifact: media in the viewer, everything else externally. */ +function openArtifactFromVerdict(artifact, step, resolved) { + if (!resolved) return; + const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts: presentedArtifacts(step) }; + const viewable = pagedArtifacts([group]); + const viewerIndexOf = viewerIndexByUrl([group]); + const at = viewerIndexOf.get(artifact.url); + const kind = artifactKind(artifact.content_type, artifact.name); + const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video; + if (media && at != null) openArtifactViewer(viewable, at); + else window.open(resolved, "_blank", "noopener,noreferrer"); +} + +/** Open the stage pane for one visit of a stage and move focus into it. */ +function openStagePane(stageKey, visitIndex) { + state.runStagePane = { stageKey, visitIndex }; + state.runStageSections = new Set(); + renderContent(); + document.querySelector(".stage-pane-back")?.focus(); +} + +/** Close the stage pane, returning focus to the timeline row that opened it. */ +function closeStagePane() { + const closing = state.runStagePane; + if (!closing) return; + state.runStagePane = null; + state.runStageSections = new Set(); + renderContent(); + const row = [...document.querySelectorAll(".timeline-row")].find( + (node) => node.dataset.stageKey === closing.stageKey && node.dataset.visitIndex === String(closing.visitIndex), + ); + row?.focus(); } /** Whether the configured server URL can resolve a server-relative artifact. */ @@ -1441,15 +1790,6 @@ function openArtifactViewer(viewable, startIndex) { document.addEventListener("keydown", viewerKeydown); } -function kv(key, value) { - return h( - "div", - { class: "kv-row" }, - h("span", { class: "kv-key", text: key }), - h("span", { class: "kv-val", text: value }), - ); -} - /** A key/value row whose value is monospace (a key, an id) rather than prose. */ function kvMono(key, value) { return h( @@ -1596,6 +1936,12 @@ 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. + state.runTab = "summary"; + state.runSections = new Set(); + state.runStagePane = null; + state.runStageSections = new Set(); renderContent(); } try { @@ -1651,6 +1997,31 @@ function stopListClock() { } } +/** + * (Re)start the run detail's own clock: it ticks once a second only while the + * shown run is executing, updating just the Duration row in place (never a full + * re-render, so an open stage pane and its scroll are not torn down). The value + * is derived from the server's start timestamp, so it survives a reconnect. + */ +function refreshDetailClock() { + stopDetailClock(); + detailNow = Date.now(); + if (state.view === "runs" && isExecuting(state.runDetail)) { + detailClock = setInterval(() => { + detailNow = Date.now(); + const node = document.querySelector(".run-duration[data-run-id]"); + if (node && state.runDetail) node.textContent = runDurationText(state.runDetail, detailNow) ?? ""; + }, 1000); + } +} + +function stopDetailClock() { + if (detailClock) { + clearInterval(detailClock); + detailClock = null; + } +} + // --------------------------------------------------------------------------- // Boot // --------------------------------------------------------------------------- @@ -1666,9 +2037,20 @@ client.addEventListener("state", (event) => { if (next.kind !== "connected" && previousKind === "connected") { stopRunPoll(); stopListClock(); + stopDetailClock(); } 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. +document.addEventListener("keydown", (event) => { + if (event.key === "Escape" && state.runStagePane && !document.querySelector(".artifact-viewer")) { + event.preventDefault(); + closeStagePane(); + } +}); + // Prefill from a previous session only; the user still confirms with Connect. render(); diff --git a/web/src/runDetail.js b/web/src/runDetail.js new file mode 100644 index 00000000..6e634666 --- /dev/null +++ b/web/src/runDetail.js @@ -0,0 +1,767 @@ +// Pure, DOM-free logic for the run-detail tabs and the stage pane, ported from +// the Android client so the browser says and shows exactly the same things: +// ui/screens/RunDetailScreen.kt the tab set (RUN_DETAIL_TABS) +// ui/screens/RunSummaryTab.kt the summary rows and identity line +// ui/screens/RunFieldSectionsTab.kt input/output field sections +// ui/screens/Timeline.kt runTimeline, timelineDescription, hasArtifacts +// ui/graph/StageDetailPane.kt runStepFields, headline/evidence split, +// stageSectionSpecs, stageDefinitionFields, +// controlVisitLabel, clampVisitIndex +// ui/graph/StageVerdict.kt verdictReasonSegments, referencedVerdictArtifacts +// ui/Format.kt displayText/displayMap, fileChangeLine, +// notificationLine, fileChangesSummary +// data/protocol/GraphSemantics.kt nodeLabel, outcome ordering, edge labels +// ui/graph/GraphPalette.kt the curated graph-only outcome palette +// +// Nothing here touches the DOM or imports the app: every function is pure so the +// wording, ordering, counting and formatting can be unit-tested without a +// browser. The tab/pane wiring lives in app.js. Every server-provided string is +// only ever compared or rendered, never parsed as markup; the caller sets it +// with textContent. +import { + runIdentity, + visitCount, + formatDuration, + durationSeconds, + secondsSince, + formatLocalTimestamp, + runStateOf, +} from "./runs.js"; +import { presentedArtifacts, sessionExportArtifact, displayVisit } from "./artifacts.js"; +import { effectiveStageType } from "./templates.js"; + +// --------------------------------------------------------------------------- +// Tabs +// --------------------------------------------------------------------------- + +/** + * 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`. + */ +export const RUN_DETAIL_TABS = [ + { key: "summary", label: "Summary" }, + { key: "graph", label: "Graph" }, + { key: "input", label: "Input" }, + { key: "output", label: "Output" }, + { key: "steps", label: "Timeline" }, +]; + +/** The tabs the browser currently renders (the Graph body is the R5 item). */ +export const RENDERED_RUN_TABS = RUN_DETAIL_TABS.filter((tab) => tab.key !== "graph"); + +// The empty-state sentences, exactly as the app spells them. +export const EMPTY_INPUT_MESSAGE = "No input recorded."; +export const EMPTY_OUTPUT_MESSAGE = "No output recorded."; +export const EMPTY_TIMELINE_MESSAGE = "No visits recorded."; +export const NO_STAGE_DETAILS_MESSAGE = "No details recorded for this node."; + +/** The stage-pane section titles (Android StageDetailPane constants). */ +export const STAGE_ARTIFACTS_TITLE = "Artifacts"; +export const STAGE_SESSION_TITLE = "Session"; +export const STAGE_EVIDENCE_TITLE = "This run"; +export const STAGE_DEFINITION_TITLE = "Stage definition"; + +// --------------------------------------------------------------------------- +// Field display (ui/Format.kt displayText / displayMap) +// --------------------------------------------------------------------------- + +/** + * Compact rendering of an arbitrary JSON value for read-only display: a + * primitive verbatim, an array `, `-joined, an object `k=v` `, `-joined. + * Mirrors Format.kt JsonElement.displayText (a JSON null reads `null`). + */ +export function displayText(value) { + if (Array.isArray(value)) return value.map((item) => displayText(item)).join(", "); + if (value !== null && typeof value === "object") { + return Object.entries(value) + .map(([key, item]) => `${key}=${displayText(item)}`) + .join(", "); + } + if (value === undefined) return "null"; + return String(value); +} + +/** + * A field map rendered one `key: value` line per entry, in insertion order. + * Mirrors Format.kt Map?.displayMap (a null/empty map is + * the empty string). + */ +export function displayMap(map) { + if (!map) return ""; + return Object.entries(map) + .map(([key, value]) => `${key}: ${displayText(value)}`) + .join("\n"); +} + +/** + * The input/output tab's sections, one per map entry in insertion order: the + * entry's own key as the title (falling back to the section prefix so it is + * never empty) and the value's display text. Mirrors + * RunFieldSectionsTab.fieldSectionTitle + displayText. + */ +export function fieldSections(map, keyPrefix) { + if (!map) return []; + return Object.entries(map).map(([key, value]) => ({ + key, + title: fieldSectionTitle(key, keyPrefix), + value: displayText(value), + })); +} + +/** A field section's title: the field's own name, else the section prefix. */ +export function fieldSectionTitle(key, keyPrefix) { + const text = String(key ?? ""); + return text.trim() === "" ? keyPrefix : text; +} + +// --------------------------------------------------------------------------- +// Run summary (ui/screens/RunSummaryTab.kt) +// --------------------------------------------------------------------------- + +/** + * The summary rows in Android order: Pipeline `id {id} · v{version}`, Stage, the + * resource-wait line only when `resource_wait` is set, Workspace, Content hash + * (monospace), Started, Finished, the live-aware Duration, `Retry of run {n}` + * when set, and the Diagnostic block. Blank values are omitted so no empty row + * is ever drawn. Each entry is tagged with a `kind` so the renderer can style + * and (for `duration`) live-update it. + */ +export function summaryRows(run, nowMillis, options = {}) { + if (!run) return []; + const rows = []; + const kv = (key, value, monospace = false) => { + const text = String(value ?? ""); + if (text.trim() === "") return; + rows.push({ kind: "kv", key, value: text, monospace }); + }; + kv("Pipeline", `id ${run.pipeline_id ?? 0} · v${run.version ?? 0}`); + kv("Stage", run.current_stage); + const wait = resourceWaitLine(run); + if (wait) rows.push({ kind: "wait", value: wait }); + kv("Workspace", run.workspace); + kv("Content hash", run.content_hash, true); + kv("Started", formatLocalTimestamp(run.created_at, options)); + kv("Finished", formatLocalTimestamp(run.finished_at, options)); + const duration = runDurationText(run, nowMillis); + if (duration != null) rows.push({ kind: "duration", key: "Duration", value: duration }); + if (Number(run.retry_of) > 0) kv("Retry of", `run ${run.retry_of}`); + if (String(run.diagnostic ?? "").trim() !== "") { + rows.push({ kind: "block", key: "Diagnostic", value: String(run.diagnostic) }); + } + return rows; +} + +/** + * The resource-wait line, `Waiting for resource {name}`, only when the run is + * waiting on a resource. Mirrors RunSummaryTab's `run.resourceWait?.let { ... }` + * and ResourceWait.statusLabel. + */ +export function resourceWaitLine(run) { + if (!run || run.resource_wait == null) return ""; + return `Waiting for resource ${String(run.resource_wait.resource ?? "")}`; +} + +/** + * The run's identity line: `run {id} · {recorded visits} · {completed visits}`, + * the same recorded/completed vocabulary the runs list and the server use. + * Mirrors RunSummaryTab's buildString. + */ +export function runIdentityLine(run) { + if (!run) return ""; + const recorded = visitCount((run.steps ?? []).length, "recorded"); + const completed = visitCount(Number(run.completed_steps) || 0, "completed"); + return `run ${run.id} · ${recorded} · ${completed}`; +} + +/** + * The run's primary label (stored title, else the pipeline name), from the one + * runIdentity helper the runs list also uses so the two never disagree. + */ +export function runLabelFor(run) { + return runIdentity(run?.title, run?.name).label; +} + +/** + * The summary's Duration value: live elapsed while executing, else the stored + * total. Mirrors Format.kt runDurationText (null when unavailable, so the caller + * omits the row). + */ +export function runDurationText(run, nowMillis) { + if (!run) return null; + if (run.executing) { + const elapsed = secondsSince(run.created_at, nowMillis); + return elapsed == null ? null : formatDuration(elapsed); + } + const total = durationSeconds(run.created_at, run.finished_at); + return total == null ? null : formatDuration(total); +} + +// --------------------------------------------------------------------------- +// Timeline (ui/screens/Timeline.kt) +// --------------------------------------------------------------------------- + +/** + * The run's timeline plus each stage's ordered visits, derived in one pass. + * Stages keep first-appearance order; a stage's visits are ordered by sequence. + * One entry per recorded visit, in step order, with the display visit number, + * the outcome chip label (`outcome` else `status`), whether the visit recorded + * artifacts, its duration and its one-line description. Pure and total over an + * empty list and blank control/outcome fields. Mirrors `runTimeline`. + */ +export function runTimeline(steps) { + const list = steps ?? []; + if (list.length === 0) return { entries: [], visitsByStage: new Map() }; + + const visitsByStage = new Map(); + for (const step of list) { + const stage = step?.stage ?? ""; + if (!visitsByStage.has(stage)) visitsByStage.set(stage, []); + visitsByStage.get(stage).push(step); + } + const indexByStageSequence = new Map(); + for (const [stage, visits] of visitsByStage) { + [...visits] + .sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0)) + .forEach((visit, index) => indexByStageSequence.set(`${stage}\u0000${visit?.sequence ?? 0}`, index)); + } + + const entries = list.map((step) => { + const index = indexByStageSequence.get(`${step?.stage ?? ""}\u0000${step?.sequence ?? 0}`) ?? 0; + return { + step, + stageKey: step?.stage ?? "", + visit: displayVisit(step, index), + visitIndex: index, + outcomeLabel: String(step?.outcome ?? "").trim() !== "" ? String(step.outcome) : String(step?.status ?? ""), + hasArtifacts: hasArtifacts(step), + duration: stepDuration(step), + description: timelineDescription(step), + }; + }); + + const orderedVisits = new Map(); + for (const [stage, visits] of visitsByStage) { + orderedVisits.set( + stage, + [...visits].sort((a, b) => (a?.sequence ?? 0) - (b?.sequence ?? 0)), + ); + } + return { entries, visitsByStage: orderedVisits }; +} + +/** + * The brief one-line description after a visit's name: the first non-blank + * diagnostic line, else the resolved target, else nothing (never fabricated). + */ +export function timelineDescription(step) { + const diagnostic = String(step?.diagnostic ?? ""); + const line = diagnostic.split(/\r?\n/).find((candidate) => candidate.trim() !== ""); + if (line != null) return line.trim(); + const target = String(step?.target ?? ""); + if (target.trim() !== "") return `→ ${nodeLabel(target)}`; + return ""; +} + +/** + * Whether a visit recorded any presented artifact. The retired session markdown + * is not presented, so it never counts. Composes the one presentedArtifacts + * filter so the timeline and the pane never disagree. + */ +export function hasArtifacts(step) { + return presentedArtifacts(step).length > 0; +} + +/** Human duration between a step's timestamps, or null when unavailable. */ +export function stepDuration(step) { + const seconds = durationSeconds(step?.started_at, step?.finished_at); + return seconds == null ? null : formatDuration(seconds); +} + +// --------------------------------------------------------------------------- +// Graph semantics (data/protocol/GraphSemantics.kt, Message.kt) +// --------------------------------------------------------------------------- + +export const SUCCESS_END = "#success"; +export const FAILURE_END = "#failure"; + +/** A node label: the success/failure terminal shorthand, else the key itself. */ +export function nodeLabel(key) { + if (key === SUCCESS_END) return "SUCCESS"; + if (key === FAILURE_END) return "FAILURE"; + return String(key ?? ""); +} + +/** Whether a resolved target is an explicit terminal. */ +export function isTerminal(target) { + return target === SUCCESS_END || target === FAILURE_END; +} + +/** Mirrors Protocol.resolveTarget: preserve `#` as the outcome's terminal. */ +export function resolveTarget(outcome, target) { + if (target !== "#") return target; + return outcome === "error" ? FAILURE_END : SUCCESS_END; +} + +/** A stage's outcomes (edge keys) in the app's order: success, others, error. */ +export function stageOutcomes(stage) { + return Object.keys(stage?.edges ?? {}).sort((a, b) => { + const pa = a === "success" ? 0 : a === "error" ? 2 : 1; + const pb = b === "success" ? 0 : b === "error" ? 2 : 1; + return pa - pb || (a < b ? -1 : a > b ? 1 : 0); + }); +} + +/** Every definition edge in stable order. Mirrors Graph.edges(). */ +export function graphEdges(graph) { + const result = []; + for (const stage of graph?.stages ?? []) { + for (const outcome of stageOutcomes(stage)) { + const target = resolveTarget(outcome, stage.edges[outcome]); + result.push({ + source: stage.key, + outcome, + target, + label: outcome === "error" && stage.fallback_error ? "error*" : outcome, + }); + } + } + return result; +} + +// --------------------------------------------------------------------------- +// Stage pane (ui/graph/StageDetailPane.kt) +// --------------------------------------------------------------------------- + +/** One labelled row/block of stage detail, rendered by the pane. */ +function field(label, value, mono = false, block = false) { + return { label, value, mono, block }; +} + +/** + * The always-visible run-side identity/result labels of a step. The item's + * headline list adds `Session` beside the app's six, so a visit that recorded a + * session id shows it up top with the rest of its result facts. + */ +export const STAGE_HEADLINE_LABELS = new Set([ + "Status", + "Outcome", + "Target", + "Duration", + "Visit", + "Model target", + "Session", +]); + +/** The always-visible run-side identity/result fields of a step's evidence. */ +export function headlineFields(fields) { + return (fields ?? []).filter((entry) => STAGE_HEADLINE_LABELS.has(entry.label)); +} + +/** + * The remaining run evidence (diagnostic, transcript, agent, file changes, + * notifications) that belongs in the collapsible "This run" section: the + * headline facts and the input/output result blocks are surfaced elsewhere. + */ +export function evidenceFields(fields) { + return (fields ?? []).filter( + (entry) => + !STAGE_HEADLINE_LABELS.has(entry.label) && entry.label !== "Input" && entry.label !== "Output", + ); +} + +/** + * The pure run view of one step: status, outcome, duration, visit against the + * control's max visits, target, session id, agent flag, diagnostic, transcript, + * the step's input/output, a file-change summary, changed files and notification + * receipts. Blank fields are skipped, so no empty row is ever emitted. Mirrors + * `runStepFields`. + */ +export function runStepFields(step) { + const fields = []; + if (step == null) return fields; + if (str(step.status).trim() !== "") fields.push(field("Status", str(step.status))); + if (str(step.outcome).trim() !== "") fields.push(field("Outcome", str(step.outcome))); + const duration = stepDuration(step); + if (duration != null) fields.push(field("Duration", duration)); + const control = step.control; + if (control) { + if (Number(control.max_visits) > 0 || Number(control.visit) > 0) { + fields.push(field("Visit", controlVisitLabel(control))); + } + const modelTarget = str(control.model_target); + if (modelTarget.trim() !== "") fields.push(field("Model target", modelTarget)); + } + if (str(step.target).trim() !== "") fields.push(field("Target", str(step.target))); + if (str(step.session_id).trim() !== "") fields.push(field("Session", str(step.session_id), true)); + if (step.agent_active) fields.push(field("Agent", "active")); + if (str(step.diagnostic).trim() !== "") fields.push(field("Diagnostic", str(step.diagnostic), false, true)); + if (str(step.transcript).trim() !== "") fields.push(field("Transcript", str(step.transcript), false, true)); + if (step.input && Object.keys(step.input).length > 0) { + fields.push(field("Input", displayMap(step.input), false, true)); + } + if (step.output && Object.keys(step.output).length > 0) { + fields.push(field("Output", displayMap(step.output), false, true)); + } + const changes = step.file_changes; + if (changes) { + const summary = fileChangesSummary(changes); + if (summary.trim() !== "") fields.push(field("File changes", summary)); + const files = changes.files ?? []; + if (files.length > 0) { + fields.push(field("Changed files", files.map((file) => fileChangeLine(file)).join("\n"), false, true)); + } + } + for (const receipt of step.notifications ?? []) { + if (str(receipt?.status).trim() !== "" || str(receipt?.destination).trim() !== "") { + fields.push(field("Notification", notificationLine(receipt))); + } + } + return fields; +} + +/** + * The stage definition view: key + type title, prompt, output, edges with their + * outcomes and resolved terminals, configs, tools, limits and memory sources. + * Only non-blank fields are emitted. Mirrors `stageDefinitionFields`. + */ +export function stageDefinitionFields(stage) { + const fields = []; + if (stage == null) return fields; + fields.push(field("Type", effectiveStageType(stage.type))); + if (str(stage.prompt).trim() !== "") fields.push(field("Prompt", str(stage.prompt), false, true)); + if (str(stage.output).trim() !== "") fields.push(field("Output", str(stage.output), false, true)); + + const outcomes = stageOutcomes(stage).map((outcome) => { + const target = resolveTarget(outcome, String(stage.edges?.[outcome] ?? "")); + const suffix = isTerminal(target) ? " (terminal)" : ""; + return `${outcome} → ${nodeLabel(target)}${suffix}`; + }); + if (outcomes.length > 0) fields.push(field("Outcomes", outcomes.join("\n"), false, true)); + + const configs = stage.configs ?? {}; + for (const key of Object.keys(configs).sort()) { + const value = str(configs[key]); + if (value.trim() !== "") fields.push(field(configLabel(key), value)); + } + + const tools = stage.blocks?.tools; + if (str(tools).trim() !== "") fields.push(field("Tools", str(tools), false, true)); + + const limits = stage.limits; + if (limits) { + if (Number(limits.max_visits) > 0) fields.push(field("Max visits", String(limits.max_visits))); + const on = limits.on ?? []; + if (on.length > 0) fields.push(field("Limit on", on.join(", "))); + } + + const memory = stage.memory; + if (memory && Object.keys(memory).length > 0) { + const value = Object.entries(memory) + .map(([key, source]) => `${key}: ${source}`) + .join("\n"); + fields.push(field("Memory", value, false, true)); + } + + const notify = stage.notify; + if (notify) { + const on = notify.on ?? []; + if (on.length > 0) fields.push(field("Notify on", on.join(", "))); + if (str(notify.destination).trim() !== "") fields.push(field("Notify destination", str(notify.destination))); + const artifacts = notify.artifacts ?? []; + if (artifacts.length > 0) fields.push(field("Notify artifacts", artifacts.join(", "))); + } + return fields; +} + +/** The config key's display label (mirrors StageDetailPane.configLabel). */ +export function configLabel(key) { + switch (key) { + case "provider": + return "Provider"; + case "model": + return "Model"; + case "retries": + return "Retries"; + case "timeout": + return "Timeout"; + case "budget_usd": + return "Budget (USD)"; + case "budget_tokens": + return "Budget (tokens)"; + case "harness": + return "Harness"; + default: + return key; + } +} + +/** Incoming routes into a terminal node, for a pane opened on a terminal. */ +export function terminalFields(graph, key) { + const lines = graphEdges(graph) + .filter((edge) => edge.target === key) + .map((edge) => `${edge.source} · ${edge.label} → ${nodeLabel(key)}`); + return lines.length === 0 ? [] : [field("Incoming routes", lines.join("\n"), false, true)]; +} + +/** + * The shared visit label for a step's control evidence, e.g. + * `3 / 5 (limit reached)` (or just `3` when no max is recorded). Mirrors + * `controlVisitLabel`. + */ +export function controlVisitLabel(control) { + const visit = Number(control?.visit) || 0; + const max = Number(control?.max_visits) || 0; + const base = max > 0 ? `${visit} / ${max}` : String(visit); + return base + (control?.limit_reached ? " (limit reached)" : ""); +} + +/** Clamps a visit index into `[0, count)`; an empty list yields 0. */ +export function clampVisitIndex(index, count) { + if (count <= 0) return 0; + return Math.min(Math.max(Number(index) || 0, 0), count - 1); +} + +/** + * The ordered sections of the stage pane for one stage and visit: a run pane + * leads with the visit's Artifacts gallery, then its exported Session when it + * has one, then Output, Input and the remaining evidence (`This run`); the + * stage's own definition is last. Blank field sections are skipped; the + * artifacts section always shows for a reached visit. Mirrors + * `stageSectionSpecs`. + */ +export function stageSectionSpecs(stageKey, graph, runSteps, visitIndex, runContext) { + const specs = []; + const stage = (graph?.stages ?? []).find((candidate) => candidate?.key === stageKey); + const definition = stage ? stageDefinitionFields(stage) : terminalFields(graph, stageKey); + const steps = runSteps ?? []; + const selectedStep = steps[clampVisitIndex(visitIndex, steps.length)]; + if (runContext && selectedStep != null) { + const runFields = runStepFields(selectedStep); + const session = sessionExportArtifact(selectedStep) != null; + specs.push({ key: "artifacts", title: STAGE_ARTIFACTS_TITLE, fields: [], artifacts: true, session: false }); + if (session) { + specs.push({ key: "session", title: STAGE_SESSION_TITLE, fields: [], artifacts: false, session: true }); + } + const output = runFields.filter((entry) => entry.label === "Output"); + if (output.length > 0) specs.push({ key: "output", title: "Output", fields: output, artifacts: false, session: false }); + const input = runFields.filter((entry) => entry.label === "Input"); + if (input.length > 0) specs.push({ key: "input", title: "Input", fields: input, artifacts: false, session: false }); + const evidence = evidenceFields(runFields); + if (evidence.length > 0) { + specs.push({ key: "run", title: STAGE_EVIDENCE_TITLE, fields: evidence, artifacts: false, session: false }); + } + } + if (definition.length > 0) { + specs.push({ key: "definition", title: STAGE_DEFINITION_TITLE, fields: definition, artifacts: false, session: false }); + } + return specs; +} + +// --------------------------------------------------------------------------- +// Verdict (ui/graph/StageVerdict.kt) +// --------------------------------------------------------------------------- + +/** + * The recorded artifacts a verdict refers to: its referenced names resolved to + * the visit's recorded artifacts, in recorded order and deduplicated by name. A + * name the server never recorded is dropped. Mirrors + * `referencedVerdictArtifacts`. + */ +export function referencedVerdictArtifacts(verdict, artifacts) { + const names = verdict?.artifacts ?? []; + if (names.length === 0) return []; + const wanted = new Set(names); + const seen = new Set(); + const referenced = []; + for (const artifact of artifacts ?? []) { + const name = str(artifact?.name); + if (name === "" || seen.has(name)) continue; + seen.add(name); + if (wanted.has(name)) referenced.push(artifact); + } + return referenced; +} + +/** + * Splits a reason into literal runs and references to the recorded artifacts it + * names (by full name or basename). At the same index a longer token wins. With + * nothing to reference the whole reason is one literal segment; an empty reason + * yields no segments. Mirrors `verdictReasonSegments`. + */ +export function verdictReasonSegments(reason, references) { + const text = String(reason ?? ""); + if (text === "") return []; + const list = references ?? []; + if (list.length === 0) return [{ text }]; + const tokens = []; + for (const artifact of list) { + const name = str(artifact?.name); + tokens.push([name, artifact]); + const base = artifactBaseName(name); + if (base !== "" && base !== name) tokens.push([base, artifact]); + } + tokens.sort((a, b) => b[0].length - a[0].length); + const segments = []; + let literal = ""; + let index = 0; + while (index < text.length) { + const match = tokens.find(([token]) => text.startsWith(token, index)); + if (!match) { + literal += text[index]; + index++; + } else { + if (literal !== "") { + segments.push({ text: literal }); + literal = ""; + } + segments.push({ text: match[0], artifact: match[1] }); + index += match[0].length; + } + } + if (literal !== "") segments.push({ text: literal }); + return segments; +} + +/** The last path segment of a recorded artifact name (`shots/x.png` → `x.png`). */ +export function artifactBaseName(name) { + const text = str(name); + const slash = Math.max(text.lastIndexOf("/"), text.lastIndexOf("\\")); + return slash === -1 ? text : text.slice(slash + 1); +} + +// --------------------------------------------------------------------------- +// Formatting (ui/Format.kt) +// --------------------------------------------------------------------------- + +/** + * One changed-file line, e.g. `modified src/a.kt (binary) (truncated)`. Mirrors + * Format.kt fileChangeLine. + */ +export function fileChangeLine(file) { + const base = `${str(file?.kind)} ${str(file?.path)}`; + const binary = file?.binary ? " (binary)" : ""; + const truncated = file?.truncated ? " (truncated)" : ""; + return base + binary + truncated; +} + +/** One notification receipt, e.g. `delivered → ntfy · ok`, skipping a blank diagnostic. */ +export function notificationLine(receipt) { + const diagnostic = str(receipt?.diagnostic); + const suffix = diagnostic.trim() !== "" ? ` · ${diagnostic}` : ""; + return `${str(receipt?.status)} → ${str(receipt?.destination)}${suffix}`; +} + +/** + * A compact file-change summary, e.g. `partial (2 files), 1 skipped`. Blank + * parts are omitted; an entirely blank change set renders as "". + */ +export function fileChangesSummary(changes) { + let text = ""; + if (str(changes?.status).trim() !== "") text += str(changes.status); + const files = changes?.files ?? []; + if (files.length > 0) { + if (text !== "") text += " "; + text += `(${files.length} files)`; + } + if (Number(changes?.skipped) > 0) { + if (text !== "") text += ", "; + text += `${changes.skipped} skipped`; + } + return text; +} + +// --------------------------------------------------------------------------- +// Outcome colours (ui/graph/GraphPalette.kt, WorkflowGraph.outcomeColor) +// --------------------------------------------------------------------------- + +/** + * The fixed palette for the graph-only flow outcomes (rejected/exhausted/retry/ + * approved/fast/missing) plus the reserved fallback slots. Mirrors + * GraphPalette.colors. + */ +export const FLOW_OUTCOME_COLORS = [ + "#F5A3A3", // rejected + "#F5B37A", // exhausted + "#7FD4E8", // retry + "#C0A3F5", // approved + "#F0E07A", // fast + "#F5A3D0", // missing + "#D8C98A", // fallback + "#9FD8C0", // fallback + "#D8A8C0", // fallback +]; + +const KNOWN_FLOW_OUTCOMES = ["rejected", "exhausted", "retry", "approved", "fast", "missing"]; + +/** + * The stable palette index for an outcome with no run-state meaning: known flow + * outcomes get their curated slot, everything else a stable fallback slot. + * Mirrors GraphPalette.outcomeColorIndex. + */ +export function flowOutcomeIndex(outcome) { + const known = KNOWN_FLOW_OUTCOMES.indexOf(outcome); + if (known !== -1) return known; + const fallbackStart = KNOWN_FLOW_OUTCOMES.length; + const fallbackCount = FLOW_OUTCOME_COLORS.length - fallbackStart; + if (fallbackCount <= 0) return 0; + return fallbackStart + (Math.abs(hashString(outcome)) % fallbackCount); +} + +/** + * The colour token for an outcome/stage status: a run-state word takes the + * shared status palette (`state {state}`), any other flow outcome its curated + * palette slot (`flow {index}`). The renderer maps the token onto a CSS class so + * the timeline and the verdict block agree. Mirrors WorkflowGraph.outcomeColor. + */ +export function outcomeColorToken(outcome, status) { + const state = runStateOf(String(outcome ?? "").trim() !== "" ? outcome : status); + if (state !== "unknown") return `state ${state}`; + return `flow ${flowOutcomeIndex(String(outcome ?? "").trim() !== "" ? outcome : status)}`; +} + +/** A distinct glyph per run state, echoing the app's one-glyph-per-state set. */ +export function stateGlyph(state) { + switch (state) { + case "running": + return "▶"; + case "queued": + return "◷"; + case "waiting": + return "✋"; + case "succeeded": + return "✓"; + case "failed": + return "✕"; + case "canceled": + return "⊘"; + case "interrupted": + return "❚❚"; + case "blocked": + return "■"; + case "skipped": + return "⏭"; + case "active": + return "⚡"; + default: + return "?"; + } +} + +// --------------------------------------------------------------------------- +// Internals +// --------------------------------------------------------------------------- + +function str(value) { + return value == null ? "" : String(value); +} + +/** A small, stable 31-bit string hash (Kotlin String.hashCode analogue). */ +function hashString(value) { + let hash = 0; + for (let i = 0; i < value.length; i++) { + hash = (hash * 31 + value.charCodeAt(i)) | 0; + } + return hash; +} diff --git a/web/styles.css b/web/styles.css index a8c9f6ba..2407b962 100644 --- a/web/styles.css +++ b/web/styles.css @@ -510,3 +510,144 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- other status chips, so RunStatusPalette stays the single source of truth for every status word. */ .chip-unknown { color: #bec9c5; border-color: #bec9c5; } + +/* --------------------------------------------------------------------------- + Run detail: tabbed Summary / Input / Output / Timeline plus the per-visit + stage pane. Hand-written, dark palette, no framework. + --------------------------------------------------------------------------- */ + +.run-tab-body { display: grid; gap: 10px; } + +.run-detail-title { margin: 0; font-size: 18px; } + +.run-chip-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.run-identity { font-size: 12px; } +.run-wait { color: var(--warn); font-size: 12px; } +.run-empty { padding: 14px 4px; } + +.collapsible .section-title { flex: 1; } +.collapsible > .section-body { padding: 8px 4px 4px; } +.field-block { + margin: 0; + padding: 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-2); + overflow: auto; + max-height: 360px; +} +.field-block code { + background: transparent; + padding: 0; + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 12px; + white-space: pre-wrap; + word-break: break-word; +} + +/* Timeline rows: one compact line per visit. */ +.timeline { display: grid; } +.timeline-row { + display: flex; + gap: 10px; + align-items: flex-start; + width: 100%; + padding: 10px 4px; + border-bottom: 1px solid var(--border); + cursor: pointer; +} +.timeline-row:last-child { border-bottom: 0; } +.timeline-row:hover, .timeline-row:focus-visible { background: var(--surface-2); outline: none; } +.timeline-glyph { flex: none; width: 18px; text-align: center; font-size: 14px; line-height: 1.4; } +.timeline-main { flex: 1; min-width: 0; display: grid; gap: 2px; } +.timeline-head { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.timeline-title { font-weight: 600; } +.timeline-duration { font-size: 12px; } +.timeline-desc { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.timeline-paperclip { font-size: 12px; } + +/* The one stage-outcome colour vocabulary: a run-state word takes the shared + status palette, any other flow outcome its curated palette slot (mirrors + GraphPalette). Set on the class, so a chip's border follows its text. */ +.outcome-chip { + display: inline-block; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid currentColor; + font-size: 11px; +} +.outcome-state-running, .outcome-state-active { color: #7fb2f0; } +.outcome-state-waiting { color: #8edff5; } +.outcome-state-succeeded { color: var(--ok); } +.outcome-state-failed { color: var(--bad); } +.outcome-state-canceled { color: #889391; } +.outcome-state-interrupted { color: var(--warn); } +.outcome-state-queued { color: #9aa6a2; } +.outcome-state-blocked { color: #f0a35e; } +.outcome-state-skipped { color: #a8b8c8; } +.outcome-state-unknown { color: #bec9c5; } +.outcome-flow-0 { color: #f5a3a3; } +.outcome-flow-1 { color: #f5b37a; } +.outcome-flow-2 { color: #7fd4e8; } +.outcome-flow-3 { color: #c0a3f5; } +.outcome-flow-4 { color: #f0e07a; } +.outcome-flow-5 { color: #f5a3d0; } +.outcome-flow-6 { color: #d8c98a; } +.outcome-flow-7 { color: #9fd8c0; } +.outcome-flow-8 { color: #d8a8c0; } + +/* The per-visit stage pane: a right-hand sheet with a modal backdrop. */ +.stage-pane { + position: fixed; + inset: 0; + z-index: 25; + display: flex; + justify-content: flex-end; + background: rgba(0, 0, 0, 0.55); +} +.stage-pane-bar { + display: flex; + gap: 10px; + align-items: center; + padding: 10px 12px; + border-bottom: 1px solid var(--border); + background: var(--surface); +} +.stage-pane-titles { display: grid; min-width: 0; } +.stage-pane-title { font-weight: 600; } +.stage-pane-run { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.stage-pane-sheet { + display: flex; + flex-direction: column; + width: min(560px, 100%); + height: 100%; + min-width: 0; + background: var(--surface); + border-left: 1px solid var(--border); + box-shadow: -12px 0 40px rgba(0, 0, 0, 0.45); +} +.stage-pane-body { flex: 1; overflow-y: auto; padding: 14px; display: grid; gap: 10px; align-content: start; } +.stage-section > .section-body { padding-top: 6px; } + +/* The verdict block leads the pane. */ +.verdict { + display: grid; + gap: 8px; + padding: 10px; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface-2); +} +.verdict-head { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.verdict-title { font-weight: 600; } +.verdict-reason { margin: 0; line-height: 1.5; } +.verdict-link { color: var(--accent); text-decoration: underline; } +.verdict-link.disabled { color: var(--muted); text-decoration: none; } +.verdict-refs { display: flex; flex-wrap: wrap; gap: 6px; } +.verdict-ref { + padding: 2px 8px; + font-size: 11px; + border-radius: 999px; + border: 1px solid var(--border); + background: var(--surface); +} diff --git a/web/test/runDetail.test.mjs b/web/test/runDetail.test.mjs new file mode 100644 index 00000000..b76a4af8 --- /dev/null +++ b/web/test/runDetail.test.mjs @@ -0,0 +1,507 @@ +// Pure unit tests for the run-detail helpers: the tab set, the summary rows and +// identity line, input/output field display, the timeline derivation and its +// one-line text, the stage-pane section ordering and field split, the +// file-change/notification formatters and the verdict reason segmentation. +// No server, no DOM. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + RUN_DETAIL_TABS, + RENDERED_RUN_TABS, + EMPTY_INPUT_MESSAGE, + EMPTY_OUTPUT_MESSAGE, + EMPTY_TIMELINE_MESSAGE, + NO_STAGE_DETAILS_MESSAGE, + STAGE_SESSION_TITLE, + STAGE_EVIDENCE_TITLE, + STAGE_DEFINITION_TITLE, + displayText, + displayMap, + fieldSections, + fieldSectionTitle, + summaryRows, + resourceWaitLine, + runIdentityLine, + runDurationText, + runTimeline, + timelineDescription, + hasArtifacts, + nodeLabel, + resolveTarget, + stageOutcomes, + headlineFields, + evidenceFields, + runStepFields, + stageDefinitionFields, + terminalFields, + controlVisitLabel, + clampVisitIndex, + stageSectionSpecs, + referencedVerdictArtifacts, + verdictReasonSegments, + artifactBaseName, + fileChangeLine, + notificationLine, + fileChangesSummary, + outcomeColorToken, + stateGlyph, +} from "../src/runDetail.js"; + +function step(overrides = {}) { + return { + sequence: 1, + stage: "implementer", + status: "completed", + outcome: "success", + target: "", + diagnostic: "", + started_at: "", + finished_at: "", + control: null, + artifacts: null, + ...overrides, + }; +} + +const TIME_OPTS = { zone: "UTC", locale: "en-GB" }; + +// --------------------------------------------------------------------------- +// Tabs and empty states +// --------------------------------------------------------------------------- + +test("RUN_DETAIL_TABS is the Android order, Summary first, Timeline keyed 'steps'", () => { + assert.deepEqual( + RUN_DETAIL_TABS.map((tab) => tab.key), + ["summary", "graph", "input", "output", "steps"], + ); + assert.deepEqual( + 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. + assert.deepEqual( + RENDERED_RUN_TABS.map((tab) => tab.label), + ["Summary", "Input", "Output", "Timeline"], + ); +}); + +test("the empty-state strings are exactly the app's wording", () => { + assert.equal(EMPTY_INPUT_MESSAGE, "No input recorded."); + assert.equal(EMPTY_OUTPUT_MESSAGE, "No output recorded."); + assert.equal(EMPTY_TIMELINE_MESSAGE, "No visits recorded."); + assert.equal(NO_STAGE_DETAILS_MESSAGE, "No details recorded for this node."); + assert.equal(STAGE_SESSION_TITLE, "Session"); + assert.equal(STAGE_EVIDENCE_TITLE, "This run"); + assert.equal(STAGE_DEFINITION_TITLE, "Stage definition"); +}); + +// --------------------------------------------------------------------------- +// Field display text +// --------------------------------------------------------------------------- + +test("displayText renders primitives, arrays and objects like Format.kt", () => { + assert.equal(displayText("hello"), "hello"); + assert.equal(displayText(42), "42"); + assert.equal(displayText(true), "true"); + assert.equal(displayText(null), "null"); + assert.equal(displayText(["a", "b", "c"]), "a, b, c"); + assert.equal(displayText({ a: 1, b: "x" }), "a=1, b=x"); + assert.equal(displayText([{ k: 1 }, 2]), "k=1, 2"); +}); + +test("displayMap renders one `key: value` line per entry in insertion order", () => { + assert.equal(displayMap({ prompt: "do it", files: ["a", "b"] }), "prompt: do it\nfiles: a, b"); + assert.equal(displayMap(null), ""); + assert.equal(displayMap({}), ""); +}); + +test("fieldSections keeps insertion order and titles each entry", () => { + const sections = fieldSections({ prompt: "do it", pwd: "/tmp" }, "input"); + assert.deepEqual(sections, [ + { key: "prompt", title: "prompt", value: "do it" }, + { key: "pwd", title: "pwd", value: "/tmp" }, + ]); + assert.deepEqual(fieldSections(null, "input"), []); +}); + +test("fieldSectionTitle falls back to the prefix and is never empty", () => { + assert.equal(fieldSectionTitle("plan", "input"), "plan"); + assert.equal(fieldSectionTitle("", "input"), "input"); + assert.equal(fieldSectionTitle(" ", "output"), "output"); +}); + +// --------------------------------------------------------------------------- +// Summary +// --------------------------------------------------------------------------- + +test("runIdentityLine carries recorded and completed visits in order", () => { + const run = { id: 430, steps: [step(), step(), step()], completed_steps: 3 }; + assert.equal(runIdentityLine(run), "run 430 · 3 recorded visits · 3 completed visits"); + assert.equal( + runIdentityLine({ id: 7, steps: [step()], completed_steps: 0 }), + "run 7 · 1 recorded visit · 0 completed visits", + ); +}); + +test("resourceWaitLine appears only when the run is waiting on a resource", () => { + assert.equal(resourceWaitLine({ resource_wait: { resource: "pixel-9" } }), "Waiting for resource pixel-9"); + assert.equal(resourceWaitLine({ resource_wait: null }), ""); + assert.equal(resourceWaitLine({}), ""); +}); + +test("summaryRows is the Android order, omitting blank values", () => { + const run = { + id: 430, + pipeline_id: 12, + version: 5, + status: "succeeded", + executing: false, + current_stage: "committer", + workspace: "/tmp/wt", + content_hash: "abc123", + created_at: "2026-10-19T09:30:00Z", + finished_at: "2026-10-19T09:32:05Z", + retry_of: 409, + diagnostic: "boom", + resource_wait: { resource: "phone" }, + steps: [step(), step(), step()], + completed_steps: 3, + }; + const rows = summaryRows(run, 0, TIME_OPTS); + assert.deepEqual( + rows.map((row) => row.key ?? row.kind), + ["Pipeline", "Stage", "wait", "Workspace", "Content hash", "Started", "Finished", "Duration", "Retry of", "Diagnostic"], + ); + assert.equal(rows[0].value, "id 12 · v5"); + assert.equal(rows[2].value, "Waiting for resource phone"); + assert.equal(rows[4].monospace, true); + assert.equal(rows[7].value, "2m 5s"); + assert.equal(rows[8].value, "run 409"); + assert.equal(rows[9].kind, "block"); +}); + +test("summaryRows omits blank values and the wait line when there is none", () => { + const rows = summaryRows( + { id: 1, pipeline_id: 2, version: 1, status: "running", executing: false, steps: [], completed_steps: 0 }, + 0, + TIME_OPTS, + ); + assert.ok(rows.every((row) => row.kind !== "wait")); + assert.ok(rows.every((row) => row.value.trim() !== "")); + assert.ok(!rows.some((row) => row.key === "Stage" || row.key === "Workspace")); +}); + +test("runDurationText is live while executing and stored at rest", () => { + assert.equal( + runDurationText({ executing: true, created_at: "2026-10-19T09:30:00Z" }, Date.parse("2026-10-19T09:31:05Z")), + "1m 5s", + ); + assert.equal(runDurationText({ executing: false, created_at: "2026-10-19T09:30:00Z", finished_at: "2026-10-19T09:32:05Z" }, 0), "2m 5s"); + assert.equal(runDurationText({ executing: false, created_at: "", finished_at: "" }, 0), null); +}); + +// --------------------------------------------------------------------------- +// Timeline +// --------------------------------------------------------------------------- + +test("runTimeline is one entry per visit with the display visit and index", () => { + const { entries, visitsByStage } = runTimeline([ + step({ sequence: 5, stage: "reviewer", outcome: "rejected", control: { visit: 2 } }), + step({ sequence: 2, stage: "reviewer", outcome: "success", control: { visit: 1 } }), + ]); + assert.deepEqual(entries.map((entry) => entry.step.sequence), [5, 2]); + const bySeq = new Map(entries.map((entry) => [entry.step.sequence, entry])); + assert.equal(bySeq.get(2).visit, 1); + assert.equal(bySeq.get(2).visitIndex, 0); + assert.equal(bySeq.get(5).visit, 2); + assert.equal(bySeq.get(5).visitIndex, 1); + assert.deepEqual(visitsByStage.get("reviewer").map((s) => s.sequence), [2, 5]); +}); + +test("runTimeline falls back to the position when control is missing", () => { + const { entries } = runTimeline([step({ sequence: 1 }), step({ sequence: 2 })]); + assert.deepEqual(entries.map((entry) => entry.visit), [1, 2]); + assert.deepEqual(entries.map((entry) => entry.visitIndex), [0, 1]); + assert.deepEqual(runTimeline([]).entries, []); +}); + +test("timeline entry text prefers the first diagnostic line, else → target", () => { + const { entries } = runTimeline([ + step({ diagnostic: "\n first line \nsecond" }), + step({ target: "#success" }), + step({ target: "reviewer" }), + step({}), + ]); + assert.equal(entries[0].description, "first line"); + assert.equal(entries[1].description, "→ SUCCESS"); + assert.equal(entries[2].description, "→ reviewer"); + assert.equal(entries[3].description, ""); +}); + +test("timelineDescription mirrors nodeLabel for the terminals", () => { + assert.equal(timelineDescription(step({ target: "#failure" })), "→ FAILURE"); + assert.equal(nodeLabel("#success"), "SUCCESS"); + assert.equal(nodeLabel("#failure"), "FAILURE"); + assert.equal(nodeLabel("reviewer"), "reviewer"); +}); + +test("timeline entries carry the outcome label and the artifact flag", () => { + const { entries } = runTimeline([ + step({ outcome: "", status: "running" }), + step({ outcome: "approved", status: "completed", artifacts: [{ name: "session.md" }] }), + step({ outcome: "approved", status: "completed", artifacts: [{ name: "shot.png" }] }), + ]); + assert.equal(entries[0].outcomeLabel, "running"); + assert.equal(entries[1].outcomeLabel, "approved"); + assert.equal(entries[1].hasArtifacts, false); + assert.equal(entries[2].hasArtifacts, true); + assert.equal(hasArtifacts(step()), false); +}); + +test("timeline duration comes from the shared formatter", () => { + const { entries } = runTimeline([ + step({ started_at: "2026-10-15T02:00:00Z", finished_at: "2026-10-15T02:02:05Z" }), + ]); + assert.equal(entries[0].duration, "2m 5s"); +}); + +// --------------------------------------------------------------------------- +// Stage pane +// --------------------------------------------------------------------------- + +test("controlVisitLabel covers a missing max and the limit", () => { + assert.equal(controlVisitLabel({ visit: 2 }), "2"); + assert.equal(controlVisitLabel({ visit: 2, max_visits: 4 }), "2 / 4"); + assert.equal(controlVisitLabel({ visit: 2, max_visits: 4, limit_reached: true }), "2 / 4 (limit reached)"); +}); + +test("clampVisitIndex keeps a valid visit and handles an empty list", () => { + assert.equal(clampVisitIndex(0, 3), 0); + assert.equal(clampVisitIndex(99, 3), 2); + assert.equal(clampVisitIndex(-4, 3), 0); + assert.equal(clampVisitIndex(5, 0), 0); +}); + +test("runStepFields skips blanks and formats the visit", () => { + assert.deepEqual(runStepFields({}), []); + const fields = runStepFields({ + status: "completed", + outcome: "success", + target: "#success", + session_id: "sess-1", + agent_active: true, + control: { visit: 3, max_visits: 5, limit_reached: true, model_target: "gpt" }, + }); + assert.equal(fields.find((f) => f.label === "Visit").value, "3 / 5 (limit reached)"); + assert.equal(fields.find((f) => f.label === "Agent").value, "active"); + assert.ok(fields.every((f) => f.value.trim() !== "")); +}); + +test("runStepFields carries every evidence kind the timeline dropped", () => { + const fields = runStepFields({ + status: "completed", + diagnostic: "why", + transcript: "said something", + input: { prompt: "do it" }, + output: { result: "done" }, + file_changes: { status: "partial", files: [{ kind: "modified", path: "a.kt" }], skipped: 2 }, + notifications: [{ status: "delivered", destination: "ntfy" }], + }); + const labels = fields.map((f) => f.label); + for (const label of ["Status", "Diagnostic", "Transcript", "Input", "Output", "File changes", "Changed files", "Notification"]) { + assert.ok(labels.includes(label), `missing ${label}`); + } + assert.equal(fields.find((f) => f.label === "Input").block, true); +}); + +test("headline and evidence split the visit's facts without duplication", () => { + const fields = runStepFields({ + status: "completed", + outcome: "success", + target: "cleanup", + session_id: "sess-1", + diagnostic: "why", + transcript: "said", + control: { visit: 2, max_visits: 4, model_target: "gpt" }, + started_at: "2026-01-01T00:00:00Z", + finished_at: "2026-01-01T00:00:05Z", + input: { prompt: "x" }, + }); + const headline = headlineFields(fields).map((f) => f.label); + assert.deepEqual(headline, ["Status", "Outcome", "Duration", "Visit", "Model target", "Target", "Session"]); + const evidence = evidenceFields(fields).map((f) => f.label); + assert.ok(!evidence.some((label) => headline.includes(label))); + assert.ok(evidence.includes("Diagnostic") && evidence.includes("Transcript")); + assert.ok(!evidence.includes("Input") && !evidence.includes("Output")); +}); + +test("stageSectionSpecs orders the run sections and puts the definition last", () => { + const graph = { + stages: [{ key: "implementer", type: "model", prompt: "do", output: "done", edges: { success: "reviewer" } }], + }; + const step1 = step({ + stage: "implementer", + input: { prompt: "do it" }, + output: { result: "done" }, + diagnostic: "why", + }); + const specs = stageSectionSpecs("implementer", graph, [step1], 0, true); + assert.deepEqual(specs.map((spec) => spec.key), ["artifacts", "output", "input", "run", "definition"]); + assert.deepEqual(specs.map((spec) => spec.title), [ + "Artifacts", + "Output", + "Input", + "This run", + "Stage definition", + ]); + assert.equal(specs[0].artifacts, true); + assert.ok(specs.find((spec) => spec.key === "definition").fields.length > 0); +}); + +test("a session export inserts the Session section after Artifacts", () => { + const graph = { stages: [{ key: "reviewer", type: "model" }] }; + const withSession = step({ + stage: "reviewer", + session_export: { html: "session.html" }, + artifacts: [{ name: "session.html", url: "/a" }], + }); + const specs = stageSectionSpecs("reviewer", graph, [withSession], 0, true); + assert.deepEqual(specs.map((spec) => spec.key), ["artifacts", "session", "definition"]); + assert.equal(specs[1].session, true); +}); + +test("a visit with no results still lists the artifacts gallery and the definition", () => { + const graph = { stages: [{ key: "s", type: "model" }] }; + const specs = stageSectionSpecs("s", graph, [step({ stage: "s" })], 0, true); + assert.deepEqual(specs.map((spec) => spec.key), ["artifacts", "definition"]); + assert.ok(specs.every((spec) => spec.artifacts || spec.fields.length > 0)); +}); + +test("stageDefinitionFields labels outcomes with resolved terminals", () => { + const stage = { + key: "planner", + type: "model", + prompt: "do the thing", + output: "plan", + configs: { model: "gpt", provider: "" }, + edges: { success: "#", error: "cleanup" }, + blocks: { tools: "read\nwrite" }, + limits: { max_visits: 3, on: ["exceeded"] }, + memory: { notes: "notes.md" }, + notify: { on: ["failure"], destination: "ntfy", artifacts: ["log"] }, + }; + const fields = stageDefinitionFields(stage); + const labels = fields.map((f) => f.label); + for (const label of ["Type", "Prompt", "Output", "Outcomes", "Model", "Tools", "Max visits", "Limit on", "Memory", "Notify on", "Notify destination", "Notify artifacts"]) { + assert.ok(labels.includes(label), `missing ${label}`); + } + assert.ok(fields.every((f) => f.value.trim() !== "")); + const outcomes = fields.find((f) => f.label === "Outcomes").value; + assert.ok(outcomes.includes("success → SUCCESS (terminal)")); + assert.ok(outcomes.includes("error → cleanup")); + assert.equal(stageDefinitionFields({ key: "p" }).map((f) => f.value)[0], "model"); +}); + +test("terminalFields lists incoming routes only", () => { + const graph = { stages: [{ key: "a", edges: { success: "#success" } }] }; + assert.deepEqual(terminalFields(graph, "a"), []); + const incoming = terminalFields(graph, "#success"); + assert.deepEqual(incoming.map((f) => f.label), ["Incoming routes"]); + assert.ok(incoming[0].value.includes("a · success → SUCCESS")); +}); + +test("resolveTarget and stageOutcomes mirror the graph semantics", () => { + assert.equal(resolveTarget("error", "#"), "#failure"); + assert.equal(resolveTarget("success", "#"), "#success"); + assert.equal(resolveTarget("success", "reviewer"), "reviewer"); + assert.deepEqual(stageOutcomes({ edges: { error: "x", success: "y", advisory: "z" } }), [ + "success", + "advisory", + "error", + ]); +}); + +// --------------------------------------------------------------------------- +// Verdict +// --------------------------------------------------------------------------- + +test("verdictReasonSegments splits a reason around every referenced name", () => { + const png = { name: "review.png", url: "/review.png" }; + const txt = { name: "report.txt", url: "/report.txt" }; + assert.deepEqual( + verdictReasonSegments("Approved: review.png shows the fix; report.txt lists the checks.", [png, txt]), + [ + { text: "Approved: " }, + { text: "review.png", artifact: png }, + { text: " shows the fix; " }, + { text: "report.txt", artifact: txt }, + { text: " lists the checks." }, + ], + ); +}); + +test("verdictReasonSegments matches a basename and prefers the longer token", () => { + const nested = { name: "shots/wide.png" }; + assert.deepEqual(verdictReasonSegments("See wide.png for the wide layout.", [nested]), [ + { text: "See " }, + { text: "wide.png", artifact: nested }, + { text: " for the wide layout." }, + ]); + const bare = { name: "wide.png" }; + assert.deepEqual(verdictReasonSegments("shots/wide.png is the shot", [bare, nested]), [ + { text: "shots/wide.png", artifact: nested }, + { text: " is the shot" }, + ]); + assert.deepEqual(verdictReasonSegments("nothing referenced here", [{ name: "x.png" }]), [ + { text: "nothing referenced here" }, + ]); + assert.deepEqual(verdictReasonSegments("", [{ name: "x.png" }]), []); + assert.equal(artifactBaseName("shots\\x.png"), "x.png"); +}); + +test("referencedVerdictArtifacts resolves names to recorded files in recorded order", () => { + const a = { name: "a.png" }; + const b = { name: "b.png" }; + const verdict = { option: "approved → success", reason: "b.png then a.png", artifacts: ["b.png", "a.png", "invented.png"] }; + assert.deepEqual(referencedVerdictArtifacts(verdict, [a, b]), [a, b]); + assert.deepEqual(referencedVerdictArtifacts(null, [a]), []); + assert.deepEqual(referencedVerdictArtifacts({ artifacts: [] }, [a]), []); +}); + +// --------------------------------------------------------------------------- +// Formatters and colours +// --------------------------------------------------------------------------- + +test("fileChangeLine adds the binary and truncated markers", () => { + assert.equal(fileChangeLine({ kind: "modified", path: "src/a.kt" }), "modified src/a.kt"); + assert.equal( + fileChangeLine({ kind: "modified", path: "src/a.kt", binary: true, truncated: true }), + "modified src/a.kt (binary) (truncated)", + ); +}); + +test("notificationLine appends a non-blank diagnostic only", () => { + assert.equal(notificationLine({ status: "delivered", destination: "ntfy" }), "delivered → ntfy"); + assert.equal( + notificationLine({ status: "delivered", destination: "ntfy", diagnostic: "ok" }), + "delivered → ntfy · ok", + ); +}); + +test("fileChangesSummary omits blank parts", () => { + assert.equal(fileChangesSummary({ status: "partial", files: [{}, {}], skipped: 1 }), "partial (2 files), 1 skipped"); + assert.equal(fileChangesSummary({}), ""); + assert.equal(fileChangesSummary(null), ""); +}); + +test("outcomeColorToken uses the status palette then the flow palette", () => { + assert.equal(outcomeColorToken("success"), "state succeeded"); + assert.equal(outcomeColorToken("error"), "state failed"); + assert.equal(outcomeColorToken("blocked"), "state blocked"); + assert.equal(outcomeColorToken("approved"), "flow 3"); + assert.equal(outcomeColorToken("rejected"), "flow 0"); + assert.equal(outcomeColorToken("", "running"), "state running"); + assert.equal(stateGlyph("succeeded"), "✓"); + assert.equal(stateGlyph("nonsense"), "?"); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 3146d43d..ded58149 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -361,23 +361,47 @@ try { // real server (the socket stays on the proxy, see the note above) so the tiles // and the viewer load real files rather than proxying a path serve.mjs does // not forward. - step(`opening run 430 and capturing its artifacts gallery`); + step("returning to Runs and opening run 430 (Summary tab)"); await page.fill("#url", artifactServerUrl); await page.clickText("nav.tabs button.tab", "Runs"); await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); await page.click('.list.runs .run-row-meta[data-run-id="430"]'); - await page.waitForSelector(".artifact-gallery .artifact-tile", { timeout: 25000 }); - await page.waitForText("recorded", { timeout: 25000 }); - const tileCount = await page.evaluate( - `document.querySelectorAll(".artifact-gallery .artifact-tile").length`, + await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 }); + + // The run-detail tabs, in the app's order (the Graph body is the R5 item). + const runTabs = await page.evaluate( + `[...document.querySelectorAll(".detail .detail-tabs .detail-tab")].map((n) => n.textContent)`, ); - if (!tileCount) throw new Error("run 430 rendered no artifact tiles"); - console.log(` run 430 gallery tiles: ${tileCount}`); - await page.rect(".artifacts-header"); + if (JSON.stringify(runTabs) !== JSON.stringify(["Summary", "Input", "Output", "Timeline"])) { + throw new Error(`run tabs are wrong: ${runTabs.join(",")}`); + } + console.log(` run tabs: ${runTabs.join(" / ")}`); + + // The run identity line, in the exact recorded/completed vocabulary. + const identity = await page.evaluate(`document.querySelector(".run-identity")?.textContent ?? ""`); + if (!/^run 430 · \d+ recorded visits? · \d+ completed visits?$/.test(identity)) { + throw new Error(`run identity line is wrong: ${identity}`); + } + const runTitle = await page.evaluate( + `document.querySelector(".run-detail-title")?.textContent ?? ""`, + ); + console.log(` summary: ${runTitle} — ${identity}`); + shots.push(await page.screenshot(`${out}/20-run-430-summary.png`)); + + // The run-level artifacts gallery (R8), collapsed by default in Summary. + step("expanding run 430's summary artifacts section (R8)"); + await page.clickText(".run-detail .section-toggle", "Artifacts"); + await page.waitForSelector(".run-detail .artifact-gallery .artifact-tile", { timeout: 25000 }); + const runTiles = await page.evaluate( + `document.querySelectorAll(".run-detail .artifact-gallery .artifact-tile").length`, + ); + console.log(` run 430 run-level gallery tiles: ${runTiles}`); + if (runTiles !== 18) throw new Error(`expected 18 run-level artifact tiles, got ${runTiles}`); + await page.rect(".run-detail .artifact-gallery"); shots.push(await page.screenshot(`${out}/04-run-430-artifacts.png`)); step("opening an image artifact in the full-screen viewer"); - await page.click(".artifact-tile img"); + await page.click(".run-detail .artifact-gallery .artifact-tile img"); await page.waitForSelector(".artifact-viewer", { timeout: 15000 }); await page.waitForText("Close viewer", { timeout: 15000 }); const position = await page.evaluate( @@ -393,22 +417,174 @@ try { { timeout: 8000, what: "the viewer image" }, ).catch(() => console.log(" (viewer image still loading)")); shots.push(await page.screenshot(`${out}/05-artifact-viewer.png`)); - - step("closing the viewer and capturing the session export link (R9)"); await page.click(".viewer-close"); - await eventually( - () => page.evaluate(`!document.querySelector(".artifact-viewer")`), - { timeout: 5000, what: "the viewer to close" }, + await eventually(() => page.evaluate(`!document.querySelector(".artifact-viewer")`), { + timeout: 5000, + what: "the viewer to close", + }); + + // R6: one collapsed field section per recorded input/output entry. + step("opening the Input tab and expanding a field section"); + await page.clickText(".detail .detail-tabs .detail-tab", "Input"); + await page.waitForSelector(".detail .run-tab-body .collapsible .section-toggle", { timeout: 15000 }); + const inputEmpty = await page.evaluate( + `document.querySelector(".detail .run-tab-body .run-empty")?.textContent ?? ""`, ); - await page.rect(".session-link"); + if (inputEmpty !== "") throw new Error(`run 430 input unexpectedly empty: ${inputEmpty}`); + await page.click(".detail .run-tab-body .collapsible .section-toggle"); + await page.waitForSelector(".detail .run-tab-body .field-block", { timeout: 15000 }); + const inputTitles = await page.evaluate( + `[...document.querySelectorAll(".detail .run-tab-body .section-title")].map((n) => n.textContent)`, + ); + console.log(` input fields: ${inputTitles.join(", ")}`); + shots.push(await page.screenshot(`${out}/21-run-430-input.png`)); + + step("opening the Output tab and expanding a field section"); + await page.clickText(".detail .detail-tabs .detail-tab", "Output"); + await page.waitForSelector(".detail .run-tab-body .collapsible .section-toggle", { timeout: 15000 }); + await page.click(".detail .run-tab-body .collapsible .section-toggle"); + await page.waitForSelector(".detail .run-tab-body .field-block", { timeout: 15000 }); + const outputTitles = await page.evaluate( + `[...document.querySelectorAll(".detail .run-tab-body .section-title")].map((n) => n.textContent)`, + ); + console.log(` output fields: ${outputTitles.join(", ")}`); + shots.push(await page.screenshot(`${out}/22-run-430-output.png`)); + + // R7: one compact row per visit, in step order. + step("opening the Timeline tab"); + await page.clickText(".detail .detail-tabs .detail-tab", "Timeline"); + await page.waitForSelector(".detail .timeline-row", { timeout: 15000 }); + const timelineRows = await page.evaluate( + `[...document.querySelectorAll(".detail .timeline-row .timeline-title")].map((n) => n.textContent)`, + ); + console.log(` timeline: ${timelineRows.join(" | ")}`); + if (timelineRows.length !== 3) throw new Error(`expected 3 timeline rows, got ${timelineRows.length}`); + if (timelineRows[0] !== "reviewer · visit 3") { + throw new Error(`first timeline row is wrong: ${timelineRows[0]}`); + } + shots.push(await page.screenshot(`${out}/23-run-430-timeline.png`)); + + // R3: the stage pane: headline rows, Verdict block and the visit's gallery. + step("opening the ui_reviewer stage pane: headline, Verdict and its artifact gallery"); + await page.click('.detail .timeline-row[data-stage-key="ui_reviewer"]'); + await page.waitForSelector(".stage-pane", { timeout: 15000 }); + await page.waitForText("Verdict", { timeout: 15000 }); + const headline = await page.evaluate( + `[...document.querySelectorAll(".stage-pane-body > .kv-row > .kv-key")].map((n) => n.textContent)`, + ); + console.log(` pane headline: ${headline.join(", ")}`); + for (const label of ["Status", "Outcome", "Duration", "Visit", "Target", "Session"]) { + if (!headline.includes(label)) throw new Error(`stage pane headline missing: ${label}`); + } + const verdictTitle = await page.evaluate( + `document.querySelector(".stage-pane .verdict-title")?.textContent ?? ""`, + ); + const verdictOption = await page.evaluate( + `document.querySelector(".stage-pane .verdict .outcome-chip")?.textContent ?? ""`, + ); + if (verdictTitle !== "Verdict") throw new Error(`verdict heading is wrong: ${verdictTitle}`); + console.log(` verdict: ${verdictTitle} — ${verdictOption}`); + await page.clickText(".stage-pane .section-toggle", "Artifacts"); + await page.waitForSelector(".stage-pane .artifact-tile", { timeout: 15000 }); + const paneTiles = await page.evaluate(`document.querySelectorAll(".stage-pane .artifact-tile").length`); + console.log(` ui_reviewer visit 2 pane tiles: ${paneTiles}`); + shots.push(await page.screenshot(`${out}/24-run-430-stage-artifacts.png`)); + + // Escape closes the pane and returns focus to the timeline row that opened it. + step("closing the pane with Escape returns focus to the timeline row"); + await page.evaluate( + `document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))`, + ); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + what: "the stage pane to close on Escape", + }); + const restored = await page.evaluate( + `(() => { const el = document.activeElement; return el ? el.getAttribute("data-stage-key") ?? "" : ""; })()`, + ); + if (restored !== "ui_reviewer") throw new Error(`focus did not return to the timeline row: ${restored}`); + console.log(` focus returned to timeline row: ${restored}`); + + // R9: the visit's exported session file, opened from the pane's Session section. + step("opening the reviewer stage pane and its Session export link (R9)"); + await page.click('.detail .timeline-row[data-stage-key="reviewer"]'); + await page.waitForSelector(".stage-pane", { timeout: 15000 }); + await page.clickText(".stage-pane .section-toggle", "Session"); + await page.waitForSelector(".stage-pane .session-link", { timeout: 15000 }); const sessionHref = await page.evaluate( - `document.querySelector(".session-link")?.getAttribute("href") ?? ""`, + `document.querySelector(".stage-pane .session-link")?.getAttribute("href") ?? ""`, ); if (!/session\.html$/.test(sessionHref)) { throw new Error(`the session export link did not resolve: ${sessionHref}`); } console.log(` session export link: ${sessionHref}`); shots.push(await page.screenshot(`${out}/06-session-export-link.png`)); + await page.click(".stage-pane-back"); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + what: "the stage pane to close on Back", + }); + + // The verdict-bearing stage pane on the failed run 440. + step("opening run 440 and capturing its verdict-bearing stage pane"); + 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", "Timeline"); + await page.waitForSelector(".detail .timeline-row", { timeout: 15000 }); + await page.click(".detail .timeline-row"); + await page.waitForSelector(".stage-pane", { timeout: 15000 }); + await page.waitForText("Verdict", { timeout: 15000 }); + const verdict440 = await page.evaluate( + `document.querySelector(".stage-pane .verdict .outcome-chip")?.textContent ?? ""`, + ); + console.log(` run 440 verdict: ${verdict440}`); + shots.push(await page.screenshot(`${out}/25-run-440-verdict.png`)); + await page.evaluate( + `document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))`, + ); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + what: "the run 440 pane to close", + }); + + // The Timeline empty state, on a run that recorded no visits (R7). + step("opening run 428: the Timeline empty state"); + await page.click('.list.runs .run-row-meta[data-run-id="428"]'); + await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 }); + await page.clickText(".detail .detail-tabs .detail-tab", "Timeline"); + await page.waitForSelector(".detail .run-tab-body .run-empty", { timeout: 15000 }); + const emptyTimeline = await page.evaluate( + `document.querySelector(".detail .run-tab-body .run-empty")?.textContent ?? ""`, + ); + if (emptyTimeline !== "No visits recorded.") { + throw new Error(`timeline empty state is wrong: ${emptyTimeline}`); + } + console.log(` timeline empty state: ${emptyTimeline}`); + shots.push(await page.screenshot(`${out}/26-run-428-timeline-empty.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(`(() => { + 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 (runningId == null) { + console.log(" -- no running run available; skipped the output empty state"); + } else { + await page.click(`.list.runs .run-row-meta[data-run-id="${runningId}"]`); + await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 }); + await page.clickText(".detail .detail-tabs .detail-tab", "Output"); + await page.waitForSelector(".detail .run-tab-body .run-empty", { timeout: 15000 }); + const emptyOutput = await page.evaluate( + `document.querySelector(".detail .run-tab-body .run-empty")?.textContent ?? ""`, + ); + if (emptyOutput !== "No output recorded.") { + throw new Error(`output empty state is wrong: ${emptyOutput}`); + } + console.log(` output empty state (run ${runningId}): ${emptyOutput}`); + shots.push(await page.screenshot(`${out}/27-run-output-empty.png`)); + } console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`);