Files
pipelines/web/src/views/dialogs.js
T

969 lines
32 KiB
JavaScript

// Full-screen and modal dialogs owned by the run detail and chat surfaces:
// the rendered/raw diff viewer, the artifact viewer, the human-decision sheet,
// the shared cancel/retry confirm and the shared Action-failed report.
import { backChevronIcon, h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact, artifactBrowserLinkProps } from "../dom.js";
import { changeKindTone, describeError } from "../format.js";
import { definitionDocument } from "./stageDefinition.js";
import {
BINARY_DIFF_MESSAGE,
NO_LINE_CHANGES_MESSAGE,
TRUNCATED_PATCH_NOTE,
changeKindTitle,
changePositionLabel,
changeStat,
diffLineClass,
diffLineSymbol,
entryHasPatch,
gutterText,
gutterWidth,
parseUnifiedPatch,
patchUnavailableReason,
} from "../changes.js";
import {
ArtifactKind,
artifactKind,
artifactViewerPositionLabel,
isMarkdownArtifact,
pagedIndex,
resolvedArtifactUrl,
} from "../artifacts.js";
import {
ACTION_FAILED_OK,
ACTION_FAILED_TITLE,
CANCEL_CONFIRM,
CANCEL_DIALOG_MESSAGE,
DECISION_CANCEL,
DECISION_CONFIRM,
DECISION_SENDING,
DISMISS_KEEP,
DecisionDraft,
FEEDBACK_LABEL,
RESTART_CONFIRM,
RESTART_DIALOG_MESSAGE,
RETRY_CONFIRM,
RETRY_DIALOG_MESSAGE,
cancelDialogTitle,
decisionSheetMeta,
decisionSheetTitle,
optionTargetText,
restartDialogTitle,
retryDialogTitle,
retryRequestKey,
} from "../actions.js";
export function createDialogsView(rt) {
const { state, repo, modal } = rt;
const renderContent = (...args) => rt.renderContent(...args);
const selectRun = (...args) => rt.selectRun(...args);
let changeViewerOverlay = null;
let changeViewerIndex = null;
let refreshAudit = null;
function refreshStageAudit() { refreshAudit?.(); }
/** Close the diff viewer; the controller returns focus to the viewed row. */
function closeChangeViewer() {
modal.close("change-viewer");
changeViewerIndex = null;
changeViewerOverlay = null;
}
/**
* The full-screen diff viewer for one changed file. It pages through the run's
* changed files exactly as the artifact viewer pages through a gallery's media
* (one shared index, previous/next affordances, Escape/the close button/backdrop
* dismissing), and shows both forms the brief requires, switchable from one
* control row: the **Rendered** reading (each hunk's `@@` header, the shared
* diff line language and the old/new gutter numbers) and the **Raw patch** (the
* server's unified patch verbatim in monospace). A file the server could not
* give a patch for (binary, truncated, or a capture that recorded none) shows the
* honest reason in place of a diff rather than a fabricated one.
*/
function openChangeViewer(files, startIndex, trigger = null) {
closeChangeViewer();
if (!files?.length) return;
let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1);
let form = "rendered";
const overlay = h("div", {
class: "change-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Diff viewer",
});
const panel = h("div", { class: "change-viewer-panel" });
overlay.append(panel);
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeChangeViewer();
});
const renderViewer = () => {
const entry = files[index];
changeViewerIndex = index;
const stat = changeStat(entry.added, entry.removed);
const hasPatch = entryHasPatch(entry);
const titles = h("div", { class: "change-viewer-titles" });
const titleRow = h("div", { class: "change-viewer-title-row" });
titleRow.append(
h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindTitle(entry.kind) }),
);
if (stat !== "") titleRow.append(h("span", { class: "change-viewer-stat monospace", text: stat }));
titles.append(titleRow);
titles.append(h("div", { class: "change-viewer-path monospace", text: entry.path }));
titles.append(
h("div", {
class: "change-viewer-position muted",
text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`,
}),
);
const head = h("div", { class: "change-viewer-head" }, titles);
const controls = h(
"div",
{ class: "change-viewer-controls" },
h("button", {
class: `change-form${form === "rendered" ? " active" : ""}`,
type: "button",
"data-form": "rendered",
text: "Rendered",
disabled: form === "rendered",
onclick: () => {
form = "rendered";
renderViewer();
},
}),
h("button", {
class: `change-form${form === "raw" ? " active" : ""}`,
type: "button",
"data-form": "raw",
text: "Raw patch",
disabled: !hasPatch,
onclick: () => {
form = "raw";
renderViewer();
},
}),
h("div", { class: "change-viewer-spacer" }),
h("button", {
class: "change-icon",
type: "button",
"data-action": "copy",
title: "Copy raw patch",
"aria-label": "Copy raw patch",
text: "\u29c9",
disabled: !hasPatch,
onclick: () => copyText(entry.patch ?? ""),
}),
h("button", {
class: "change-icon",
type: "button",
"data-page": "prev",
title: "Previous file",
"aria-label": "Previous file",
text: "\u2039",
disabled: index === 0,
onclick: () => {
index = Math.max(index - 1, 0);
form = "rendered";
renderViewer();
},
}),
h("button", {
class: "change-icon",
type: "button",
"data-page": "next",
title: "Next file",
"aria-label": "Next file",
text: "\u203a",
disabled: index === files.length - 1,
onclick: () => {
index = Math.min(index + 1, files.length - 1);
form = "rendered";
renderViewer();
},
}),
h("button", {
class: "change-icon",
type: "button",
"data-action": "close",
title: "Close diff",
"aria-label": "Close diff",
text: "\u00d7",
onclick: closeChangeViewer,
}),
);
const body = h("div", { class: "change-viewer-body" });
if (entry.binary || !hasPatch) {
body.append(
h("div", {
class: "change-honest muted",
text: entry.binary ? BINARY_DIFF_MESSAGE : patchUnavailableReason(entry),
}),
);
} else if (form === "raw") {
body.append(h("pre", { class: "change-raw monospace", text: entry.patch ?? "" }));
} else {
body.append(renderRenderedDiff(entry));
}
// The toolbar is the first row: paging/copy/close never move when the
// path or the diff length changes.
panel.replaceChildren(controls, head, body);
};
renderViewer();
changeViewerOverlay = overlay;
modal.open("change-viewer", overlay, {
onClose: () => closeChangeViewer(),
trigger,
restore: () =>
changeViewerIndex == null
? null
: document.querySelector(`.change-row[data-change-index="${changeViewerIndex}"]`),
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
}
/** The rendered reading: the stat line, an optional truncation note, each hunk. */
function renderRenderedDiff(entry) {
const wrap = h("div", { class: "change-diff" });
const parsed = parseUnifiedPatch(entry.patch);
const statLine = h("div", { class: "change-diff-stat" });
if (parsed.added > 0) statLine.append(h("span", { class: "stat-add", text: `+${parsed.added}` }));
if (parsed.removed > 0) statLine.append(h("span", { class: "stat-del", text: `-${parsed.removed}` }));
if (parsed.added === 0 && parsed.removed === 0) {
statLine.append(h("span", { class: "muted", text: NO_LINE_CHANGES_MESSAGE }));
}
wrap.append(statLine);
if (entry.truncated) wrap.append(h("div", { class: "change-diff-note muted", text: TRUNCATED_PATCH_NOTE }));
for (const hunk of parsed.hunks) wrap.append(renderHunk(hunk));
return wrap;
}
/**
* One `@@` hunk: its header on a raised surface, then its lines in a
* horizontally scrollable container, each with its old/new gutter numbers (blank
* on the absent side and on a `\ No newline` marker) and the shared
* `{symbol} {text}` coloured by kind.
*/
function renderHunk(hunk) {
const width = gutterWidth(hunk);
const wrap = h("div", { class: "change-hunk" });
wrap.append(h("div", { class: "change-hunk-head", text: hunk.header }));
const lines = h("div", { class: "change-hunk-lines" });
for (const line of hunk.lines) {
const gutter = line.noNewlineMarker
? " ".repeat(width * 2 + 1)
: `${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}`;
lines.append(
h(
"div",
{ class: "change-line" },
h("span", { class: "change-gutter", text: gutter }),
h("span", { class: `change-text ${diffLineClass(line.kind)}`, text: `${diffLineSymbol(line.kind)} ${line.text}` }),
),
);
}
wrap.append(lines);
return wrap;
}
function openDecisionSheet(decision) {
state.runDecision = decision;
state.decisionOpen = true;
state.decisionDraft = new DecisionDraft();
state.decisionError = "";
renderContent();
}
/** Dismiss the decision sheet (never while a decision is in flight). */
function closeDecisionSheet() {
if (state.decisionSending) return;
const wasOpen = state.decisionOpen;
state.decisionOpen = false;
state.runDecision = null;
state.decisionError = "";
state.decisionDraft = new DecisionDraft();
if (!wasOpen) return;
renderContent();
}
/**
* The decision sheet (R11): the waiting stage, the author's recorded
* instructions, one selectable row per option (with its resolved target when
* declared), the optional feedback field and the deliberate confirm. Selecting a
* row never sends; a refusal keeps the sheet open with the server's exact reason.
*/
function renderDecisionSheet(decision) {
const overlay = h("div", {
class: "decision-sheet",
role: "dialog",
"aria-modal": "true",
"aria-label": decisionSheetTitle(decision.stageKey),
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeDecisionSheet();
});
const sheet = h("div", { class: "decision-sheet-panel" });
sheet.append(h("h2", { class: "decision-sheet-title", text: decisionSheetTitle(decision.stageKey) }));
sheet.append(h("div", { class: "decision-sheet-meta muted", text: decisionSheetMeta(decision) }));
if (String(decision.instructions ?? "").trim() !== "") {
sheet.append(h("p", { class: "decision-instructions", text: decision.instructions }));
}
const options = h("div", { class: "decision-options", role: "radiogroup", "aria-label": "Options" });
for (const option of decision.options) {
const selected = state.decisionDraft.selected === option.key;
const row = h("button", {
class: `decision-option${selected ? " selected" : ""}`,
type: "button",
role: "radio",
"aria-checked": selected ? "true" : "false",
"data-option": option.key,
onclick: () => {
state.decisionDraft = state.decisionDraft.select(option.key);
renderContent();
},
});
row.append(h("span", { class: "decision-radio", "aria-hidden": "true" }));
const body = h("span", { class: "decision-option-body" });
body.append(h("span", { class: "decision-option-key", text: option.key }));
const target = optionTargetText(option.target);
if (target !== "") body.append(h("span", { class: "decision-option-target muted", text: target }));
row.append(body);
options.append(row);
}
sheet.append(options);
const field = h("label", { class: "decision-field" });
field.append(h("span", { class: "decision-field-label", text: FEEDBACK_LABEL }));
field.append(
h("input", {
class: "decision-feedback",
type: "text",
value: state.decisionDraft.feedback,
spellcheck: "false",
oninput: (event) => {
state.decisionDraft = state.decisionDraft.withFeedback(event.target.value);
},
}),
);
sheet.append(field);
if (state.decisionError) sheet.append(h("div", { class: "decision-error bad", text: state.decisionError }));
const actions = h("div", { class: "decision-sheet-actions" });
actions.append(
h("button", {
class: "ghost decision-cancel",
type: "button",
text: DECISION_CANCEL,
disabled: state.decisionSending,
onclick: closeDecisionSheet,
}),
);
actions.append(
h("button", {
class: "decision-confirm",
type: "button",
text: state.decisionSending ? DECISION_SENDING : DECISION_CONFIRM,
disabled: !state.decisionDraft.canSubmit || state.decisionSending,
onclick: () => confirmDecision(decision),
}),
);
sheet.append(actions);
overlay.append(sheet);
modal.stage("decision-sheet", overlay, {
onClose: () => closeDecisionSheet(),
triggerSelector: ".decision-card .decision-open",
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return overlay;
}
/** Send the chosen decision; on refusal show the server's reason and re-read. */
async function confirmDecision(decision) {
if (state.decisionSending || !state.decisionDraft.canSubmit) return;
const option = state.decisionDraft.selected;
state.decisionSending = true;
state.decisionError = "";
renderContent();
try {
await repo.decideRun(decision.runId, {
stage: decision.stageKey,
option,
feedback: state.decisionDraft.feedback,
});
state.decisionSending = false;
state.decisionOpen = false;
state.runDecision = null;
state.decisionDraft = new DecisionDraft();
await selectRun(decision.runId, { silent: true });
} catch (error) {
state.decisionSending = false;
state.decisionError = describeError(error);
await selectRun(decision.runId, { silent: true });
}
renderContent();
}
/** Open one of the shared confirm dialogs (cancel / retry / restart). */
function openConfirm(kind) {
state.confirmKind = kind;
renderContent();
}
function dismissConfirm() {
state.confirmKind = null;
renderContent();
}
/**
* The shared confirm dialog: the exact Android title/message for cancel and
* retry (with Keep as the dismiss), plus the browser-only "Restart from start"
* secondary confirm that plainly states the whole-pipeline replay. The dismiss
* button is "Keep".
*/
function renderConfirmDialog(d) {
const kind = state.confirmKind;
if (!kind) return null;
const runId = kind.runId ?? d.id;
let title;
let message;
let confirmLabel;
let secondary = null;
if (kind.kind === "cancel") {
title = cancelDialogTitle(runId);
message = CANCEL_DIALOG_MESSAGE;
confirmLabel = CANCEL_CONFIRM;
} else if (kind.kind === "retry") {
title = retryDialogTitle(runId);
message = RETRY_DIALOG_MESSAGE;
confirmLabel = RETRY_CONFIRM;
secondary = { label: RESTART_CONFIRM, next: { kind: "restart", runId } };
} else {
title = restartDialogTitle(runId);
message = RESTART_DIALOG_MESSAGE;
confirmLabel = RESTART_CONFIRM;
}
const overlay = h("div", {
class: `confirm-dialog confirm-${kind.kind}`,
role: "dialog",
"aria-modal": "true",
"aria-label": title,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissConfirm();
});
const panel = h("div", { class: "confirm-panel" });
panel.append(h("h2", { class: "confirm-title", text: title }));
panel.append(h("p", { class: "confirm-message", text: message }));
const actions = h("div", { class: "confirm-actions" });
if (secondary) {
actions.append(
h("button", {
class: "ghost confirm-secondary",
type: "button",
text: secondary.label,
onclick: () => openConfirm(secondary.next),
}),
);
}
actions.append(
h("button", {
class: "ghost confirm-dismiss",
type: "button",
text: DISMISS_KEEP,
onclick: dismissConfirm,
}),
);
actions.append(
h("button", {
class: "confirm-accept",
type: "button",
text: confirmLabel,
onclick: () => acceptConfirm(kind),
}),
);
panel.append(actions);
overlay.append(panel);
modal.stage("confirm", overlay, {
onClose: () => dismissConfirm(),
triggerSelector:
kind.kind === "cancel" ? ".run-actions .cancel-run" : ".run-actions .retry-run",
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
return overlay;
}
/**
* Run the confirmed action, then a silent get_run refresh — exactly as the
* Android client does. A server refusal is reported through the one shared
* Action-failed dialog.
*/
async function acceptConfirm(kind) {
const runId = kind.runId ?? state.runDetail?.id;
state.confirmKind = null;
renderContent();
try {
if (kind.kind === "cancel") {
await repo.cancelRun(runId);
} else {
const mode = kind.kind === "restart" ? "restart" : "resume";
await repo.retryRun(runId, { mode, requestKey: retryRequestKey(runId) });
}
} catch (error) {
state.actionError = describeError(error);
}
await selectRun(runId, { silent: true });
renderContent();
}
/** The one shared "Action failed" dialog (title, the server's message, OK). */
function renderActionFailedDialog() {
const overlay = h("div", {
class: "action-failed",
role: "dialog",
"aria-modal": "true",
"aria-label": ACTION_FAILED_TITLE,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) dismissActionError();
});
const panel = h("div", { class: "action-failed-panel" });
panel.append(h("h2", { class: "action-failed-title", text: ACTION_FAILED_TITLE }));
panel.append(h("p", { class: "action-failed-message", text: state.actionError }));
panel.append(
h("button", { class: "action-failed-ok", type: "button", text: ACTION_FAILED_OK, onclick: dismissActionError }),
);
overlay.append(panel);
modal.stage("action-error", overlay, {
onClose: () => dismissActionError(),
fallbackSelectors: ["#detailTitle", "#listTitle", "#pane-main"],
});
return overlay;
}
function dismissActionError() {
state.actionError = "";
renderContent();
}
let viewerOverlay = null;
let viewerSession = null;
/** Close the full-screen viewer; the controller returns focus to its trigger. */
function closeArtifactViewer() {
if (viewerSession) {
viewerSession.closed = true;
viewerSession.abort?.abort();
viewerSession = null;
}
modal.close("artifact-viewer");
viewerOverlay = null;
}
/**
* Open the full-screen viewer at `startIndex` into `viewable`, the same ordered
* list the grid drew (images, videos and markdown/text documents). Previous/Next
* are disabled at the ends; ArrowLeft/ArrowRight page the same list; Escape and a
* click on the dimmed backdrop close it, while clicks inside the panel never do.
* Nothing autoplays: a video shows a still poster placeholder instead.
*
* Markdown and text artifacts are fetched once per viewer session from the
* resolved artifact URL and rendered with the page's own markdown renderer,
* building DOM nodes (never innerHTML). A failed fetch or render keeps the
* viewer honest: it shows describeError's message, the resolved-external action
* and the normal Open/Copy/Share actions.
*/
function openArtifactViewer(viewable, startIndex, trigger = null) {
closeArtifactViewer();
if (!viewable?.length) return;
let index = pagedIndex(startIndex, 0, viewable.length);
const session = {
closed: false,
generation: 0,
abort: null,
cache: new Map(),
errors: new Map(),
};
const overlay = h("div", {
class: "artifact-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Artifact viewer",
});
const panel = h("div", { class: "viewer-panel", "data-viewer-focus": "panel", tabindex: "-1" });
overlay.append(panel);
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeArtifactViewer();
});
/** The focus key of the control inside the panel that currently owns focus. */
const focusedKey = () => {
const active = document.activeElement;
if (!panel.contains(active)) return null;
return active?.getAttribute?.("data-viewer-focus") ?? null;
};
/** Keep focus inside the viewer after the panel is rebuilt. */
const restoreFocus = (key) => {
if (!key) return;
const target =
key === "panel" ? panel : panel.querySelector(`[data-viewer-focus="${key}"]`);
if (target && !target.disabled) target.focus({ preventScroll: true });
else panel.focus({ preventScroll: true });
};
const step = (delta) => {
const next = pagedIndex(index, delta, viewable.length);
if (next === index) return;
index = next;
renderViewer({ restore: true });
};
overlay.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") {
event.preventDefault();
step(-1);
} else if (event.key === "ArrowRight") {
event.preventDefault();
step(1);
}
});
const renderViewer = ({ restore = false } = {}) => {
const keepFocus = restore ? focusedKey() : null;
const generation = ++session.generation;
const artifact = viewable[index] ?? {};
const resolved = resolvedArtifactUrl(artifact, state.url);
const kind = artifactKind(artifact.content_type, artifact.name);
const markdown = isMarkdownArtifact(artifact.content_type, artifact.name);
const name = artifact.name || "(unnamed artifact)";
const board = h("div", { class: "viewer-board" });
if (kind === ArtifactKind.Image && resolved) {
board.append(h("img", { class: "viewer-image", src: resolved, alt: name }));
} else if (kind === ArtifactKind.Video) {
board.append(
h(
"div",
{ class: "viewer-placeholder" },
h("span", { class: "artifact-play", text: "▶" }),
h("span", { class: "viewer-placeholder-name", text: name }),
),
);
} else if (markdown) {
board.classList.add("viewer-board-document");
const renderMarkdown = rt.views?.chat?.renderMarkdown;
const showFailure = (message) => {
const error = h("div", { class: "viewer-error" });
error.append(h("div", { class: "viewer-error-message", text: message }));
if (resolved) {
error.append(
h("a", {
class: "viewer-external",
...artifactBrowserLinkProps(resolved),
text: `Open ${name} externally`,
}),
);
}
board.append(error);
};
const draw = (text) => {
try {
const article = h("div", { class: "viewer-markdown" });
article.append(renderMarkdown(text));
board.append(article);
return true;
} catch (error) {
showFailure(describeError(error));
return false;
}
};
if (!resolved) {
showFailure("Set the server URL in Settings to open this artifact.");
} else if (session.cache.has(resolved)) {
draw(session.cache.get(resolved));
} else if (session.errors.has(resolved)) {
showFailure(session.errors.get(resolved));
} else if (typeof renderMarkdown !== "function") {
showFailure("Markdown rendering is unavailable.");
} else {
board.append(h("div", { class: "viewer-loading muted", text: "Loading markdown…" }));
session.abort?.abort();
const controller = new AbortController();
session.abort = controller;
(async () => {
try {
const response = await fetch(resolved, { signal: controller.signal });
if (!response.ok) throw new Error(`The server answered ${response.status}.`);
const text = await response.text();
if (session.closed || generation !== session.generation) return;
session.cache.set(resolved, text);
renderViewer({ restore: true });
} catch (error) {
if (error?.name === "AbortError" || session.closed || generation !== session.generation) return;
session.errors.set(resolved, describeError(error));
renderViewer({ restore: true });
}
})();
}
} else {
board.append(
h(
"div",
{ class: "viewer-placeholder" },
h("span", { class: "artifact-play", text: "▶" }),
h("span", { class: "viewer-placeholder-name", text: name }),
),
);
}
const head = h(
"div",
{ class: "viewer-head" },
h("div", { class: "viewer-title", text: name }),
h("div", {
class: "viewer-position muted",
text: artifactViewerPositionLabel(index, viewable.length, artifact.content_type),
}),
);
const actions = h("div", { class: "viewer-actions" });
// Where this file came from: a run's evidence is only interpretable next to
// the run, so the viewer offers the trip back without closing on a guess.
const runId = Number(artifact.run_id ?? state.selectedRunId ?? 0);
if (Number.isFinite(runId) && runId > 0) {
actions.append(
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "run",
text: `Open run ${runId}`,
onclick: () => {
closeArtifactViewer();
selectRun(runId);
},
}),
);
}
if (resolved) {
actions.append(
h("a", {
class: "viewer-action browser-button",
...artifactBrowserLinkProps(resolved),
"data-viewer-focus": "open",
text: "Open in browser",
}),
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "copy",
text: "Copy link",
disabled: !canCopyLink(),
onclick: () => copyArtifactLink(resolved),
}),
h("button", {
class: "viewer-action",
type: "button",
"data-viewer-focus": "share",
text: "Share",
disabled: !canShare(),
onclick: () => shareArtifact(resolved),
}),
);
}
actions.append(
h("button", {
class: "viewer-action viewer-close",
type: "button",
"data-viewer-focus": "close",
text: "Close viewer",
onclick: closeArtifactViewer,
}),
);
const nodes = [head, board];
if (viewable.length > 1) {
nodes.push(
h(
"div",
{ class: "viewer-nav" },
h("button", {
class: "viewer-page",
type: "button",
"data-viewer-focus": "prev",
text: "Previous artifact",
disabled: pagedIndex(index, -1, viewable.length) === index,
onclick: () => step(-1),
}),
h("button", {
class: "viewer-page",
type: "button",
"data-viewer-focus": "next",
text: "Next artifact",
disabled: pagedIndex(index, 1, viewable.length) === index,
onclick: () => step(1),
}),
),
);
}
nodes.push(actions);
panel.replaceChildren(...nodes);
if (restore) restoreFocus(keepFocus ?? "panel");
};
renderViewer();
viewerOverlay = overlay;
viewerSession = session;
modal.open("artifact-viewer", overlay, {
onClose: () => closeArtifactViewer(),
trigger,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
}
/** Graph inspection reuses the audit viewer without touching pane/route state. */
function openStageDefinition(detail, stageKey, subtitle = "") {
openStageAudit({
title: `${stageKey} definition`,
subtitle,
tabs: [{ key: "definition", label: "Definition", body: () =>
definitionDocument(detail, stageKey, (text) => rt.views.chat.renderMarkdown(text)) }],
});
}
/**
* The Audit & debug dialog: a stage's turn-owned evidence behind vertical tabs
* (Input, Output, Memory, Session, Stage definition), the chosen section's body
* on the right. It is the only place the system files are shown, so the artifact
* surfaces stay focused on what the stage actually produced.
*/
function openStageAudit({ title = "Audit", subtitle = "", tabs = [], trigger = null, revision = null } = {}) {
const available = (tabs ?? []).filter((tab) => typeof tab?.body === "function");
if (!available.length) return;
const close = () => { refreshAudit = null; modal.close("stage-audit"); };
const overlay = h("div", {
class: "audit-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": title,
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) close();
});
const closeButton = h("button", {
class: "audit-close",
type: "button",
text: "Close",
onclick: close,
});
const panel = h("div", { class: "audit-panel" });
panel.append(
h(
"div",
{ class: "audit-head" },
h("button", { class: "ghost back-button audit-back", type: "button", "aria-label": "Back to stage", title: "Back to stage", onclick: close }, backChevronIcon()),
h(
"div",
{ class: "audit-titles" },
h("h2", { class: "audit-title", text: title }),
subtitle ? h("p", { class: "audit-subtitle muted", text: subtitle }) : null,
),
closeButton,
),
);
const nav = h("nav", {
class: "audit-tabs",
role: "tablist",
"aria-orientation": window.matchMedia("(max-width: 599px)").matches ? "horizontal" : "vertical",
"aria-label": "Audit sections",
});
const body = h("div", {
class: "audit-body",
id: "auditBody",
role: "tabpanel",
tabindex: "0",
});
panel.append(h("div", { class: "audit-layout" }, nav, body));
overlay.append(panel);
let active = available[0].key;
let renderedRevision = null;
const renderBody = () => {
const current = available.find((tab) => tab.key === active) ?? available[0];
body.replaceChildren(current.body());
renderedRevision = typeof revision === "function" ? revision(active) : null;
};
const renderTabs = () => {
nav.replaceChildren(
...available.map((tab) => {
const selected = tab.key === active;
return h("button", {
class: `audit-tab${selected ? " active" : ""}`,
type: "button",
role: "tab",
"aria-selected": selected ? "true" : "false",
"aria-controls": "auditBody",
"data-audit-tab": tab.key,
tabindex: selected ? "0" : "-1",
text: tab.label,
onclick: () => {
active = tab.key;
renderTabs();
},
onkeydown: (event) => {
const index = available.findIndex((entry) => entry.key === tab.key);
let next = -1;
if (event.key === "ArrowDown" || event.key === "ArrowRight") next = (index + 1) % available.length;
else if (event.key === "ArrowUp" || event.key === "ArrowLeft") next = (index - 1 + available.length) % available.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = available.length - 1;
if (next < 0) return;
event.preventDefault();
active = available[next].key;
renderTabs();
nav.querySelector(`[data-audit-tab="${active}"]`)?.focus();
},
});
}),
);
renderBody();
};
renderTabs();
modal.open("stage-audit", overlay, {
onClose: () => close(),
trigger,
fallbackSelectors: ["#detailTitle", "#pane-main"],
});
refreshAudit = () => {
if (!overlay.isConnected || typeof revision !== "function") return;
if (revision(active) !== renderedRevision) renderBody();
};
}
return {
refreshStageAudit,
openStageDefinition,
closeChangeViewer,
openChangeViewer,
openDecisionSheet,
closeDecisionSheet,
renderDecisionSheet,
confirmDecision,
openConfirm,
dismissConfirm,
renderConfirmDialog,
acceptConfirm,
renderActionFailedDialog,
dismissActionError,
closeArtifactViewer,
openArtifactViewer,
openStageAudit,
};
}