Files
pipelines/web/src/app.js
T
alan 4be740b461 Merge branch 'main' into web-artifacts
Combine the R8/R9 artifacts gallery, viewer and session link with main's
pipelines/runs/templates work. app.js: keep both import blocks. ui-smoke.mjs:
the artifacts step now navigates to Runs and selects run 430 through the
post-main run-row markup (meta[data-run-id=430]) instead of the retired
'.list button.row #430' spike row.

Checks: node --check on every touched file; node --test test/ 108 pass;
live ui-smoke against ws://127.0.0.1:8080/connect passes (run 430: 18 tiles,
viewer '1 of 10 · image/png', session link .../artifacts/430/8/session.html).
captures/ stays untracked.
2026-10-19 03:05:58 +01:00

1675 lines
51 KiB
JavaScript

// Spike web UI: pipeline list + run detail over the live WebSocket protocol.
// Deliberately small and DOM-only (no framework, no build step). Every value
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
ArtifactKind,
artifactCaptureNotes,
artifactGroups,
artifactKind,
artifactKindLabel,
artifactsHeader,
artifactsSummary,
artifactViewerPositionLabel,
displayVisit,
humanBytes,
pagedArtifacts,
pagedIndex,
presentedArtifacts,
resolvedArtifactUrl,
sessionExportArtifact,
viewerIndexByUrl,
} from "./artifacts.js";
import {
PIPELINE_SORTS,
PIPELINE_DETAIL_TABS,
RUN_PRESENCES,
RUN_STATUS_FILTERS,
EMPTY_PIPELINE_FILTERS,
filterPipelines,
graphNote,
latestRunByPipeline,
pipelineFilterCount,
pipelineListEmptyState,
pipelineSubtitle,
pipelineUpdatedLine,
runBadge,
runBadgeMetaLine,
sortPipelines,
summaryFields,
versionRow,
} from "./pipelines.js";
import {
RUN_STATES,
RUN_TIME_RANGES,
RUN_SORTS,
DEFAULT_RUN_SORT,
runStateOf,
runIdentity,
versionLabel,
progressText,
metaText,
formatDuration,
localDayKey,
filterRuns,
groupRunsByDay,
runComparator,
pipelineFilterOptions,
runListEntries,
defaultRunFilters,
runFiltersActiveCount,
} from "./runs.js";
import {
effectiveStageType,
templateCard,
templateDetailName,
templateGalleryName,
templateGraphNote,
templateStageCountLabel,
templateStageSummary,
TEMPLATE_UNPARSED_SOURCE_NOTE,
} from "./templates.js";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
/** 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.";
/**
* The page is normally served by serve.mjs, which also proxies /connect to the
* Pipelines server. Defaulting to this page's own origin therefore points at
* that proxy and keeps the page and the WebSocket same-origin — the server
* rejects a cross-origin upgrade with 403. Nothing is hardcoded: the value is
* derived from wherever the page was loaded, and the user can override it.
*/
function defaultServerUrl() {
if (typeof location === "undefined" || !location.host) return "";
const scheme = location.protocol === "https:" ? "wss" : "ws";
return `${scheme}://${location.host}/connect`;
}
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
const state = {
view: "pipelines",
url: localStorage.getItem(STORAGE_KEY) ?? defaultServerUrl(),
connection: client.state,
pipelines: [],
runs: [],
usage: null,
pipelineDetail: null,
runDetail: null,
selectedPipelineId: null,
selectedRunId: null,
// Pipelines view: client-side filter/sort/detail-tab state. The run history is
// fetched alongside the pipelines so the list can show each pipeline's last
// run; runsLoaded tells a genuinely empty history apart from one not in hand.
pipelineFilters: { ...EMPTY_PIPELINE_FILTERS },
pipelineSort: "server_order",
pipelineMenu: null,
pipelineTab: "summary",
versionsExpanded: false,
pipelinesLoaded: false,
runsLoaded: false,
templates: [],
templateLoading: false,
// key -> graph|null: the parsed definition, cached once per template key. A
// failed/absent validate stores null so the card/detail say "unavailable".
templateGraphs: new Map(),
selectedTemplateKey: null,
templateTab: "summary",
loading: false,
error: "",
runFilters: defaultRunFilters(),
runSort: DEFAULT_RUN_SORT,
openMenu: null,
};
let runPoll = null;
// One shared live clock for the runs list: it ticks only while a shown run is
// executing, and each running row reads its elapsed from it rather than starting
// a timer of its own. Elapsed is derived from the server's start timestamp, so
// it stays correct after a reconnect; a finished history never ticks.
let listClock = null;
let listNow = Date.now();
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
function h(tag, props = {}, ...children) {
const node = document.createElement(tag);
for (const [key, value] of Object.entries(props)) {
if (value == null || value === false) continue;
if (key === "class") node.className = value;
else if (key === "text") node.textContent = value;
else if (key.startsWith("on") && typeof value === "function") {
node.addEventListener(key.slice(2).toLowerCase(), value);
} else node.setAttribute(key, value === true ? "" : String(value));
}
for (const child of children.flat()) {
if (child == null || child === false) continue;
node.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
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);
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
const header = h("header", { class: "topbar" });
const content = h("main", { id: "content" });
document.body.append(header, content);
function renderHeader() {
header.replaceChildren(
h("div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" })),
h(
"div",
{ class: "connbar" },
h("input", {
id: "url",
type: "text",
placeholder: "ws://HOST:PORT/connect",
value: state.url,
spellcheck: "false",
oninput: (e) => {
state.url = e.target.value;
},
}),
h("button", {
id: "connectBtn",
text: state.connection.kind === "connected" ? "Disconnect" : "Connect",
onclick: onConnectClicked,
}),
h("span", { class: "state", id: "stateBadge" }, connectionLabel()),
),
);
}
function connectionLabel() {
const c = state.connection;
switch (c.kind) {
case "connected":
return h("span", { class: "dot ok" }, "connected");
case "connecting":
return h("span", { class: "dot warn" }, `connecting… (attempt ${c.attempt})`);
case "disconnected":
return h("span", { class: "dot bad" }, `disconnected${c.reason ? ` — ${c.reason}` : ""}${c.retrying ? " (retrying)" : ""}`);
default:
return h("span", { class: "dot idle" }, "idle");
}
}
function render() {
renderHeader();
renderContent();
}
function renderContent() {
const nodes = [];
if (state.error) {
nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error));
}
nodes.push(
h(
"nav",
{ class: "tabs" },
tabButton("pipelines", `Pipelines (${state.pipelines.length})`),
tabButton("runs", `Runs (${state.runs.length})`),
tabButton("templates", "Templates"),
h("span", { class: "spacer" }),
h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }),
),
);
const split = h("div", { class: "split" });
if (state.view === "pipelines") {
split.append(renderPipelineList(), renderPipelineDetail());
} else if (state.view === "runs") {
split.append(renderRunList(), renderRunDetail());
} else {
split.append(renderTemplateGallery(), renderTemplateDetail());
}
nodes.push(split);
content.replaceChildren(...nodes);
if (state.view === "runs") refreshListClock();
else stopListClock();
}
function tabButton(view, label) {
return h("button", {
class: `tab${state.view === view ? " active" : ""}`,
text: label,
onclick: () => {
state.view = view;
state.error = "";
renderContent();
if (view === "runs" && !state.runs.length) loadCurrentView();
if (view === "pipelines" && !state.pipelines.length) loadCurrentView();
if (view === "templates" && !state.templates.length) loadCurrentView();
},
});
}
function renderPipelineList() {
const list = h("div", { class: "list" });
list.append(renderPipelineControls());
const rows = h("div", { id: "pipelineRows" });
fillPipelineRows(rows);
list.append(rows);
return list;
}
/**
* The list's filter + sort toolbar and (when open) the matching menu panel. The
* rows themselves live in the separate `#pipelineRows` container so a keystroke
* in the name filter can refresh just the rows without rebuilding (and so
* blurring) the input the operator is typing in.
*/
function renderPipelineControls() {
const filters = state.pipelineFilters;
const count = pipelineFilterCount(filters);
const panel = state.pipelineMenu;
const controls = h(
"div",
{ class: "list-controls" },
h(
"div",
{ class: "list-toolbar" },
h(
"button",
{
id: "filterToggle",
class: `control${panel === "filter" ? " active" : ""}`,
onclick: () => {
state.pipelineMenu = panel === "filter" ? null : "filter";
renderContent();
},
},
h("span", { text: "Filter" }),
h("span", { id: "filterCount", class: "count", text: count ? ` (${count})` : "" }),
),
h("button", {
id: "sortToggle",
class: `control${panel === "sort" ? " active" : ""}`,
text: `Sort: ${pipelineSortLabel(state.pipelineSort)}`,
onclick: () => {
state.pipelineMenu = panel === "sort" ? null : "sort";
renderContent();
},
}),
h("button", {
id: "clearFilters",
class: "ghost clear",
text: "Clear filters",
hidden: count === 0,
onclick: clearPipelineFilters,
}),
),
);
if (panel === "filter") controls.append(renderFilterPanel());
if (panel === "sort") controls.append(renderSortPanel());
return controls;
}
function renderFilterPanel() {
const filters = state.pipelineFilters;
const panel = h("div", { class: "menu-panel filter-panel" });
panel.append(h("div", { class: "filter-section", text: "Name" }));
panel.append(
h(
"label",
{ class: "filter-field" },
h("span", { class: "filter-field-label", text: "Pipeline name contains" }),
h("input", {
id: "pipelineNameFilter",
type: "text",
value: filters.name,
spellcheck: "false",
oninput: (e) => {
state.pipelineFilters = { ...state.pipelineFilters, name: e.target.value };
// Targeted refresh: the input keeps focus and its value while the
// list narrows behind it.
refreshPipelineRows();
},
}),
),
);
panel.append(h("div", { class: "filter-section", text: "Runs" }));
for (const presence of RUN_PRESENCES) {
panel.append(
h(
"label",
{ class: "filter-item" },
h("input", {
type: "radio",
name: "runPresence",
checked: filters.presence === presence.key,
onchange: () => {
state.pipelineFilters = { ...state.pipelineFilters, presence: presence.key };
renderContent();
},
}),
h("span", { text: presence.label }),
),
);
}
panel.append(h("div", { class: "filter-section", text: "Last run status" }));
for (const status of RUN_STATUS_FILTERS) {
panel.append(
h(
"label",
{ class: "filter-item" },
h("input", {
id: `status-${status}`,
type: "checkbox",
checked: filters.lastRunStatuses.includes(status),
onchange: (e) => {
const next = e.target.checked
? [...state.pipelineFilters.lastRunStatuses, status]
: state.pipelineFilters.lastRunStatuses.filter((s) => s !== status);
state.pipelineFilters = { ...state.pipelineFilters, lastRunStatuses: next };
renderContent();
},
}),
h("span", { text: status }),
),
);
}
panel.append(
h("div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearPipelineFilters })),
);
return panel;
}
function renderSortPanel() {
const panel = h("div", { class: "menu-panel sort-panel" });
for (const option of PIPELINE_SORTS) {
panel.append(
h("button", {
class: `sort-option${state.pipelineSort === option.key ? " active" : ""}`,
text: option.label,
onclick: () => {
state.pipelineSort = option.key;
state.pipelineMenu = null;
renderContent();
},
}),
);
}
panel.append(
h(
"div",
{ class: "filter-actions" },
h("button", {
class: "ghost",
text: "Reset",
onclick: () => {
state.pipelineSort = "server_order";
state.pipelineMenu = null;
renderContent();
},
}),
),
);
return panel;
}
/** Re-renders the rows and the toolbar's active-filter badge after a filter change. */
function refreshPipelineRows() {
const rows = document.getElementById("pipelineRows");
if (rows) fillPipelineRows(rows);
const count = pipelineFilterCount(state.pipelineFilters);
const badge = document.getElementById("filterCount");
if (badge) badge.textContent = count ? ` (${count})` : "";
const clear = document.getElementById("clearFilters");
if (clear) clear.hidden = count === 0;
}
/** Sorts, filters and renders the pipeline rows (or the matching empty state) into `rowsEl`. */
function fillPipelineRows(rowsEl) {
const latestRuns = latestRunByPipeline(state.runs);
const runsKnown = state.runsLoaded;
const now = Date.now();
const nodes = [];
if (state.loading && !state.pipelines.length) {
nodes.push(h("div", { class: "muted pad", text: "Loading pipelines…" }));
} else if (!state.pipelinesLoaded) {
nodes.push(h("div", { class: "muted pad", text: "Connect to the server to load pipelines." }));
} else {
const sorted = sortPipelines(state.pipelines, state.pipelineSort, latestRuns);
const items = filterPipelines(sorted, state.pipelineFilters, latestRuns, runsKnown);
if (items.length) {
for (const pipeline of items) nodes.push(renderPipelineRow(pipeline, latestRuns, runsKnown, now));
} else {
const empty = pipelineListEmptyState(state.pipelines, items, state.pipelineFilters);
const box = h("div", { class: "empty pad" }, h("div", { class: "muted", text: empty.message }));
if (empty.clearAction) {
box.append(h("button", { class: "ghost", text: empty.clearAction, onclick: clearPipelineFilters }));
}
nodes.push(box);
}
}
rowsEl.replaceChildren(...nodes);
}
function renderPipelineRow(pipeline, latestRuns, runsKnown, now) {
const children = [
h("span", { class: "row-title", text: pipeline.name || `pipeline ${pipeline.id}` }),
h("span", { class: "row-meta", text: pipelineSubtitle(pipeline) }),
];
const updated = pipelineUpdatedLine(pipeline);
if (updated) children.push(h("span", { class: "row-meta", text: updated }));
if (runsKnown) {
const run = latestRuns.get(pipeline.id);
if (!run) {
children.push(h("span", { class: "row-meta muted", text: "no runs recorded" }));
} else {
const badge = runBadge(run, now);
children.push(
h(
"span",
{ class: "row-run" },
h("span", { class: `chip chip-${badge.state}`, text: badge.state }),
h("span", { class: "row-meta", text: runBadgeMetaLine(badge) }),
),
);
}
}
return h(
"button",
{ class: `row${state.selectedPipelineId === pipeline.id ? " selected" : ""}`, onclick: () => selectPipeline(pipeline) },
...children,
);
}
function renderPipelineDetail() {
const d = state.pipelineDetail;
const pane = h("div", { class: "detail" });
if (!d) {
pane.append(h("div", { class: "muted pad", text: "Select a pipeline." }));
return pane;
}
pane.append(h("h2", { text: d.name || `pipeline ${d.id}` }));
pane.append(
h(
"div",
{ class: "detail-tabs" },
...PIPELINE_DETAIL_TABS.map((tab) =>
h("button", {
class: `detail-tab${state.pipelineTab === tab.key ? " active" : ""}`,
text: tab.label,
onclick: () => {
state.pipelineTab = tab.key;
renderContent();
},
}),
),
),
);
if (state.pipelineTab === "graph") {
pane.append(h("p", { class: "graph-note muted", text: graphNote() }));
return pane;
}
if (state.pipelineTab === "source") {
pane.append(h("pre", { class: "source-code" }, h("code", { text: d.source || "" })));
return pane;
}
pane.append(h("div", { class: "detail-subtitle muted", text: pipelineSubtitle({ ...d, stages: d.graph?.stages?.length ?? d.stages }) }));
const rows = h("div", { class: "kv" });
for (const field of summaryFields(d)) {
rows.append(
h(
"div",
{ class: "kv-row" },
h("span", { class: "kv-key", text: field.key }),
h("span", { class: `kv-val${field.monospace ? " monospace" : ""}`, text: field.value }),
),
);
}
pane.append(rows);
pane.append(
h(
"button",
{
class: "section-toggle",
onclick: () => {
state.versionsExpanded = !state.versionsExpanded;
renderContent();
},
},
h("span", { class: "chevron", text: state.versionsExpanded ? "\u25be" : "\u25b8" }),
h("span", { text: "Versions" }),
),
);
if (state.versionsExpanded) {
const versions = d.versions ?? [];
const body = h("div", { class: "section-body versions-list" });
if (!versions.length) {
body.append(h("div", { class: "muted", text: "No versions recorded." }));
} else {
for (const version of versions) {
const row = versionRow(version);
body.append(
h(
"div",
{ class: "version-row" },
h("span", { class: "version-title", text: row.versionLabel }),
h("span", { class: "muted", text: row.stagesText }),
row.createdText ? h("span", { class: "muted", text: row.createdText }) : null,
),
);
}
}
pane.append(body);
}
return pane;
}
// --- Templates -------------------------------------------------------------
/** The cached parsed graph for a template key, or null when it did not parse. */
function templateGraphFor(key) {
return state.templateGraphs.has(key) ? state.templateGraphs.get(key) : null;
}
function renderTemplateGallery() {
const pane = h("div", { class: "list gallery" });
pane.append(
h(
"div",
{ class: "pane-head" },
h("h2", { text: "Templates" }),
h("button", { class: "ghost", text: "Refresh templates", onclick: () => loadTemplates(true) }),
),
);
if (state.templateLoading && !state.templates.length) {
pane.append(h("div", { class: "muted pad", text: "Loading templates…" }));
return pane;
}
if (!state.templates.length) {
pane.append(h("div", { class: "muted pad", text: "No templates are available on this server." }));
return pane;
}
const cards = h("div", { class: "cards" });
for (const entry of state.templates) {
const card = templateCard(entry, templateGraphFor(entry.key));
cards.append(
h(
"button",
{
class: `card${state.selectedTemplateKey === entry.key ? " selected" : ""}`,
onclick: () => selectTemplate(entry.key),
},
h("span", { class: "card-name", text: templateGalleryName(card.name) }),
h("span", { class: "card-desc", text: card.description }),
h("span", { class: "card-meta", text: templateStageCountLabel(card.stageCount) }),
),
);
}
pane.append(cards);
return pane;
}
function renderTemplateDetail() {
const pane = h("div", { class: "detail" });
const entry = state.templates.find((t) => t.key === state.selectedTemplateKey);
if (!entry) {
pane.append(h("div", { class: "muted pad", text: "Select a template." }));
return pane;
}
const graph = templateGraphFor(entry.key);
pane.append(
h(
"div",
{ class: "tabstrip" },
templateTabButton("summary", "Summary"),
templateTabButton("graph", "Graph"),
templateTabButton("source", "Source"),
),
);
if (state.templateTab === "graph") pane.append(renderTemplateGraphTab(graph));
else if (state.templateTab === "source") pane.append(renderTemplateSourceTab(entry, graph));
else pane.append(renderTemplateSummaryTab(entry, graph));
return pane;
}
function templateTabButton(tab, label) {
return h("button", {
class: `minitab${state.templateTab === tab ? " active" : ""}`,
text: label,
onclick: () => {
state.templateTab = tab;
renderContent();
},
});
}
function renderTemplateSummaryTab(entry, graph) {
const wrap = h("div", { class: "tabbody" });
wrap.append(h("h2", { text: templateDetailName(entry) }));
if ((entry.description ?? "").trim()) {
wrap.append(h("p", { class: "body", text: entry.description }));
}
wrap.append(h("div", { class: "kv" }, kvMono("Key", entry.key)));
wrap.append(
h("div", { class: "meta-line", text: templateStageCountLabel(graph?.stages?.length ?? null) }),
);
if (entry.scheduled) wrap.append(h("div", { class: "meta-line", text: "Includes a schedule" }));
const summary = templateStageSummary(graph);
if (summary.note) {
wrap.append(h("div", { class: "muted pad", text: summary.note }));
return wrap;
}
wrap.append(h("h3", { text: "Stages" }));
const ul = h("ul", { class: "stages" });
for (const stage of summary.stages) {
ul.append(
h(
"li",
{},
h("code", { text: stage.key }),
h("span", { class: "chip", text: effectiveStageType(stage.type) }),
),
);
}
wrap.append(ul);
return wrap;
}
function renderTemplateGraphTab(graph) {
const wrap = h("div", { class: "tabbody" });
wrap.append(h("p", { class: "muted", text: templateGraphNote(graph) }));
return wrap;
}
function renderTemplateSourceTab(entry, graph) {
const wrap = h("div", { class: "tabbody" });
if (graph == null) {
wrap.append(h("p", { class: "muted", text: TEMPLATE_UNPARSED_SOURCE_NOTE }));
}
wrap.append(
h(
"div",
{ class: "codeblock" },
h("div", { class: "codeblock-label", text: "Definition source" }),
h("pre", { class: "codeblock-body", text: entry.source ?? "" }),
),
);
return wrap;
}
function pipelineSortLabel(key) {
return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label;
}
function clearPipelineFilters() {
state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS };
renderContent();
}
function renderRunList() {
const pane = h("div", { class: "list runs" });
pane.append(renderRunToolbar());
const scroll = h("div", { class: "run-scroll" });
if (state.loading && !state.runs.length) {
scroll.append(h("div", { class: "muted pad", text: "Loading…" }));
pane.append(scroll);
return pane;
}
const filters = state.runFilters;
const today = localDayKey(new Date());
const filtered = filterRuns(state.runs, filters, today);
const groups = groupRunsByDay(filtered, today, undefined, runComparator(state.runSort));
const entries = runListEntries(
state.usage,
state.runs.length === 0,
filtered.length === 0 && state.runs.length > 0,
groups,
"",
);
for (const entry of entries) {
switch (entry.kind) {
case "usage":
scroll.append(renderUsage(entry.usage));
break;
case "empty":
scroll.append(renderEmptyState(entry));
break;
case "day":
scroll.append(h("div", { class: "day-header", text: entry.label }));
break;
case "run":
scroll.append(renderRunRow(entry.run));
break;
case "error":
scroll.append(h("div", { class: "run-list-error", text: entry.message }));
break;
}
}
pane.append(scroll);
return pane;
}
function renderUsage(usage) {
const metrics = h("div", { class: "metrics" });
metrics.append(metric("Total", String(usage.total ?? 0), "total"));
if ((usage.average_seconds ?? 0) > 0) {
metrics.append(metric("Average", formatDuration(usage.average_seconds), "average"));
}
metrics.append(metric("Succeeded", String(usage.succeeded ?? 0), "succeeded"));
metrics.append(metric("Failed", String(usage.failed ?? 0), "failed"));
metrics.append(metric("Canceled", String(usage.canceled ?? 0), "canceled"));
metrics.append(metric("Interrupted", String(usage.interrupted ?? 0), "interrupted"));
metrics.append(metric("Active", String(usage.active ?? 0), "active"));
return metrics;
}
function metric(label, value, cls) {
return h(
"div",
{ class: `metric metric-${cls}` },
h("span", { class: "metric-value", text: value }),
h("span", { class: "metric-label", text: label }),
);
}
function renderEmptyState(entry) {
const wrap = h("div", { class: "empty-state" }, h("span", { text: entry.message }));
if (entry.actionLabel) {
wrap.append(h("button", { class: "ghost", text: entry.actionLabel, onclick: clearRunFilters }));
}
return wrap;
}
/**
* One run row, in the app's exact hierarchy: status chip (+ spinner while
* executing); primary line = stored title else pipeline name, carrying the
* version chip when there is no title; the pipeline name + version chip on a
* second line only when a title exists; the progress line; the meta line; and
* the diagnostic line, in the error colour only on a failure. Every
* server-provided string is set with textContent.
*/
function renderRunRow(run) {
const status = runStateOf(run.status);
const identity = runIdentity(run.title, run.name);
const row = h("button", {
class: `row run-row${state.selectedRunId === run.id ? " selected" : ""}`,
onclick: () => selectRun(run.id),
});
const head = h("span", { class: "run-row-head" });
head.append(h("span", { class: `chip chip-${status}`, text: status }));
if (run.executing) head.append(h("span", { class: "spinner", "aria-hidden": "true" }));
head.append(h("span", { class: "run-row-title", text: identity.label }));
if (identity.pipeline == null) head.append(versionChip(run.version));
row.append(head);
if (identity.pipeline != null) {
row.append(
h(
"span",
{ class: "run-row-pipeline" },
h("span", { class: "run-row-pipeline-name", text: identity.pipeline }),
versionChip(run.version),
),
);
}
row.append(h("span", { class: "run-row-progress", text: progressText(run) }));
row.append(
h("span", {
class: "run-row-meta",
"data-run-id": String(run.id),
text: metaText(run, listNow),
}),
);
if (String(run.diagnostic ?? "").trim()) {
row.append(
h("span", {
class: `run-row-diag${status === "failed" ? " error" : ""}`,
text: run.diagnostic,
}),
);
}
return row;
}
function versionChip(version) {
return h("span", { class: "version-chip", text: versionLabel(version) });
}
function renderRunToolbar() {
const activeCount = runFiltersActiveCount(state.runFilters);
const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter";
const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label;
const toolbar = h("div", { class: "run-toolbar" });
toolbar.append(
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runFilterBtn",
class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`,
title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs",
text: filterLabel,
"data-active-count": String(activeCount),
onclick: () => toggleMenu("filter"),
}),
state.openMenu === "filter" ? renderFilterMenu() : null,
),
h(
"div",
{ class: "menu-anchor" },
h("button", {
id: "runSortBtn",
class: "ghost sort-btn",
title: "Sort runs",
text: `Sort: ${sortLabel}`,
onclick: () => toggleMenu("sort"),
}),
state.openMenu === "sort" ? renderSortMenu() : null,
),
h("span", { class: "spacer" }),
);
return toolbar;
}
function renderFilterMenu() {
const filters = state.runFilters;
const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" });
menu.append(h("div", { class: "menu-section", text: "Status" }));
for (const status of RUN_STATES) {
menu.append(
filterCheck(status, filters.statuses.has(status), () => toggleStatusFilter(status), {
"data-status": status,
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Pipeline" }));
menu.append(
filterCheck("Any pipeline", filters.pipelineId == null, () => setPipelineFilter(null), {
"data-pipeline": "any",
}),
);
for (const option of pipelineFilterOptions(state.runs)) {
menu.append(
filterCheck(option.name, filters.pipelineId === option.id, () => setPipelineFilter(option.id), {
"data-pipeline": String(option.id),
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(h("div", { class: "menu-section", text: "Time range" }));
for (const range of RUN_TIME_RANGES) {
menu.append(
filterCheck(range.label, filters.timeRange === range.value, () => setTimeRangeFilter(range.value), {
"data-time": range.value,
}),
);
}
menu.append(
h(
"div",
{ class: "menu-actions" },
h("button", { class: "ghost", text: "Clear filters", onclick: clearRunFilters }),
h("button", { class: "ghost", text: "Done", onclick: closeMenu }),
),
);
return menu;
}
function filterCheck(label, checked, onclick, data = {}) {
return h(
"label",
{ class: "filter-check" },
h("input", {
type: "checkbox",
checked: checked ? "checked" : null,
onchange: onclick,
...data,
}),
h("span", { text: label }),
);
}
function renderSortMenu() {
const menu = h("div", { class: "menu sort-menu", id: "runSortMenu" });
for (const option of RUN_SORTS) {
menu.append(
h("button", {
class: `menu-item${state.runSort === option.value ? " selected" : ""}`,
text: option.label,
onclick: () => {
state.runSort = option.value;
closeMenu();
},
}),
);
}
menu.append(h("div", { class: "menu-divider" }));
menu.append(
h("button", {
class: "menu-item",
text: "Reset",
onclick: () => {
state.runSort = DEFAULT_RUN_SORT;
closeMenu();
},
}),
);
return menu;
}
function toggleStatusFilter(status) {
const next = new Set(state.runFilters.statuses);
if (next.has(status)) next.delete(status);
else next.add(status);
state.runFilters = { ...state.runFilters, statuses: next };
renderContent();
}
function setPipelineFilter(pipelineId) {
state.runFilters = { ...state.runFilters, pipelineId };
closeMenu();
}
function setTimeRangeFilter(timeRange) {
state.runFilters = { ...state.runFilters, timeRange };
closeMenu();
}
function clearRunFilters() {
state.runFilters = defaultRunFilters();
closeMenu();
}
function toggleMenu(name) {
state.openMenu = state.openMenu === name ? null : name;
renderContent();
}
function closeMenu() {
state.openMenu = null;
renderContent();
}
function renderRunDetail() {
const d = state.runDetail;
const pane = h("div", { class: "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,
),
);
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;
}
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),
),
);
}
pane.append(list);
return pane;
}
/** 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.
*/
function renderArtifactGallery(steps) {
const wrap = h("div", { class: "artifact-gallery" });
const groups = artifactGroups(steps);
if (!groups.length) return wrap;
if (!artifactsResolvable()) {
wrap.append(h("div", { class: "muted artifact-hint", text: ARTIFACT_SERVER_HINT }));
}
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 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 media, exactly as the Android section does.
*/
function renderVisitArtifacts(step) {
const wrap = h("div", { class: "artifacts" });
wrap.append(h("div", { class: "artifacts-summary", text: artifactsSummary(step) }));
for (const note of artifactCaptureNotes(step)) {
wrap.append(h("div", { class: "artifacts-note muted", text: note }));
}
const artifacts = presentedArtifacts(step);
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. 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 name = artifact.name || "(unnamed artifact)";
const tile = h("div", { class: "artifact-tile clickable" });
const openViewer = () => {
const at = viewerIndexOf.get(artifact.url);
if (at != null) openArtifactViewer(viewable, at);
};
const openTab = () => {
if (resolved) window.open(resolved, "_blank", "noopener,noreferrer");
};
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);
} else if (kind === ArtifactKind.Video) {
tile.append(h("div", { class: "artifact-poster" }, h("span", { class: "artifact-play", text: "▶" })));
tile.append(h("div", { class: "artifact-name", text: name }));
tile.addEventListener("click", openViewer);
} else {
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);
}
tile.append(renderTileActions(resolved, media));
return tile;
}
/** The compact per-tile actions: copy-link (non-media tiles) and share. */
function renderTileActions(resolved, media) {
const actions = h("div", { class: "artifact-actions" });
const stop = (fn) => (event) => {
event.stopPropagation();
fn();
};
if (!media) {
actions.append(
h("button", {
class: "artifact-action",
type: "button",
text: "Copy link",
disabled: !resolved || !canCopyLink(),
onclick: stop(() => copyArtifactLink(resolved)),
}),
);
}
actions.append(
h("button", {
class: "artifact-action",
type: "button",
text: "Share",
disabled: !resolved || !canShare(),
onclick: stop(() => shareArtifact(resolved)),
}),
);
return actions;
}
function canCopyLink() {
return typeof navigator !== "undefined" && Boolean(navigator.clipboard?.writeText);
}
function canShare() {
return typeof navigator !== "undefined" && typeof navigator.share === "function";
}
async function copyArtifactLink(resolved) {
if (!resolved || !canCopyLink()) return;
try {
await navigator.clipboard.writeText(resolved);
} catch {
// Clipboard permission may be denied; the link is still openable.
}
}
async function shareArtifact(resolved) {
if (!resolved || !canShare()) return;
try {
await navigator.share({ url: resolved });
} catch {
// The share chooser may be dismissed.
}
}
/**
* 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" });
if (!file) {
wrap.append(h("span", { class: "muted", text: "No session was exported for this visit." }));
return wrap;
}
const href = resolvedArtifactUrl(file, state.url);
if (href) {
wrap.append(
h("a", {
class: "session-link",
href,
target: "_blank",
rel: "noreferrer",
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;
}
let viewerOverlay = null;
let viewerKeydown = null;
/** Close the full-screen viewer and remove its Escape listener. */
function closeArtifactViewer() {
if (viewerKeydown) {
document.removeEventListener("keydown", viewerKeydown);
viewerKeydown = null;
}
viewerOverlay?.remove();
viewerOverlay = null;
}
/**
* Open the full-screen viewer at `startIndex` into `viewable`, the same ordered
* media list the grid drew. Previous/Next are disabled at the ends and absent for
* a single artifact; Escape and a backdrop click close it. Nothing autoplays: a
* non-image artifact shows a still poster placeholder instead.
*/
function openArtifactViewer(viewable, startIndex) {
closeArtifactViewer();
if (!viewable?.length) return;
let index = pagedIndex(startIndex, 0, viewable.length);
const overlay = h("div", {
class: "artifact-viewer",
role: "dialog",
"aria-modal": "true",
"aria-label": "Artifact viewer",
});
overlay.addEventListener("click", (event) => {
if (event.target === overlay) closeArtifactViewer();
});
const renderViewer = () => {
const artifact = viewable[index] ?? {};
const resolved = resolvedArtifactUrl(artifact, state.url);
const kind = artifactKind(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 {
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" });
if (resolved) {
actions.append(
h("button", {
class: "viewer-action",
type: "button",
text: "Open",
onclick: () => window.open(resolved, "_blank", "noopener,noreferrer"),
}),
h("button", {
class: "viewer-action",
type: "button",
text: "Copy link",
disabled: !canCopyLink(),
onclick: () => copyArtifactLink(resolved),
}),
h("button", {
class: "viewer-action",
type: "button",
text: "Share",
disabled: !canShare(),
onclick: () => shareArtifact(resolved),
}),
);
}
actions.append(
h("button", {
class: "viewer-action viewer-close",
type: "button",
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",
text: "Previous artifact",
disabled: pagedIndex(index, -1, viewable.length) === index,
onclick: () => {
index = pagedIndex(index, -1, viewable.length);
renderViewer();
},
}),
h("button", {
class: "viewer-page",
type: "button",
text: "Next artifact",
disabled: pagedIndex(index, 1, viewable.length) === index,
onclick: () => {
index = pagedIndex(index, 1, viewable.length);
renderViewer();
},
}),
),
);
}
nodes.push(actions);
overlay.replaceChildren(...nodes);
};
renderViewer();
document.body.append(overlay);
viewerOverlay = overlay;
viewerKeydown = (event) => {
if (event.key === "Escape") closeArtifactViewer();
};
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(
"div",
{ class: "kv-row" },
h("span", { class: "kv-key", text: key }),
h("span", { class: "kv-val" }, h("code", { text: value })),
);
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
function setError(err) {
state.error = err instanceof Error ? err.message : String(err);
state.loading = false;
renderContent();
}
function onConnectClicked() {
if (state.connection.kind === "connected") {
repo.disconnect();
stopRunPoll();
return;
}
const validated = validateServerUrl(state.url);
if (!validated.valid) {
state.error = validated.message;
renderContent();
return;
}
state.error = "";
localStorage.setItem(STORAGE_KEY, state.url.trim());
repo.connect(validated);
// The `state` listener kicks off the initial load once connected.
}
async function onConnected() {
try {
await repo.ping();
} catch (err) {
setError(err);
return;
}
await loadCurrentView();
}
async function loadCurrentView(force = false) {
if (state.connection.kind !== "connected") {
state.error = "Connect to the server first.";
renderContent();
return;
}
if (state.view === "templates") {
await loadTemplates(force);
return;
}
state.loading = true;
state.error = "";
renderContent();
try {
if (state.view === "pipelines") {
state.pipelines = await repo.listPipelines();
state.pipelinesLoaded = true;
// The last-run line joins list_runs onto the pipelines, so the history is
// fetched alongside them; runsLoaded distinguishes a genuinely empty
// history from one that has not arrived yet.
const { runs, usage } = await repo.listRuns();
state.runs = runs;
if (usage) state.usage = usage;
state.runsLoaded = true;
} else {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
state.usage = usage;
state.runsLoaded = true;
}
state.loading = false;
renderContent();
// Keep the current selection fresh after a refresh.
if (force && state.view === "runs" && state.selectedRunId) {
await selectRun(state.selectedRunId, { silent: true });
}
} catch (err) {
setError(err);
}
}
/**
* Loads the template catalogue, then validates each template's source once and
* caches the parsed graph (null when it did not parse) so a card's stage count
* and the detail's stage list read the same result and can never disagree.
*/
async function loadTemplates(force = false) {
state.templateLoading = true;
state.error = "";
renderContent();
try {
state.templates = await repo.listTemplates();
for (const entry of state.templates) {
if (force || !state.templateGraphs.has(entry.key)) {
state.templateGraphs.set(entry.key, await validateTemplate(entry));
}
}
state.templateLoading = false;
renderContent();
} catch (err) {
state.templateLoading = false;
setError(err);
}
}
/** The parsed graph for a template, or null when the server cannot parse its source. */
async function validateTemplate(entry) {
try {
return await repo.validate(entry.source);
} catch {
return null;
}
}
function selectTemplate(key) {
state.selectedTemplateKey = key;
state.templateTab = "summary";
renderContent();
}
async function selectPipeline(summary) {
state.selectedPipelineId = summary.id;
state.pipelineDetail = null;
state.pipelineTab = "summary";
state.versionsExpanded = false;
renderContent();
try {
state.pipelineDetail = await repo.getPipeline(summary.id, summary.version);
renderContent();
} catch (err) {
setError(err);
}
}
async function selectRun(id, { silent = false } = {}) {
state.selectedRunId = id;
if (!silent) {
state.runDetail = null;
renderContent();
}
try {
state.runDetail = await repo.getRun(id);
renderContent();
updateRunPoll();
} catch (err) {
if (!silent) setError(err);
else stopRunPoll();
}
}
function updateRunPoll() {
stopRunPoll();
if (state.view === "runs" && state.selectedRunId && isExecuting(state.runDetail)) {
runPoll = setInterval(() => selectRun(state.selectedRunId, { silent: true }), 1000);
}
}
function stopRunPoll() {
if (runPoll) {
clearInterval(runPoll);
runPoll = null;
}
}
/**
* (Re)start the shared runs-list clock: it ticks once a second only while a
* shown run is executing, updating each running row's meta line in place (never
* a full re-render, so an open filter/sort menu is not torn down). The elapsed
* value is derived from the run's server start timestamp, so it survives a
* reconnect.
*/
function refreshListClock() {
stopListClock();
listNow = Date.now();
if (state.view === "runs" && state.runs.some((run) => run.executing)) {
listClock = setInterval(() => {
listNow = Date.now();
for (const node of document.querySelectorAll(".run-row-meta[data-run-id]")) {
const id = Number(node.getAttribute("data-run-id"));
const run = state.runs.find((candidate) => candidate.id === id);
if (run && run.executing) node.textContent = metaText(run, listNow);
}
}, 1000);
}
}
function stopListClock() {
if (listClock) {
clearInterval(listClock);
listClock = null;
}
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
client.addEventListener("state", (event) => {
const next = event.detail;
const wasConnected = state.connection.kind === "connected";
const previousKind = state.connection.kind;
state.connection = next;
if (next.kind === "connected" && !wasConnected) {
onConnected();
}
if (next.kind !== "connected" && previousKind === "connected") {
stopRunPoll();
stopListClock();
}
render();
});
// Prefill from a previous session only; the user still confirms with Connect.
render();