1463 lines
53 KiB
JavaScript
1463 lines
53 KiB
JavaScript
// The run detail: Summary / Graph / Input / Output / Timeline, the per-visit
|
||
// stage pane, the decision card and run actions, the Summary title/rename row and
|
||
// the run's artifact gallery. Pure models live in runDetail.js, changes.js,
|
||
// artifacts.js and actions.js; dialogs are delegated to dialogs.js.
|
||
|
||
import { backChevronIcon, h, kvMono, canCopyLink, canShare, copyArtifactLink, shareArtifact, artifactBrowserLinkProps, openArtifactInBrowser } from "../dom.js";
|
||
import { isExecuting, changeKindTone, describeError } from "../format.js";
|
||
import { resolveArtifactUrl } from "../serverUrl.js";
|
||
import { runStateOf, runStatusLabel } from "../runs.js";
|
||
import { scheduledRunLabel } from "../scheduleOrigin.js";
|
||
import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, mount as mountGraph } from "../graph.js";
|
||
import { writeGraphExpanded } from "../graphPrefs.js";
|
||
import { definitionDocument } from "./stageDefinition.js";
|
||
import {
|
||
RENDERED_RUN_TABS,
|
||
EMPTY_INPUT_MESSAGE,
|
||
EMPTY_OUTPUT_MESSAGE,
|
||
EMPTY_TIMELINE_MESSAGE,
|
||
NO_STAGE_DETAILS_MESSAGE,
|
||
originalRunPrompt,
|
||
fieldSections,
|
||
summaryRows,
|
||
runIdentityLine,
|
||
runLabelFor,
|
||
runDurationText,
|
||
runTimeline,
|
||
runGraphState,
|
||
nodeLabel,
|
||
headlineFields,
|
||
runStepFields,
|
||
stageSectionSpecs,
|
||
clampVisitIndex,
|
||
referencedVerdictArtifacts,
|
||
verdictReasonSegments,
|
||
outcomeColorToken,
|
||
stateGlyph,
|
||
looksLikeMarkdown,
|
||
} from "../runDetail.js";
|
||
import {
|
||
ArtifactKind,
|
||
artifactCaptureNotes,
|
||
artifactGroups,
|
||
artifactKind,
|
||
artifactKindLabel,
|
||
artifactsHeader,
|
||
artifactsSummary,
|
||
artifactViewerPositionLabel,
|
||
displayVisit,
|
||
humanBytes,
|
||
isViewerArtifact,
|
||
pagedArtifacts,
|
||
presentedArtifacts,
|
||
resolvedArtifactUrl,
|
||
sessionExportArtifact,
|
||
effectiveSessionExport,
|
||
sessionCaptureState,
|
||
stageArtifacts,
|
||
systemArtifacts,
|
||
visitArtifacts,
|
||
viewerIndexByUrl,
|
||
} from "../artifacts.js";
|
||
import { writeArtifactView } from "../artifactViewPrefs.js";
|
||
import {
|
||
BINARY_DIFF_MESSAGE,
|
||
NO_LINE_CHANGES_MESSAGE,
|
||
TRUNCATED_PATCH_NOTE,
|
||
ChangeKind,
|
||
changeKindLabel,
|
||
changeKindTitle,
|
||
changePositionLabel,
|
||
changeRowMeta,
|
||
changeStat,
|
||
changesListSummary,
|
||
diffLineClass,
|
||
diffLineSymbol,
|
||
entryHasPatch,
|
||
gutterText,
|
||
gutterWidth,
|
||
noChangeDetail,
|
||
parseUnifiedPatch,
|
||
patchUnavailableReason,
|
||
runChanges,
|
||
runChangesHeader,
|
||
runChangesNote,
|
||
showRunChangesSummary,
|
||
} from "../changes.js";
|
||
import {
|
||
DECISION_ACTION,
|
||
DECISION_CARD_TITLE,
|
||
RENAME_ACTION,
|
||
RENAME_CANCEL,
|
||
RENAME_FIELD_LABEL,
|
||
RENAME_SAVE,
|
||
canCancel,
|
||
canRetry,
|
||
decisionCardMeta,
|
||
pendingDecision,
|
||
} from "../actions.js";
|
||
|
||
/** Shown where tiles exist but the configured server URL cannot resolve them. */
|
||
const ARTIFACT_SERVER_HINT =
|
||
"Set the server URL in Settings to open or copy artifact links.";
|
||
|
||
export function createRunDetailView(rt) {
|
||
const { state, repo, modal } = rt;
|
||
const renderContent = (...args) => rt.renderContent(...args);
|
||
const selectRun = (...args) => rt.selectRun(...args);
|
||
const pushRoute = (...args) => rt.pushRoute(...args);
|
||
const openChangeViewer = (...args) => rt.views.dialogs.openChangeViewer(...args);
|
||
const openDecisionSheet = (...args) => rt.views.dialogs.openDecisionSheet(...args);
|
||
const openConfirm = (...args) => rt.views.dialogs.openConfirm(...args);
|
||
const renderDecisionSheet = (...args) => rt.views.dialogs.renderDecisionSheet(...args);
|
||
const renderConfirmDialog = (...args) => rt.views.dialogs.renderConfirmDialog(...args);
|
||
const renderActionFailedDialog = (...args) => rt.views.dialogs.renderActionFailedDialog(...args);
|
||
const openArtifactViewer = (...args) => rt.views.dialogs.openArtifactViewer(...args);
|
||
const showStageAudit = (...args) => rt.views.dialogs.openStageAudit(...args);
|
||
const selectPipeline = (...args) => rt.selectPipeline(...args);
|
||
const sessionRepairs = new Set();
|
||
|
||
function sessionExportRetry(step) {
|
||
const run = state.runDetail;
|
||
if (!run?.id || !step?.sequence || !(step.session_id || step.session_export?.session_id)) return null;
|
||
const key = `${run.id}:${step.sequence}`;
|
||
const running = step.agent_active || ["running", "queued"].includes(run.status) ||
|
||
(run.status === "waiting" && run.export_pending_sequence !== step.sequence);
|
||
const button = h("button", {
|
||
class: "ghost session-export-retry",
|
||
type: "button",
|
||
disabled: running || sessionRepairs.has(key),
|
||
text: sessionRepairs.has(key) ? "Exporting…" : "Retry export only",
|
||
title: "Read the exact recorded session again. Does not rerun the stage or its tools.",
|
||
});
|
||
button.addEventListener("click", async () => {
|
||
if (sessionRepairs.has(key)) return;
|
||
sessionRepairs.add(key);
|
||
button.disabled = true;
|
||
button.textContent = "Exporting…";
|
||
try {
|
||
const detail = await repo.repairSessionExport(run.id, step.sequence);
|
||
if (state.runDetail?.id === run.id) {
|
||
if (rt.refreshRunDetail) rt.refreshRunDetail(run.id);
|
||
else {
|
||
state.runDetail = detail;
|
||
renderContent();
|
||
}
|
||
}
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
renderContent();
|
||
} finally {
|
||
sessionRepairs.delete(key);
|
||
button.disabled = Boolean(running);
|
||
button.textContent = "Retry export only";
|
||
rt.views.dialogs.refreshStageAudit?.();
|
||
}
|
||
});
|
||
return button;
|
||
}
|
||
|
||
/**
|
||
* The run detail: a tab strip (Summary / Graph / Input / Output / Timeline) over
|
||
* the selected tab's body, wired from the pure helpers in runDetail.js. Summary
|
||
* is the default and carries the run's identity, key/value rows and diagnostic;
|
||
* the Graph tab mounts the shared workflow graph in run mode; Input/Output are
|
||
* one collapsed section per recorded field; the Timeline is one compact row per
|
||
* visit that opens the stage pane. Every server string is set with textContent,
|
||
* never innerHTML.
|
||
*/
|
||
function renderRunDetail(now = Date.now()) {
|
||
const d = state.runDetail;
|
||
const pane = h("div", { class: "detail run-detail" });
|
||
if (!d) {
|
||
pane.append(h("div", { class: "muted pad", text: "Select a run." }));
|
||
return pane;
|
||
}
|
||
// A run parked on a person surfaces its decision above the tabs, exactly where
|
||
// the Android run detail does, so opening the run is enough — no tab hunt.
|
||
const decision = pendingDecision(d);
|
||
if (decision) pane.append(renderDecisionCard(decision));
|
||
const status = runStateOf(d.status);
|
||
const kicker = h("div", { class: "run-kicker" });
|
||
kicker.append(h("span", { class: `chip chip-${status}`, text: runStatusLabel(d) }));
|
||
if (String(d.outcome ?? "").trim()) {
|
||
kicker.append(h("span", { class: "muted", text: `outcome ${d.outcome}` }));
|
||
}
|
||
if (d.executing && !d.cleanup_unconfirmed) kicker.append(h("span", { class: "muted", text: "executing" }));
|
||
pane.append(kicker);
|
||
pane.append(
|
||
h("h1", {
|
||
class: "run-detail-title",
|
||
id: "detailTitle",
|
||
tabindex: "-1",
|
||
text: runLabelFor(d),
|
||
}),
|
||
);
|
||
const actions = renderRunActions(d);
|
||
if (actions) pane.append(actions);
|
||
if (state.runTab === "graph") {
|
||
pane.append(renderRunGraphTab(d));
|
||
} else if (state.runTab === "input") {
|
||
pane.append(renderRunFieldTab(d.input, "input", EMPTY_INPUT_MESSAGE));
|
||
} else if (state.runTab === "output") {
|
||
pane.append(renderRunFieldTab(d.output, "output", EMPTY_OUTPUT_MESSAGE));
|
||
} else if (state.runTab === "steps") {
|
||
pane.append(renderRunTimelineTab(d));
|
||
} else {
|
||
pane.append(renderRunSummaryTab(d, now));
|
||
}
|
||
if (state.runStagePane) pane.append(renderStagePane(d));
|
||
if (state.decisionOpen && state.runDecision) pane.append(renderDecisionSheet(state.runDecision));
|
||
const confirm = renderConfirmDialog(d);
|
||
if (confirm) pane.append(confirm);
|
||
if (state.actionError) pane.append(renderActionFailedDialog());
|
||
return pane;
|
||
}
|
||
|
||
/**
|
||
* The Graph tab (R5): the run's own guidance note plus the shared workflow graph
|
||
* mounted in run mode, or the app's exact missing-graph sentence when the server
|
||
* sent no stages. The active stage pulses with its elapsed time while the run
|
||
* executes; clicking a stage opens the same recorded-visit pane as Timeline.
|
||
* The mount handle is tracked in `state.runGraph` so a re-render
|
||
* (or a tab/run change) always unmounts the previous wheel/pointer/resize
|
||
* listeners and the elapsed timer.
|
||
*/
|
||
function renderRunGraphTab(d) {
|
||
const wrap = h("div", { class: "run-tab-body run-graph" });
|
||
const stages = d.graph?.stages ?? [];
|
||
if (!stages.length) {
|
||
wrap.append(h("div", { class: "run-empty muted", text: RUN_GRAPH_MISSING }));
|
||
return wrap;
|
||
}
|
||
const host = h("div", { class: "graph-host" });
|
||
wrap.append(host);
|
||
state.runGraph = mountGraph(host, d.graph, {
|
||
runState: runGraphState(d),
|
||
expanded: state.runGraphExpanded,
|
||
onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)),
|
||
onExpandedChange: (value) => {
|
||
state.runGraphExpanded = value;
|
||
writeGraphExpanded(value);
|
||
},
|
||
});
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* The visit index the graph opens for a stage: its most recent recorded visit
|
||
* (`visits.size - 1`, never negative), exactly as RunGraphTab computes it.
|
||
*/
|
||
function latestVisitIndex(d, key) {
|
||
const visits = runTimeline(d.steps ?? []).visitsByStage.get(key) ?? [];
|
||
return Math.max(0, visits.length - 1);
|
||
}
|
||
|
||
/** Open the audit dialog for one visit: its turn files, session and definition. */
|
||
function openAuditFor(d, step, stageKey, visitIndex) {
|
||
if (!step) return;
|
||
const currentStep = () => state.runDetail?.id === d.id
|
||
? state.runDetail.steps?.find((entry) => entry.sequence === step.sequence) ?? step : step;
|
||
showStageAudit({
|
||
title: `${nodeLabel(stageKey)} audit`,
|
||
subtitle: `Visit ${visitIndex + 1} · ${runLabelFor(d)}`,
|
||
tabs: [
|
||
{ key: "input", label: "Input", body: () => auditArtifact(currentStep(), "input.md", EMPTY_INPUT_MESSAGE) },
|
||
{ key: "output", label: "Output", body: () => auditArtifact(currentStep(), "output.md", EMPTY_OUTPUT_MESSAGE) },
|
||
{ key: "memory", label: "Memory", body: () => auditArtifact(currentStep(), "memory.md", "No memory recorded for this visit.") },
|
||
{ key: "session", label: "Session", body: () => auditSession(currentStep()) },
|
||
{ key: "definition", label: "Definition", body: () => definitionDocument(
|
||
runDefinition(d), stageKey, (text) => rt.views.chat.renderMarkdown(text),
|
||
) },
|
||
],
|
||
revision: (tab) => {
|
||
const current = currentStep();
|
||
if (tab === "session") {
|
||
const capture = sessionCaptureState(current);
|
||
const complete = capture.artifact && capture.evidence?.status === "complete" && !capture.evidence.truncated;
|
||
const retryState = complete ? null : [sessionRepairs.has(`${d.id}:${step.sequence}`), current.agent_active, state.runDetail?.status, state.runDetail?.export_pending_sequence];
|
||
return JSON.stringify([capture.sessionId,capture.artifact,capture.evidence?.status,capture.evidence?.messages,capture.evidence?.truncated,capture.evidence?.diagnostic,capture.message,retryState]);
|
||
}
|
||
if (["input","output","memory"].includes(tab)) return JSON.stringify(systemArtifacts(current).find((entry)=>entry.name===`${tab}.md`) ?? null);
|
||
return `${d.pipeline_id}:${d.version}:${stageKey}`;
|
||
},
|
||
});
|
||
}
|
||
|
||
/**
|
||
* One turn file in the audit: the raw bytes and the rendered markdown, with a
|
||
* Rendered/Raw switch and a link to the file on the server. The file is fetched
|
||
* (not the step's field map), so the outcome section is visible exactly as the
|
||
* stage wrote it.
|
||
*/
|
||
function auditArtifact(step, name, emptyMessage) {
|
||
const artifact = systemArtifacts(step).find((entry) => entry.name === name);
|
||
const wrap = h("div", { class: "audit-doc" });
|
||
if (!artifact) {
|
||
wrap.append(h("div", { class: "muted", text: emptyMessage }));
|
||
return wrap;
|
||
}
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
if (!resolved) {
|
||
wrap.append(h("div", { class: "muted", text: ARTIFACT_SERVER_HINT }));
|
||
return wrap;
|
||
}
|
||
let text = "";
|
||
let mode = "rendered";
|
||
const bar = h("div", { class: "audit-doc-bar" });
|
||
const toggle = h("div", { class: "audit-doc-toggle", role: "group", "aria-label": "Document view" });
|
||
const out = h("div", { class: "audit-doc-body" });
|
||
const draw = () => {
|
||
toggle.replaceChildren(
|
||
...[
|
||
["rendered", "Rendered"],
|
||
["raw", "Raw"],
|
||
].map(([key, label]) =>
|
||
h("button", {
|
||
class: `audit-doc-mode${mode === key ? " active" : ""}`,
|
||
type: "button",
|
||
"aria-pressed": mode === key ? "true" : "false",
|
||
text: label,
|
||
onclick: () => {
|
||
mode = key;
|
||
draw();
|
||
},
|
||
}),
|
||
),
|
||
);
|
||
out.replaceChildren();
|
||
if (mode === "raw" || !looksLikeMarkdown(text)) {
|
||
out.append(h("pre", { class: "field-block" }, h("code", { text })));
|
||
return;
|
||
}
|
||
out.append(h("div", { class: "field-markdown" }, rt.views.chat.renderMarkdown(text)));
|
||
};
|
||
bar.append(
|
||
toggle,
|
||
h("a", {
|
||
class: "audit-doc-open",
|
||
...artifactBrowserLinkProps(resolved),
|
||
text: "Open raw file",
|
||
}),
|
||
);
|
||
wrap.append(bar, out);
|
||
out.append(h("div", { class: "muted", text: "Loading…" }));
|
||
fetch(resolved)
|
||
.then((response) => {
|
||
if (!response.ok) throw new Error(`The server answered ${response.status}.`);
|
||
return response.text();
|
||
})
|
||
.then((body) => {
|
||
text = body;
|
||
draw();
|
||
})
|
||
.catch((error) => {
|
||
out.replaceChildren(h("div", { class: "muted", text: describeError(error) }));
|
||
});
|
||
return wrap;
|
||
}
|
||
|
||
/** The exported session, rendered in place, with the raw file one click away. */
|
||
function auditSession(step) {
|
||
const capture = sessionCaptureState(step);
|
||
const legacy = !step?.session_export && !(step?.session_export_repairs?.length);
|
||
const artifact = capture.artifact ?? (legacy ? systemArtifacts(step).find((entry) => entry.name === "session.html") : null);
|
||
if (!artifact) {
|
||
const body = h("div", {
|
||
class: "audit-session-state muted",
|
||
"data-session-id": capture.sessionId,
|
||
});
|
||
body.append(h("p",{text:capture.message}));
|
||
const retry=sessionExportRetry(step);if(retry)body.append(retry);
|
||
return body;
|
||
}
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
const wrap = h("div", { class: "audit-session" });
|
||
if (capture.sessionId) wrap.append(h("p", {class:"audit-session-state muted",text:`Recorded session: ${capture.sessionId}`}));
|
||
if (capture.evidence && (capture.evidence.status && capture.evidence.status!=="complete" || capture.evidence.truncated)) {
|
||
wrap.append(h("p",{class:"audit-session-state muted",text:`This export is ${capture.evidence.status || "partial"}; full session evidence is not available.`}));
|
||
const retry=sessionExportRetry(step);if(retry)wrap.append(retry);
|
||
}
|
||
if (!resolved) {
|
||
wrap.append(h("div", { class: "muted", text: ARTIFACT_SERVER_HINT }));
|
||
return wrap;
|
||
}
|
||
wrap.append(
|
||
h(
|
||
"div",
|
||
{ class: "audit-doc-bar" },
|
||
h("a", {
|
||
class: "audit-doc-open",
|
||
...artifactBrowserLinkProps(resolved),
|
||
text: "Open raw file",
|
||
}),
|
||
),
|
||
);
|
||
wrap.append(
|
||
h("iframe", {
|
||
class: "audit-session-frame",
|
||
src: resolved,
|
||
title: `Session export · ${step.stage}`,
|
||
sandbox: "",
|
||
}),
|
||
);
|
||
return wrap;
|
||
}
|
||
|
||
/** Load authored source for exactly the run's recorded version. */
|
||
function runDefinition(d) {
|
||
// Never fall back to latest: a run must show the version it executed.
|
||
if (!(Number(d.pipeline_id) > 0 && Number(d.version) > 0)) {
|
||
return Promise.reject(new Error("The run did not include its pipeline version."));
|
||
}
|
||
return repo.getPipeline(d.pipeline_id, d.version);
|
||
}
|
||
|
||
/** The Summary tab: identity, key/value rows, diagnostic and the sections. */
|
||
function renderRunSummaryTab(d, now) {
|
||
const wrap = h("div", { class: "run-tab-body" });
|
||
wrap.append(renderRunTitleRow(d));
|
||
wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) }));
|
||
const origin = scheduledRunLabel(d);
|
||
if (origin) wrap.append(h("p", { class: "run-schedule-origin muted", text: origin }));
|
||
|
||
const rows = h("div", { class: "kv" });
|
||
for (const row of summaryRows(d, now)) {
|
||
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 if (row.kind === "pipeline") rows.append(renderPipelineRow(row));
|
||
else rows.append(renderKvRow(row));
|
||
}
|
||
wrap.append(rows);
|
||
|
||
// Stage-produced artifacts first: the turn's own input/memory/output/session
|
||
// files are audit evidence and live behind Audit & debug instead.
|
||
wrap.append(
|
||
renderCollapsible(
|
||
"summary-artifacts",
|
||
artifactsHeader(d.steps ?? [], isExecuting(d)),
|
||
() => renderArtifactGallery(d.steps ?? []),
|
||
{ actions: artifactViewToggle() },
|
||
),
|
||
);
|
||
|
||
// The run-level Changes (parity R4): the observed final-state workspace diff.
|
||
// Only a succeeded run has a settled final state to present; a failed run keeps
|
||
// its evidence in each visit's own capture.
|
||
if (showRunChangesSummary(d.status)) {
|
||
const changes = runChanges(d.steps ?? []);
|
||
wrap.append(
|
||
renderCollapsible("summary-changes", runChangesHeader(changes), () => renderChangesBody(changes)),
|
||
);
|
||
}
|
||
|
||
// Input and Output are sections of the summary now, not tabs.
|
||
wrap.append(
|
||
renderCollapsible("summary-input", "Input", () =>
|
||
renderRunFieldBody(d.input, "input", EMPTY_INPUT_MESSAGE),
|
||
),
|
||
);
|
||
wrap.append(
|
||
renderCollapsible("summary-output", "Output", () =>
|
||
renderRunFieldBody(d.output, "output", EMPTY_OUTPUT_MESSAGE),
|
||
),
|
||
);
|
||
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* The Pipeline row: the same "id N · vM" text, but a button that opens that
|
||
* pipeline version. A run is only legible next to the definition it executed, so
|
||
* this is the shortest path from the evidence to the pipeline.
|
||
*/
|
||
function renderPipelineRow(row) {
|
||
const wrap = h("div", { class: "kv-row" });
|
||
wrap.append(h("span", { class: "kv-key", text: row.key }));
|
||
const link = h("button", {
|
||
class: "kv-val kv-pipeline-link",
|
||
type: "button",
|
||
title: `Open pipeline ${row.pipelineId}`,
|
||
"aria-label": `Open pipeline ${row.pipelineName || row.pipelineId}, version ${row.version}`,
|
||
});
|
||
if (row.pipelineName) {
|
||
link.append(
|
||
h("span", { class: "kv-pipeline-name", text: row.pipelineName }),
|
||
h("span", { class: "kv-pipeline-ident", text: row.value }),
|
||
);
|
||
} else {
|
||
link.textContent = row.value;
|
||
}
|
||
link.addEventListener("click", async () => {
|
||
state.view = "pipelines";
|
||
state.selectedRunId = null;
|
||
await selectPipeline({ id: row.pipelineId, version: row.version });
|
||
});
|
||
wrap.append(link);
|
||
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. */
|
||
/**
|
||
* One recorded field value: a markdown body (the new stage turns) is rendered as
|
||
* markdown; anything else stays an honest monospace block.
|
||
*/
|
||
function renderFieldValue(value) {
|
||
const text = typeof value === "string" ? value : String(value ?? "");
|
||
if (looksLikeMarkdown(text)) {
|
||
return h("div", { class: "field-markdown" }, rt.views.chat.renderMarkdown(text));
|
||
}
|
||
return h("pre", { class: "field-block" }, h("code", { text }));
|
||
}
|
||
|
||
function renderStageField(field) {
|
||
if (field.block) {
|
||
// A turn's input/output is one markdown document: render it as the document,
|
||
// not as a code card whose label repeats the section title.
|
||
if (looksLikeMarkdown(field.value)) {
|
||
return h("div", { class: "stage-field-markdown" }, renderFieldValue(field.value));
|
||
}
|
||
return h(
|
||
"div",
|
||
{ class: "codeblock" },
|
||
h("div", { class: "codeblock-label", text: field.label }),
|
||
renderFieldValue(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) {
|
||
return h("div", { class: "run-tab-body" }, renderRunFieldBody(map, keyPrefix, emptyMessage));
|
||
}
|
||
|
||
/** The input/output body itself, shared by the old tab and the summary sections. */
|
||
function renderRunFieldBody(map, keyPrefix, emptyMessage) {
|
||
const wrap = h("div", { class: "run-field-body" });
|
||
const sections = fieldSections(map, keyPrefix);
|
||
if (!sections.length) {
|
||
wrap.append(h("div", { class: "run-empty muted", text: emptyMessage }));
|
||
return wrap;
|
||
}
|
||
// A turn's output is one markdown body: render it as the result, not as a
|
||
// collapsed field named "markdown". Legacy field maps keep their sections.
|
||
const single = sections.length === 1 ? sections[0] : null;
|
||
if (single && single.key.toLowerCase() === "markdown") {
|
||
wrap.append(h("div", { class: "run-markdown-body" }, renderFieldValue(single.value)));
|
||
return wrap;
|
||
}
|
||
for (const section of sections) {
|
||
const key = `${keyPrefix}-${section.key}`;
|
||
wrap.append(
|
||
renderCollapsible(key, section.title, () => renderFieldValue(section.value)),
|
||
);
|
||
}
|
||
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, { actions = null } = {}) {
|
||
const expanded = state.runSections.has(key);
|
||
const wrap = h("div", { class: "collapsible" });
|
||
const head = h("div", { class: "section-row" });
|
||
head.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 (actions) head.append(actions);
|
||
wrap.append(head);
|
||
if (expanded) wrap.append(h("div", { class: "section-body" }, bodyFn()));
|
||
return wrap;
|
||
}
|
||
|
||
// --- Changes (parity R4) ---------------------------------------------------
|
||
|
||
/**
|
||
* The Changes section body: the file-list summary line, the honest capture note
|
||
* (when the capture was not complete) and then either the no-change detail or
|
||
* one clickable row per changed file in first-seen order. Every server string is
|
||
* set as text, never as markup.
|
||
*/
|
||
function renderChangesBody(changes) {
|
||
const body = h("div", { class: "changes" });
|
||
body.append(h("div", { class: "changes-summary", text: changesListSummary(changes) }));
|
||
const note = runChangesNote(changes);
|
||
if (note.trim() !== "") body.append(h("div", { class: "changes-note muted", text: note }));
|
||
if (changes.files.length === 0) {
|
||
body.append(h("div", { class: "changes-empty muted", text: noChangeDetail(changes) }));
|
||
return body;
|
||
}
|
||
const list = h("div", { class: "changes-list" });
|
||
changes.files.forEach((entry, index) => list.append(renderChangeRow(entry, index, changes.files)));
|
||
body.append(list);
|
||
return body;
|
||
}
|
||
|
||
/**
|
||
* One changed-file row: the kind word in its hue, the path in monospace, the
|
||
* `+N -M` stat and the `changed by …` meta line. Clicking (or Enter/Space) opens
|
||
* the diff viewer on this file, whose position there confirms which row it is.
|
||
*/
|
||
function renderChangeRow(entry, index, files) {
|
||
const row = h("div", {
|
||
class: "change-row",
|
||
role: "button",
|
||
tabindex: "0",
|
||
"data-change-index": String(index),
|
||
"aria-label": `Open ${entry.path}`,
|
||
});
|
||
const open = () => openChangeViewer(files, index, row);
|
||
row.addEventListener("click", open);
|
||
row.addEventListener("keydown", (event) => {
|
||
if (event.key === "Enter" || event.key === " ") {
|
||
event.preventDefault();
|
||
open();
|
||
}
|
||
});
|
||
row.append(h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindLabel(entry.kind) }));
|
||
const main = h("div", { class: "change-main" });
|
||
main.append(h("div", { class: "change-path monospace", text: entry.path }));
|
||
main.append(h("div", { class: "change-meta muted", text: changeRowMeta(entry) }));
|
||
row.append(main);
|
||
const stat = h("div", { class: "change-stat" });
|
||
if (entry.added > 0) stat.append(h("span", { class: "stat-add", text: `+${entry.added}` }));
|
||
if (entry.removed > 0) stat.append(h("span", { class: "stat-del", text: `-${entry.removed}` }));
|
||
row.append(stat);
|
||
return row;
|
||
}
|
||
|
||
|
||
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, d.steps ?? []);
|
||
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: "ghost back-button stage-pane-back",
|
||
type: "button",
|
||
"aria-label": "Back to run",
|
||
title: "Back to run",
|
||
onclick: closeStagePane,
|
||
}, backChevronIcon()),
|
||
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, d.steps ?? []));
|
||
if (step) {
|
||
body.append(
|
||
h(
|
||
"div",
|
||
{ class: "stage-pane-audit" },
|
||
h("button", {
|
||
class: "ghost audit-open",
|
||
type: "button",
|
||
text: "Audit & debug",
|
||
title: "Input, output, memory, session and definition",
|
||
onclick: () => openAuditFor(d, step, stageKey, visitIndex),
|
||
}),
|
||
),
|
||
);
|
||
}
|
||
overlay.append(h("div", { class: "stage-pane-sheet" }, bar, body));
|
||
modal.stage("stage-pane", overlay, {
|
||
onClose: () => closeStagePane(),
|
||
fallbackSelectors: ["#detailTitle", "#pane-main"],
|
||
// A pane opened from the Timeline returns to its row; one opened from the
|
||
// Graph returns to the stage node (there is no timeline row then).
|
||
restore: () => {
|
||
const row = [...document.querySelectorAll(".timeline-row")].find(
|
||
(node) =>
|
||
node.dataset.stageKey === stageKey && node.dataset.visitIndex === String(visitIndex),
|
||
);
|
||
return (
|
||
row ??
|
||
[...document.querySelectorAll(".graph-node")].find((node) => node.dataset.key === stageKey) ??
|
||
null
|
||
);
|
||
},
|
||
});
|
||
return overlay;
|
||
}
|
||
|
||
/** One stage-pane section, using the pane's own expansion state. */
|
||
function renderStageSection(spec, step, allSteps = null) {
|
||
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, allSteps));
|
||
else if (spec.changes && step) body.append(renderChangesBody(runChanges([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;
|
||
}
|
||
|
||
/** Open references in the browser; preview is an explicit gallery action. */
|
||
function renderVerdictLink(text, artifact, step) {
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
if (!resolved) return h("span", { class: "verdict-link disabled", text });
|
||
return h("a", { class: "verdict-link", ...artifactBrowserLinkProps(resolved), text });
|
||
}
|
||
|
||
/** 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", () => openArtifactInBrowser(resolved));
|
||
return chip;
|
||
}
|
||
|
||
/** Open the stage pane for one visit of a stage; the controller moves focus in. */
|
||
function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) {
|
||
state.runStagePane = { stageKey, visitIndex };
|
||
state.runStageSections = new Set();
|
||
if (updateRoute && state.selectedRunId) {
|
||
pushRoute({
|
||
kind: "runStage",
|
||
id: state.selectedRunId,
|
||
stageKey,
|
||
visit: Number.isSafeInteger(visitIndex) && visitIndex >= 0 ? visitIndex : null,
|
||
});
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Close the stage pane; the controller returns focus to the row or graph node. */
|
||
function closeStagePane({ updateRoute = true } = {}) {
|
||
if (!state.runStagePane) return;
|
||
state.runStagePane = null;
|
||
state.runStageSections = new Set();
|
||
if (updateRoute && state.selectedRunId) {
|
||
pushRoute({ kind: "run", id: state.selectedRunId });
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
// --- Run-level operator actions (R11–R14) ----------------------------------
|
||
|
||
|
||
/**
|
||
* The decision card (R11): a prominent "Waiting for your decision" banner with
|
||
* the stage/run identity and a deliberate Decide action. Only rendered when the
|
||
* loaded run is genuinely waiting on a person.
|
||
*/
|
||
function renderDecisionCard(decision) {
|
||
const card = h("div", { class: "decision-card" });
|
||
card.append(h("span", { class: "decision-card-icon", "aria-hidden": "true", text: "\u270B" }));
|
||
const text = h("div", { class: "decision-card-text" });
|
||
text.append(h("div", { class: "decision-card-title", text: DECISION_CARD_TITLE }));
|
||
text.append(h("div", { class: "decision-card-meta muted", text: decisionCardMeta(decision) }));
|
||
card.append(text);
|
||
card.append(
|
||
h("button", {
|
||
class: "decision-open",
|
||
type: "button",
|
||
text: DECISION_ACTION,
|
||
onclick: () => openDecisionSheet(decision),
|
||
}),
|
||
);
|
||
return card;
|
||
}
|
||
|
||
/** Run controls plus an independent schedule seeded from the original RunInfo. */
|
||
function renderRunActions(d) {
|
||
const buttons = [];
|
||
let status = null;
|
||
const prompt = originalRunPrompt(d);
|
||
if (prompt !== undefined) {
|
||
status = h("span", {
|
||
class: "run-action-status",
|
||
role: "status",
|
||
"aria-live": "polite",
|
||
"aria-atomic": "true",
|
||
hidden: true,
|
||
});
|
||
const report = (message, tone) => {
|
||
status.textContent = message;
|
||
status.dataset.state = tone;
|
||
status.hidden = false;
|
||
};
|
||
const copy = h("button", {
|
||
class: "run-action copy-prompt",
|
||
type: "button",
|
||
text: "Copy prompt",
|
||
"aria-label": "Copy prompt",
|
||
});
|
||
copy.addEventListener("click", async () => {
|
||
const clipboard = typeof navigator === "undefined" ? null : navigator.clipboard;
|
||
if (typeof clipboard?.writeText !== "function") {
|
||
report("Clipboard is unavailable in this browser.", "error");
|
||
return;
|
||
}
|
||
copy.disabled = true;
|
||
report("Copying prompt…", "pending");
|
||
try {
|
||
await clipboard.writeText(prompt);
|
||
report("Prompt copied to clipboard.", "success");
|
||
} catch {
|
||
report("Could not copy prompt to clipboard.", "error");
|
||
} finally {
|
||
copy.disabled = false;
|
||
}
|
||
});
|
||
buttons.push(copy);
|
||
}
|
||
if (rt.views?.schedules && Number(d.pipeline_id) > 0 && Number(d.version) > 0) {
|
||
buttons.push(h("button", {
|
||
class: "run-action schedule-run",
|
||
type: "button",
|
||
text: "Schedule this run",
|
||
title: "Save this run's prompt and options with an independent timer; does not rerun it now",
|
||
onclick: async (event) => {
|
||
const trigger = event.currentTarget;
|
||
trigger.disabled = true;
|
||
try {
|
||
const pipeline = await runDefinition(d);
|
||
if (state.runDetail?.id === d.id) rt.views.schedules.openScheduleEditor({ pipeline, run: d, trigger });
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
renderContent();
|
||
} finally { trigger.disabled = false; }
|
||
},
|
||
}));
|
||
}
|
||
if (canCancel(d)) {
|
||
buttons.push(
|
||
h("button", {
|
||
class: "run-action cancel-run",
|
||
type: "button",
|
||
text: "Cancel run",
|
||
onclick: () => openConfirm({ kind: "cancel", runId: d.id }),
|
||
}),
|
||
);
|
||
}
|
||
if (canRetry(d)) {
|
||
buttons.push(
|
||
h("button", {
|
||
class: "run-action retry-run",
|
||
type: "button",
|
||
text: "Retry",
|
||
onclick: () => openConfirm({ kind: "retry", runId: d.id }),
|
||
}),
|
||
);
|
||
}
|
||
if (status) buttons.push(status);
|
||
if (!buttons.length) return null;
|
||
return h("div", { class: "run-actions" }, ...buttons);
|
||
}
|
||
|
||
function renderRunTitleRow(d) {
|
||
const row = h("div", { class: "run-title-row" });
|
||
if (state.renameValue == null) {
|
||
row.append(
|
||
h("button", {
|
||
class: "ghost rename-open",
|
||
type: "button",
|
||
text: RENAME_ACTION,
|
||
onclick: () => {
|
||
state.renameValue = String(d.title ?? "");
|
||
renderContent();
|
||
},
|
||
}),
|
||
);
|
||
return row;
|
||
}
|
||
const field = h("div", { class: "rename-field" });
|
||
field.append(
|
||
h("input", {
|
||
class: "rename-input",
|
||
type: "text",
|
||
value: state.renameValue,
|
||
"aria-label": RENAME_FIELD_LABEL,
|
||
oninput: (event) => {
|
||
state.renameValue = event.target.value;
|
||
},
|
||
}),
|
||
);
|
||
field.append(
|
||
h("button", {
|
||
class: "rename-save",
|
||
type: "button",
|
||
text: RENAME_SAVE,
|
||
onclick: () => saveRunTitle(d.id),
|
||
}),
|
||
);
|
||
field.append(
|
||
h("button", {
|
||
class: "ghost rename-cancel",
|
||
type: "button",
|
||
text: RENAME_CANCEL,
|
||
onclick: () => {
|
||
state.renameValue = null;
|
||
renderContent();
|
||
},
|
||
}),
|
||
);
|
||
row.append(field);
|
||
return row;
|
||
}
|
||
|
||
/**
|
||
* Rename the run: send `set_run_title`, then update the run detail and the runs
|
||
* list row. A refusal (for example a blank title) keeps the field open and shows
|
||
* the server's exact reason through the shared Action-failed dialog.
|
||
*/
|
||
async function saveRunTitle(id) {
|
||
if (state.renameBusy) return;
|
||
state.renameBusy = true;
|
||
try {
|
||
const detail = await repo.setRunTitle(id, String(state.renameValue ?? ""));
|
||
state.renameValue = null;
|
||
applyRunTitle(id, detail);
|
||
await selectRun(id, { silent: true });
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
renderContent();
|
||
} finally {
|
||
state.renameBusy = false;
|
||
}
|
||
}
|
||
|
||
/** Apply a renamed run to the loaded detail and the runs-list row. */
|
||
function applyRunTitle(id, detail) {
|
||
if (state.runDetail && state.runDetail.id === id && detail) state.runDetail = detail;
|
||
const title = String(detail?.title ?? "");
|
||
state.runs = state.runs.map((run) => (run.id === id ? { ...run, title } : run));
|
||
}
|
||
|
||
/** Whether the configured server URL can resolve a server-relative artifact. */
|
||
function artifactsResolvable() {
|
||
return resolveArtifactUrl(state.url, "/artifacts/0/0/probe") != null;
|
||
}
|
||
|
||
/**
|
||
* The run-level gallery: one header per (stage, visit) and one grid of tiles per
|
||
* visit, in the gallery order (stages first-appearance, visits by sequence). A
|
||
* run with no artifacts shows the header (which already says why) and nothing
|
||
* else, so the section is never blank.
|
||
*/
|
||
/** The gallery/list switch in the artifacts section header. */
|
||
function artifactViewToggle() {
|
||
const group = h("div", {
|
||
class: "view-toggle",
|
||
role: "group",
|
||
"aria-label": "Artifact view",
|
||
});
|
||
for (const [key, label] of [
|
||
["gallery", "Gallery"],
|
||
["list", "List"],
|
||
]) {
|
||
group.append(
|
||
h("button", {
|
||
class: `view-toggle-button${state.artifactView === key ? " active" : ""}`,
|
||
type: "button",
|
||
"aria-pressed": state.artifactView === key ? "true" : "false",
|
||
text: label,
|
||
onclick: () => {
|
||
state.artifactView = key;
|
||
writeArtifactView(key);
|
||
renderContent();
|
||
},
|
||
}),
|
||
);
|
||
}
|
||
return group;
|
||
}
|
||
|
||
function renderArtifactGallery(steps) {
|
||
const wrap = h("div", { class: "artifact-gallery" });
|
||
const groups = artifactGroups(steps);
|
||
if (!groups.length) {
|
||
wrap.append(h("div", { class: "muted artifact-hint", text: "No stage artifacts recorded." }));
|
||
return wrap;
|
||
}
|
||
if (!artifactsResolvable()) {
|
||
wrap.append(h("div", { class: "muted artifact-hint", text: ARTIFACT_SERVER_HINT }));
|
||
}
|
||
if (state.artifactView === "list") {
|
||
wrap.append(renderArtifactList(groups));
|
||
return wrap;
|
||
}
|
||
const viewable = pagedArtifacts(groups);
|
||
const viewerIndexOf = viewerIndexByUrl(groups);
|
||
for (const group of groups) {
|
||
wrap.append(
|
||
h("div", { class: "artifact-group-head", text: `${group.stageKey} · visit ${group.visit}` }),
|
||
renderArtifactGrid(group.artifacts, viewable, viewerIndexOf),
|
||
);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
/** The list form of the run's artifacts: one full-name row per file. */
|
||
function renderArtifactList(groups) {
|
||
const list = h("div", { class: "artifact-list" });
|
||
const viewable = pagedArtifacts(groups);
|
||
const viewerIndexOf = viewerIndexByUrl(groups);
|
||
for (const group of groups) {
|
||
list.append(
|
||
h("div", { class: "artifact-group-head", text: `${group.stageKey} · visit ${group.visit}` }),
|
||
);
|
||
for (const artifact of group.artifacts) {
|
||
list.append(renderArtifactListRow(artifact, viewable, viewerIndexOf));
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/** One artifact list row: kind, full name, size, and hover-only actions. */
|
||
function renderArtifactListRow(artifact, viewable, viewerIndexOf) {
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
const kind = artifactKind(artifact.content_type, artifact.name);
|
||
const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video;
|
||
const opensViewer = isViewerArtifact(artifact.content_type, artifact.name);
|
||
const name = artifact.name || "(unnamed artifact)";
|
||
const wrap = h("div", { class: "artifact-list-row" });
|
||
const open = h("button", {
|
||
class: "artifact-list-open",
|
||
type: "button",
|
||
"aria-label": `Open ${name}`,
|
||
title: name,
|
||
});
|
||
open.append(h("span", { class: "artifact-kind", text: artifactKindLabel(kind) }));
|
||
open.append(h("span", { class: "artifact-list-name", text: name }));
|
||
open.append(h("span", { class: "artifact-size", text: humanBytes(artifact.size_bytes) }));
|
||
const at = viewerIndexOf.get(artifact.url);
|
||
const previewImage = kind === ArtifactKind.Image && at != null;
|
||
open.addEventListener("click", () => previewImage
|
||
? openArtifactViewer(viewable, at, open) : openArtifactInBrowser(resolved));
|
||
wrap.append(open, renderTileActions(resolved, media, opensViewer && at != null
|
||
? (trigger) => openArtifactViewer(viewable, at, trigger) : null, name, previewImage, artifact));
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* The per-visit artifacts section shown inside one step: the summary line, the
|
||
* capture notes, the no-server-URL hint and a headerless grid of that visit's
|
||
* tiles (matching the Android ArtifactsSection). Its viewer pages only through
|
||
* that visit's viewable artifacts (media and markdown), exactly as the Android
|
||
* section does.
|
||
*/
|
||
function renderVisitArtifacts(step, allSteps = null) {
|
||
const wrap = h("div", { class: "artifacts" });
|
||
const artifacts = visitArtifacts(step, allSteps ?? [step]);
|
||
// The section title already carries the count, so the body repeats it only when
|
||
// there is nothing to show and the reason itself is the useful part.
|
||
if (artifacts.length === 0) {
|
||
wrap.append(h("div", { class: "artifacts-summary", text: artifactsSummary(step, 0) }));
|
||
}
|
||
for (const note of artifactCaptureNotes(step)) {
|
||
wrap.append(h("div", { class: "artifacts-note muted", text: note }));
|
||
}
|
||
if (artifacts.length) {
|
||
if (!artifactsResolvable()) {
|
||
wrap.append(h("div", { class: "muted artifact-hint", text: ARTIFACT_SERVER_HINT }));
|
||
}
|
||
const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts };
|
||
wrap.append(
|
||
renderArtifactGrid(artifacts, pagedArtifacts([group]), viewerIndexByUrl([group])),
|
||
);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
/** One visit's tiles in a CSS grid. */
|
||
function renderArtifactGrid(artifacts, viewable, viewerIndexOf) {
|
||
const grid = h("div", { class: "artifact-grid" });
|
||
for (const artifact of artifacts) {
|
||
grid.append(renderArtifactTile(artifact, viewable, viewerIndexOf));
|
||
}
|
||
return grid;
|
||
}
|
||
|
||
/**
|
||
* One gallery tile: an image thumbnail, a video poster with a play marker (never
|
||
* a <video> element or autoplay), or a kind/name/size label. Markdown and text
|
||
* documents get a paper glyph and open in the viewer like media. Every server
|
||
* string is set as text, never as markup.
|
||
*/
|
||
function renderArtifactTile(artifact, viewable, viewerIndexOf) {
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
const kind = artifactKind(artifact.content_type, artifact.name);
|
||
const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video;
|
||
const opensViewer = isViewerArtifact(artifact.content_type, artifact.name);
|
||
const name = artifact.name || "(unnamed artifact)";
|
||
// The tile is the native control (M5): Enter/Space activate it for free, and
|
||
// the Copy link / Share buttons are siblings in the wrapper, never children.
|
||
const wrap = h("div", { class: "artifact-tile-wrap" });
|
||
const tile = h("button", {
|
||
class: "artifact-tile clickable",
|
||
type: "button",
|
||
"aria-label": `Open ${name}`,
|
||
"data-artifact-name": artifact.name ?? "",
|
||
"data-artifact-kind": kind,
|
||
"data-artifact-url": artifact.url ?? "",
|
||
title: name,
|
||
});
|
||
const openViewer = (trigger = tile) => {
|
||
const at = viewerIndexOf.get(artifact.url);
|
||
if (at != null) openArtifactViewer(viewable, at, trigger);
|
||
};
|
||
const openTab = () => {
|
||
if (resolved) openArtifactInBrowser(resolved);
|
||
};
|
||
if (kind === ArtifactKind.Image) {
|
||
const img = h("img", { class: "artifact-thumb", alt: name, loading: "lazy" });
|
||
if (resolved) img.src = resolved;
|
||
tile.append(img);
|
||
tile.addEventListener("click", () => openViewer(tile));
|
||
} else if (kind === ArtifactKind.Video) {
|
||
tile.append(
|
||
h(
|
||
"div",
|
||
{ class: "artifact-poster" },
|
||
h("span", { class: "artifact-play", "aria-hidden": "true", text: "▶" }),
|
||
),
|
||
);
|
||
tile.append(h("div", { class: "artifact-name", text: name }));
|
||
tile.addEventListener("click", openTab);
|
||
} else {
|
||
if (opensViewer) {
|
||
tile.classList.add("artifact-document-tile");
|
||
tile.append(h("span", { class: "artifact-doc-glyph", "aria-hidden": "true" }));
|
||
}
|
||
tile.append(
|
||
h("div", { class: "artifact-kind", text: artifactKindLabel(kind) }),
|
||
h("div", { class: "artifact-name", text: name }),
|
||
h("div", { class: "artifact-size", text: humanBytes(artifact.size_bytes) }),
|
||
);
|
||
tile.addEventListener("click", openTab);
|
||
}
|
||
wrap.append(tile, renderTileActions(resolved, media, opensViewer ? openViewer : null, name, kind === ArtifactKind.Image, artifact));
|
||
return wrap;
|
||
}
|
||
|
||
/** The compact per-tile actions: icon-only link/share, shown on hover or focus. */
|
||
function renderTileActions(resolved, media, preview = null, name = "artifact", previewImage = false, artifact = null) {
|
||
const actions = h("div", { class: "artifact-actions" });
|
||
const stop = (fn) => (event) => {
|
||
event.stopPropagation();
|
||
fn(event.currentTarget);
|
||
};
|
||
if (previewImage) {
|
||
actions.append(artifactAction("external", `Open in browser: ${name}`, !resolved, stop(() => openArtifactInBrowser(resolved))));
|
||
} else if (preview) {
|
||
actions.append(artifactAction("preview", `Preview in app: ${name}`, !resolved, stop(preview)));
|
||
}
|
||
if (!media) {
|
||
actions.append(
|
||
artifactAction("link", "Copy link", !resolved || !canCopyLink(), stop(() => copyArtifactLink(resolved))),
|
||
);
|
||
}
|
||
actions.append(
|
||
artifactAction("share", "Share", !resolved || !canShare(), stop((trigger) => shareArtifact(resolved, artifact, trigger))),
|
||
);
|
||
if (!canShare()) actions.lastElementChild.title = "File sharing is not supported in this browser";
|
||
return actions;
|
||
}
|
||
|
||
const ARTIFACT_SVG_NS = "http://www.w3.org/2000/svg";
|
||
|
||
/** One icon-only artifact action (24px target, accessible name, hover-visible). */
|
||
function artifactAction(kind, label, disabled, onclick) {
|
||
const button = h("button", {
|
||
class: "artifact-action",
|
||
type: "button",
|
||
"aria-label": label,
|
||
title: label,
|
||
disabled,
|
||
onclick,
|
||
});
|
||
const svg = document.createElementNS(ARTIFACT_SVG_NS, "svg");
|
||
svg.setAttribute("viewBox", "0 0 24 24");
|
||
svg.setAttribute("aria-hidden", "true");
|
||
svg.setAttribute("focusable", "false");
|
||
const path = document.createElementNS(ARTIFACT_SVG_NS, "path");
|
||
path.setAttribute("d", kind === "external"
|
||
? "M14 3h7v7M21 3 10 14M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5"
|
||
: kind === "preview"
|
||
? "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12ZM15 12a3 3 0 1 1-6 0a3 3 0 0 1 6 0Z"
|
||
: kind === "link"
|
||
? "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"
|
||
: "M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13");
|
||
path.setAttribute("fill", "none");
|
||
path.setAttribute("stroke", "currentColor");
|
||
path.setAttribute("stroke-width", "2");
|
||
path.setAttribute("stroke-linecap", "round");
|
||
path.setAttribute("stroke-linejoin", "round");
|
||
svg.append(path);
|
||
button.append(svg);
|
||
return button;
|
||
}
|
||
|
||
/**
|
||
* The step's session export: a link opening the read-only session.html in a new
|
||
* tab, or the plain notice when the visit exported nothing (parity R9).
|
||
*/
|
||
function renderSessionExport(step) {
|
||
const file = sessionExportArtifact(step);
|
||
const wrap = h("div", { class: "session-export" });
|
||
const evidence = effectiveSessionExport(step);
|
||
const complete = evidence?.status === "complete" && evidence.messages>0 && evidence.html_bytes>0 && file && !evidence.truncated && !evidence.diagnostic;
|
||
const recovery = step?.session_export_recovery;
|
||
if (recovery && !complete) wrap.append(h("div", { class: "muted", text: `Automatic export recovery: ${recovery.status} · ${recovery.attempts}/3 attempts. ${recovery.diagnostic || ""}` }));
|
||
for (const repair of step?.session_export_repairs || []) {
|
||
const row = h("div", { class: "session-export-repair" });
|
||
row.append(h("span", { text: `Repair: ${repair.status || "partial"} · ${repair.messages || 0} messages. ${repair.diagnostic || ""}` }));
|
||
const repaired = sessionExportArtifact({ ...step, session_export: repair, session_export_repairs: [] });
|
||
const repairedHref = repaired && resolvedArtifactUrl(repaired, state.url);
|
||
if (repairedHref) row.append(h("a", { ...artifactBrowserLinkProps(repairedHref), text: "Open repaired export" }));
|
||
wrap.append(row);
|
||
}
|
||
const incomplete = evidence && (evidence.status && evidence.status !== "complete" || !evidence.messages || evidence.truncated || evidence.diagnostic);
|
||
if (incomplete) {
|
||
wrap.append(h("span", { class: "muted", text: `Session recorded, but export ${evidence.status || (!evidence.messages ? "empty" : "partial")}. Full session evidence was not captured.${evidence.diagnostic ? ` ${evidence.diagnostic}` : ""}` }));
|
||
}
|
||
if (!file) {
|
||
wrap.append(h("span", { class: "muted", text: sessionCaptureState(step).message }));
|
||
return wrap;
|
||
}
|
||
const href = resolvedArtifactUrl(file, state.url);
|
||
if (href) {
|
||
wrap.append(
|
||
h("a", {
|
||
class: "session-link",
|
||
...artifactBrowserLinkProps(href),
|
||
text: `Open ${file.name || "session.html"}`,
|
||
}),
|
||
);
|
||
} else {
|
||
wrap.append(
|
||
h("span", { class: "muted", text: "Set the server URL in Settings to open the session." }),
|
||
);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
return {
|
||
renderRunDetail,
|
||
renderRunGraphTab,
|
||
renderRunSummaryTab,
|
||
renderStagePane,
|
||
openStagePane,
|
||
closeStagePane,
|
||
renderArtifactGallery,
|
||
renderVisitArtifacts,
|
||
renderSessionExport,
|
||
latestVisitIndex,
|
||
};
|
||
}
|