// 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 { 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"; const STORAGE_KEY = "pipelines.web.serverUrl.v2"; /** * The retired markdown session export. The server no longer writes it, but a run * recorded before the HTML-only change still lists session.md among its stored * artifacts. It is dated evidence the operator never sees, so every artifact * listing hides it rather than showing it beside the session html (mirroring the * app's presentedArtifacts). */ const LEGACY_SESSION_MARKDOWN_ARTIFACT = "session.md"; /** * 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, loading: false, error: "", }; let runPoll = null; // --------------------------------------------------------------------------- // 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})`), 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 { split.append(renderRunList(), renderRunDetail()); } nodes.push(split); content.replaceChildren(...nodes); } 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(); }, }); } 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; } 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 list = h("div", { class: "list" }); if (state.usage) { list.append( h( "div", { class: "usage" }, h("span", { text: `${state.usage.total} total` }), h("span", { class: "ok", text: `${state.usage.succeeded} succeeded` }), h("span", { class: "bad", text: `${state.usage.failed} failed` }), h("span", { class: "warn", text: `${state.usage.active} active` }), ), ); } if (state.loading && !state.runs.length) { list.append(h("div", { class: "muted pad", text: "Loading…" })); return list; } if (!state.runs.length) { list.append(h("div", { class: "muted pad", text: "No runs." })); return list; } for (const r of state.runs) { list.append( h( "button", { class: `row${state.selectedRunId === r.id ? " selected" : ""}`, onclick: () => selectRun(r.id), }, h( "span", { class: "row-head" }, h("span", { class: "row-title", text: r.title || r.name || `run ${r.id}` }), h("span", { class: statusClass(r.status), text: r.status || "unknown" }), ), h( "span", { class: "row-meta" }, `#${r.id} · ${fmtTime(r.created_at)} · `, isExecuting(r) ? h("em", { text: fmtDuration(r.created_at, "") }) : fmtDuration(r.created_at, r.finished_at), ), r.diagnostic ? h("span", { class: "row-diag", text: r.diagnostic }) : null, ), ); } return list; } 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 ?? []; 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, ), renderArtifacts(s), ), ); } pane.append(list); return pane; } function renderArtifacts(step) { const artifacts = (step.artifacts ?? []).filter((a) => a.name !== LEGACY_SESSION_MARKDOWN_ARTIFACT); if (!artifacts.length) return null; const wrap = h("div", { class: "artifacts" }, h("span", { class: "muted", text: "Artifacts: " })); for (const a of artifacts) { const href = resolveArtifactUrl(state.url, a.url); if (href) { wrap.append(h("a", { href, target: "_blank", rel: "noreferrer", text: a.name || a.url })); } else { wrap.append(h("span", { class: "muted", text: `${a.name || a.url} (no server URL)` })); } } return wrap; } function kv(key, value) { return h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: key }), h("span", { class: "kv-val", 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; } 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); } } 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; } } // --------------------------------------------------------------------------- // 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(); } render(); }); // Prefill from a previous session only; the user still confirms with Connect. render();