From da3c488506320d42c885c3cc8da4927e6104c24e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 02:30:39 +0100 Subject: [PATCH 1/3] web: templates gallery and template detail (P4) --- web/PARITY.md | 2 +- web/src/app.js | 210 ++++++++++++++++++++++++++++++++++- web/src/protocol.js | 5 + web/src/repository.js | 14 +++ web/src/templates.js | 93 ++++++++++++++++ web/styles.css | 53 +++++++++ web/test/repository.test.mjs | 106 ++++++++++++++++++ web/test/templates.test.mjs | 87 +++++++++++++++ web/test/ui-smoke.mjs | 18 +++ 9 files changed, 586 insertions(+), 2 deletions(-) create mode 100644 web/src/templates.js create mode 100644 web/test/repository.test.mjs create mode 100644 web/test/templates.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index 5df4f4e4..0db762e0 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -24,7 +24,7 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | P1 | Pipeline list | `list_pipelines` | partial (list + count only) | | P2 | Filter + sort (status/name/updated) | client-side | todo | | P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | todo | -| P4 | Templates gallery + template detail | `list_templates` | todo | +| P4 | Templates gallery + template detail | `list_templates`, `validate` | done | | P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | todo | | P6 | Workflow graph rendering (nodes, edges, stage panes) | `get_pipeline` | todo | diff --git a/web/src/app.js b/web/src/app.js index 1af401e1..4eeda71e 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -4,6 +4,16 @@ import { PipelinesClient } from "./client.js"; import { PipelinesRepository } from "./repository.js"; import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js"; +import { + effectiveStageType, + templateCard, + templateDetailName, + templateGalleryName, + templateGraphNote, + templateStageCountLabel, + templateStageSummary, + TEMPLATE_UNPARSED_SOURCE_NOTE, +} from "./templates.js"; const STORAGE_KEY = "pipelines.web.serverUrl.v2"; @@ -43,6 +53,13 @@ const state = { runDetail: null, selectedPipelineId: null, selectedRunId: null, + 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: "", }; @@ -168,6 +185,7 @@ function renderContent() { { 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) }), ), @@ -176,8 +194,10 @@ function renderContent() { const split = h("div", { class: "split" }); if (state.view === "pipelines") { split.append(renderPipelineList(), renderPipelineDetail()); - } else { + } else if (state.view === "runs") { split.append(renderRunList(), renderRunDetail()); + } else { + split.append(renderTemplateGallery(), renderTemplateDetail()); } nodes.push(split); content.replaceChildren(...nodes); @@ -193,6 +213,7 @@ function tabButton(view, label) { renderContent(); if (view === "runs" && !state.runs.length) loadCurrentView(); if (view === "pipelines" && !state.pipelines.length) loadCurrentView(); + if (view === "templates" && !state.templates.length) loadCurrentView(); }, }); } @@ -264,6 +285,140 @@ function renderPipelineDetail() { 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 renderRunList() { const list = h("div", { class: "list" }); if (state.usage) { @@ -401,6 +556,16 @@ function kv(key, 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 // --------------------------------------------------------------------------- @@ -445,6 +610,10 @@ async function loadCurrentView(force = false) { renderContent(); return; } + if (state.view === "templates") { + await loadTemplates(force); + return; + } state.loading = true; state.error = ""; renderContent(); @@ -467,6 +636,45 @@ async function loadCurrentView(force = false) { } } +/** + * 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; diff --git a/web/src/protocol.js b/web/src/protocol.js index 72ce842b..65fd52cf 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -11,6 +11,11 @@ export const Protocol = Object.freeze({ GET_PIPELINE: "get_pipeline", PIPELINE: "pipeline", + LIST_TEMPLATES: "list_templates", + TEMPLATES: "templates", + VALIDATE: "validate", + VALIDATED: "validated", + LIST_RUNS: "list_runs", RUNS: "runs", GET_RUN: "get_run", diff --git a/web/src/repository.js b/web/src/repository.js index 1ae5387c..11251765 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -43,6 +43,20 @@ export class PipelinesRepository { return response.detail; } + async listTemplates() { + return (await this.#client.call({ type: Protocol.LIST_TEMPLATES })).templates ?? []; + } + + async validate(source) { + const response = await this.#client.call({ type: Protocol.VALIDATE, source }); + // A server error envelope already rejects inside client.call, so a reply + // here is `validated`; a missing graph is still an unusable definition. + if (!response.graph) { + throw new ProtocolError("The server returned no graph."); + } + return response.graph; + } + async listRuns() { const response = await this.#client.call({ type: Protocol.LIST_RUNS }); return { runs: response.runs ?? [], usage: response.usage ?? null }; diff --git a/web/src/templates.js b/web/src/templates.js new file mode 100644 index 00000000..a7e01a62 --- /dev/null +++ b/web/src/templates.js @@ -0,0 +1,93 @@ +// Pure Templates derivations, mirroring the Android app's ui/Templates.kt, +// ui/Format.kt and ui/graph/StageDetailPane.kt. No DOM and no protocol here, so +// the gallery/detail wording and the stage-count mapping are unit-tested without +// a browser. Every value returned is plain text (or plain data); the caller sets +// it with textContent and never with innerHTML. + +/** A gallery card's name: a blank name is the explicit unnamed-template placeholder. */ +export function templateGalleryName(name) { + return (name ?? "").trim() ? name : "(unnamed template)"; +} + +/** A detail's heading: a blank name falls back to the template's key. */ +export function templateDetailName(entry) { + const name = (entry?.name ?? "").trim(); + return name ? entry.name : (entry?.key ?? ""); +} + +/** "1 stage" / "N stages", mirroring ui/Format.kt stageCountText. */ +export function stageCountText(count) { + return `${count} ${count === 1 ? "stage" : "stages"}`; +} + +/** + * The card's stage-count line: the count parsed from the source, or an explicit + * "unavailable" when the source could not be parsed (never "0 stages", which + * would claim a count the client does not have). + */ +export function templateStageCountLabel(stageCount) { + return stageCount == null ? "stage count unavailable" : stageCountText(stageCount); +} + +/** The effective stage type, mirroring internal/stage.EffectiveType: blank is the model stage. */ +export function effectiveStageType(type) { + return (type ?? "").trim() ? type : "model"; +} + +/** + * One gallery card's content: the template's name and description (from the + * catalogue) and its stage count (from the graph the server parsed out of the + * source; null when the source did not parse, so the card says so rather than + * claiming zero stages). + */ +export function templateCard(entry, graph = null) { + return { + key: entry?.key ?? "", + name: entry?.name ?? "", + description: entry?.description ?? "", + stageCount: graph?.stages?.length ?? null, + }; +} + +/** The unparsed-source note the Summary tab shows instead of a stage list. */ +export const TEMPLATE_UNPARSED_SUMMARY_NOTE = + "This template's source could not be parsed, so its stages are not listed. See the Source tab for the raw definition."; + +/** The note the Summary tab shows for a parsed template that declares no stages. */ +export const TEMPLATE_NO_STAGES_NOTE = "This template has no stages."; + +/** The Graph tab's note when the source did not parse. */ +export const TEMPLATE_UNPARSED_GRAPH_NOTE = + "This template's source could not be parsed, so there is no graph. The Source tab shows the raw definition."; + +/** The Graph tab's note when the source parsed; the graph is the parsed definition. */ +export const TEMPLATE_GRAPH_NOTE = + "Pinch to zoom and drag to pan. The graph is the parsed definition; nothing runs."; + +/** The Source tab's note when the source did not parse on the server. */ +export const TEMPLATE_UNPARSED_SOURCE_NOTE = + "This source could not be parsed on the server; showing the raw definition."; + +/** + * The Summary tab's stage section: an explicit [note] and no stages when the + * source did not parse or parsed to nothing, else the stage rows (key + effective + * type). One derivation, so the note and the list can never disagree. + */ +export function templateStageSummary(graph) { + if (graph == null) { + return { note: TEMPLATE_UNPARSED_SUMMARY_NOTE, stages: [] }; + } + const stages = graph.stages ?? []; + if (!stages.length) { + return { note: TEMPLATE_NO_STAGES_NOTE, stages: [] }; + } + return { + note: null, + stages: stages.map((stage) => ({ key: stage.key, type: effectiveStageType(stage.type) })), + }; +} + +/** The Graph tab's note: the unparsed note when there is no graph, else the parsed-definition note. */ +export function templateGraphNote(graph) { + return graph == null ? TEMPLATE_UNPARSED_GRAPH_NOTE : TEMPLATE_GRAPH_NOTE; +} diff --git a/web/styles.css b/web/styles.css index f753f440..0dce27da 100644 --- a/web/styles.css +++ b/web/styles.css @@ -142,3 +142,56 @@ button.ghost { background: transparent; } .banner.error { background: #2c1616; color: var(--bad); } code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-size: 12px; } + +/* --- Templates gallery + detail ------------------------------------------ */ + +.pane-head { display: flex; gap: 8px; align-items: center; justify-content: space-between; padding: 12px 12px 0; } +.pane-head h2 { margin: 0; font-size: 16px; } + +.gallery { padding-bottom: 8px; } +.cards { display: grid; gap: 8px; padding: 10px 12px; } +.card { + display: block; + width: 100%; + text-align: left; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface-2); + padding: 10px 12px; +} +.card:hover { border-color: var(--accent); } +.card.selected { box-shadow: inset 3px 0 0 var(--accent); border-color: var(--accent); } +.card-name { display: block; font-weight: 600; } +.card-desc { + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + color: var(--muted); + font-size: 12px; + margin-top: 2px; +} +.card-desc:empty { display: none; } +.card-meta { display: block; color: var(--accent); font-size: 12px; margin-top: 4px; } + +.tabstrip { display: flex; gap: 4px; margin: -4px 0 12px; } +.minitab { border-color: transparent; background: transparent; padding: 5px 10px; } +.minitab.active { background: var(--surface-2); border-color: var(--border); color: var(--accent); } + +.tabbody h2 { margin-top: 0; } +.tabbody .body { margin: 0 0 12px; } +.meta-line { color: var(--muted); font-size: 12px; margin-top: 4px; } + +.codeblock { border: 1px solid var(--border); border-radius: 10px; overflow: hidden; margin-top: 12px; } +.codeblock-label { padding: 6px 10px; background: var(--surface-2); border-bottom: 1px solid var(--border); color: var(--muted); font-size: 12px; } +.codeblock-body { + margin: 0; + padding: 10px; + max-height: 420px; + overflow: auto; + background: transparent; + color: var(--text); + font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; + white-space: pre-wrap; + word-break: break-word; +} diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs new file mode 100644 index 00000000..1b560c5e --- /dev/null +++ b/web/test/repository.test.mjs @@ -0,0 +1,106 @@ +// Repository request-shape tests: the templates catalogue and the validate +// command, driven through the real transport against a fake WebSocket so the +// exact frames sent (and the error-envelope handling) are proven, not assumed. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { PipelinesClient, ProtocolError } from "../src/client.js"; +import { PipelinesRepository } from "../src/repository.js"; +import { validateServerUrl } from "../src/serverUrl.js"; + +const VALID = validateServerUrl("ws://host:8080/connect"); + +/** The same minimal fake the client tests use (test files are not importable). */ +class FakeWebSocket { + static instances = []; + + constructor(url) { + this.url = url; + this.sent = []; + this.onopen = null; + this.onmessage = null; + this.onclose = null; + this.onerror = null; + this.reply = null; + FakeWebSocket.instances.push(this); + } + + send(data) { + const frame = JSON.parse(data); + this.sent.push(frame); + const response = this.reply?.(frame); + if (response !== undefined) { + this.onmessage?.({ data: JSON.stringify(response) }); + } + } + + close(code, reason) { + this.onclose?.({ code, reason }); + } + + open() { + this.onopen?.({}); + } +} + +function connected() { + FakeWebSocket.instances = []; + const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket }); + const repo = new PipelinesRepository(client); + client.connect(VALID); + const ws = FakeWebSocket.instances.at(-1); + ws.open(); + return { repo, ws, client }; +} + +/** The last frame without the client-generated id, for an exact shape assertion. */ +function lastFrame(ws) { + const { id, ...frame } = ws.sent.at(-1); + assert.match(id, /^web-\d+$/); + return frame; +} + +test("listTemplates sends exactly {type:'list_templates'} and returns the catalogue", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ + id: frame.id, + type: "templates", + templates: [{ key: "task", name: "Complete a task" }], + }); + + const templates = await repo.listTemplates(); + assert.deepEqual(lastFrame(ws), { type: "list_templates" }); + assert.equal(templates.length, 1); + assert.equal(templates[0].key, "task"); +}); + +test("listTemplates returns [] when the reply carries no templates", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "templates" }); + assert.deepEqual(await repo.listTemplates(), []); +}); + +test("validate sends exactly {type:'validate', source} and returns response.graph", async () => { + const { repo, ws } = connected(); + const graph = { stages: [{ key: "plan" }] }; + ws.reply = (frame) => ({ id: frame.id, type: "validated", graph }); + + const result = await repo.validate("the source"); + assert.deepEqual(lastFrame(ws), { type: "validate", source: "the source" }); + assert.deepEqual(result, graph); +}); + +test("validate rejects a server error envelope with the server's text", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unexpected token" }); + await assert.rejects(() => repo.validate("bad source"), { + name: "ProtocolError", + message: "unexpected token", + }); +}); + +test("validate throws when the reply has no graph", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "validated" }); + await assert.rejects(() => repo.validate("empty"), ProtocolError); +}); diff --git a/web/test/templates.test.mjs b/web/test/templates.test.mjs new file mode 100644 index 00000000..ba98e17b --- /dev/null +++ b/web/test/templates.test.mjs @@ -0,0 +1,87 @@ +// Pure Templates helper tests: wording (singular/plural, placeholders), the +// card mapping and the stage-summary/graph-note derivations. No DOM, no server. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + effectiveStageType, + stageCountText, + templateCard, + templateDetailName, + templateGalleryName, + templateGraphNote, + templateStageCountLabel, + templateStageSummary, + TEMPLATE_GRAPH_NOTE, + TEMPLATE_NO_STAGES_NOTE, + TEMPLATE_UNPARSED_GRAPH_NOTE, + TEMPLATE_UNPARSED_SUMMARY_NOTE, +} from "../src/templates.js"; + +test("stageCountText spells one stage and many stages", () => { + assert.equal(stageCountText(1), "1 stage"); + assert.equal(stageCountText(2), "2 stages"); + assert.equal(stageCountText(0), "0 stages"); +}); + +test("templateStageCountLabel says unavailable for an unknown count, never zero", () => { + assert.equal(templateStageCountLabel(null), "stage count unavailable"); + assert.equal(templateStageCountLabel(undefined), "stage count unavailable"); + assert.equal(templateStageCountLabel(1), "1 stage"); + assert.equal(templateStageCountLabel(3), "3 stages"); +}); + +test("a blank gallery name becomes the unnamed placeholder", () => { + assert.equal(templateGalleryName(""), "(unnamed template)"); + assert.equal(templateGalleryName(" "), "(unnamed template)"); + assert.equal(templateGalleryName("Review a repository"), "Review a repository"); +}); + +test("a blank detail name falls back to the template key", () => { + assert.equal(templateDetailName({ key: "task", name: "" }), "task"); + assert.equal(templateDetailName({ key: "task", name: " " }), "task"); + assert.equal(templateDetailName({ key: "task", name: "Complete a task" }), "Complete a task"); +}); + +test("effectiveStageType defaults a blank type to model", () => { + assert.equal(effectiveStageType(""), "model"); + assert.equal(effectiveStageType(null), "model"); + assert.equal(effectiveStageType(" "), "model"); + assert.equal(effectiveStageType("human"), "human"); +}); + +test("templateCard takes the stage count from the parsed graph, null when absent", () => { + const entry = { key: "task", name: "Complete a task", description: "Do it." }; + assert.equal(templateCard(entry, null).stageCount, null); + assert.equal(templateCard(entry, { stages: [] }).stageCount, 0); + assert.equal(templateCard(entry, { stages: [{ key: "a" }, { key: "b" }] }).stageCount, 2); + assert.deepEqual(templateCard(entry, null), { + key: "task", + name: "Complete a task", + description: "Do it.", + stageCount: null, + }); +}); + +test("templateStageSummary distinguishes unparsed, empty and populated", () => { + assert.deepEqual(templateStageSummary(null), { + note: TEMPLATE_UNPARSED_SUMMARY_NOTE, + stages: [], + }); + assert.deepEqual(templateStageSummary({ stages: [] }), { + note: TEMPLATE_NO_STAGES_NOTE, + stages: [], + }); + + const summary = templateStageSummary({ stages: [{ key: "plan", type: "" }, { key: "review", type: "human" }] }); + assert.equal(summary.note, null); + assert.deepEqual(summary.stages, [ + { key: "plan", type: "model" }, + { key: "review", type: "human" }, + ]); +}); + +test("templateGraphNote picks the unparsed or parsed note", () => { + assert.equal(templateGraphNote(null), TEMPLATE_UNPARSED_GRAPH_NOTE); + assert.equal(templateGraphNote({ stages: [] }), TEMPLATE_GRAPH_NOTE); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index c39dfc6e..0ca34c8d 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -86,6 +86,24 @@ try { await page.waitForSelector(".detail h2", { timeout: 25000 }); shots.push(await page.screenshot(`${out}/03-run-detail.png`)); + step("opening the Templates gallery"); + await page.clickText("nav.tabs button.tab", "Templates"); + await page.waitForSelector(".cards button.card", { timeout: 25000 }); + shots.push(await page.screenshot(`${out}/04-templates-gallery.png`)); + const templateCount = await page.evaluate(`document.querySelectorAll(".cards button.card").length`); + console.log(` templates rendered: ${templateCount}`); + + step("opening a template detail (Summary)"); + await page.click(".cards button.card"); + await page.waitForSelector(".detail .tabstrip", { timeout: 25000 }); + await page.waitForText("Key", { timeout: 25000 }); + shots.push(await page.screenshot(`${out}/05-template-detail-summary.png`)); + + step("opening the template Source tab"); + await page.clickText(".detail .tabstrip button.minitab", "Source"); + await page.waitForText("Definition source", { timeout: 25000 }); + shots.push(await page.screenshot(`${out}/06-template-source.png`)); + console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`); } catch (error) { From 849a18456106adcecc46ab2aa6c0c2de2174ea79 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 02:50:51 +0100 Subject: [PATCH 2/3] web: run history list, filter and sort (R1/R2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Day-grouped run list with sticky day headers (Today / Yesterday / d MMM yyyy / Unknown date), a usage roll-up block, the app's row hierarchy and a bounded filter/sort menu — mirroring RunHistoryScreen.kt, ListFilter.kt and ListSort.kt. New pure helpers live in src/runs.js with focused unit tests; app.js keeps the wiring and sets server strings with textContent. R1 done, R2 partial: no per-row "needs you" mark exists in the Android app; its wording is deferred to R15 (separate attention surface). --- web/PARITY.md | 4 +- web/src/app.js | 382 ++++++++++++++++++++++++++---- web/src/runs.js | 512 +++++++++++++++++++++++++++++++++++++++++ web/styles.css | 185 ++++++++++++++- web/test/runs.test.mjs | 393 +++++++++++++++++++++++++++++++ web/test/ui-smoke.mjs | 173 +++++++++++++- 6 files changed, 1601 insertions(+), 48 deletions(-) create mode 100644 web/src/runs.js create mode 100644 web/test/runs.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index 5df4f4e4..af754d46 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -31,8 +31,8 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu ## Runs | # | Feature | Protocol | Status | | --- | --- | --- | --- | -| R1 | Run history list with status roll-up | `list_runs` | partial (list only) | -| R2 | Filter by status, sort, "needs you" markers | client-side | todo | +| R1 | Run history list with status roll-up | `list_runs` | done | +| R2 | Filter by status, sort, "needs you" markers | client-side | partial (status/pipeline/time filter + sort implemented and captured; the per-row "needs you" mark has no Android counterpart and its wording is deferred to R15, still todo) | | R3 | Run detail: run fields, steps/visits, targets, sessions | `get_run` | partial (fields + steps) | | R4 | Summary tab incl. collapsible **Changes** viewer (raw + rendered diff) | `get_run` file changes | todo | | R5 | Graph tab (per-stage panes, verdicts) | `get_run` | todo | diff --git a/web/src/app.js b/web/src/app.js index 1af401e1..b612314f 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -4,6 +4,26 @@ import { PipelinesClient } from "./client.js"; import { PipelinesRepository } from "./repository.js"; import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.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"; const STORAGE_KEY = "pipelines.web.serverUrl.v2"; @@ -45,10 +65,20 @@ const state = { selectedRunId: null, 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 // --------------------------------------------------------------------------- @@ -181,6 +211,8 @@ function renderContent() { } nodes.push(split); content.replaceChildren(...nodes); + if (state.view === "runs") refreshListClock(); + else stopListClock(); } function tabButton(view, label) { @@ -265,52 +297,294 @@ function renderPipelineDetail() { } 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` }), - ), - ); - } + const pane = h("div", { class: "list runs" }); + pane.append(renderRunToolbar()); + + const scroll = h("div", { class: "run-scroll" }); if (state.loading && !state.runs.length) { - list.append(h("div", { class: "muted pad", text: "Loading…" })); - return list; + scroll.append(h("div", { class: "muted pad", text: "Loading…" })); + pane.append(scroll); + return pane; } - if (!state.runs.length) { - list.append(h("div", { class: "muted pad", text: "No runs." })); - return list; + + 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; + } } - for (const r of state.runs) { - list.append( + 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( - "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, + "span", + { class: "run-row-pipeline" }, + h("span", { class: "run-row-pipeline-name", text: identity.pipeline }), + versionChip(run.version), ), ); } - return list; + + 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() { @@ -509,6 +783,35 @@ function stopRunPoll() { } } +/** + * (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 // --------------------------------------------------------------------------- @@ -523,6 +826,7 @@ client.addEventListener("state", (event) => { } if (next.kind !== "connected" && previousKind === "connected") { stopRunPoll(); + stopListClock(); } render(); }); diff --git a/web/src/runs.js b/web/src/runs.js new file mode 100644 index 00000000..7737f6b5 --- /dev/null +++ b/web/src/runs.js @@ -0,0 +1,512 @@ +// Pure, DOM-free helpers for the runs history list: the status vocabulary, run +// identity, progress/meta wording, filtering, sorting and day grouping. +// +// This mirrors the Android app exactly — ui/screens/RunHistoryScreen.kt, +// screens/ListFilter.kt, screens/ListSort.kt, ui/RunIdentity.kt and ui/Format.kt +// — so the browser list reads the same words in the same order as the app. It is +// deliberately DOM-free: every rule here is unit-testable under `node --test` +// with no browser and no server. app.js keeps the wiring. +// +// Every server-provided string is only ever compared or rendered, never parsed +// as markup; the caller sets it with textContent. + +// --------------------------------------------------------------------------- +// Status vocabulary +// --------------------------------------------------------------------------- + +/** + * The server's own run vocabulary, in the filter's display order + * (internal/pipeline/runs.go: queued/running/waiting/succeeded/failed/canceled/ + * interrupted). The app-only `active` usage bucket, the stage-outcome words + * (`blocked`/`skipped`) and the `unknown` fallback are deliberately not offered + * as run-status filters, mirroring RUN_STATUS_FILTERS. + */ +export const RUN_STATES = [ + "queued", + "running", + "waiting", + "succeeded", + "failed", + "canceled", + "interrupted", +]; + +/** + * Maps a server status or outcome word to its canonical display state, accepting + * the server's vocabulary only (the steps/outcomes synonyms resolve onto the same + * states so one chip set renders list, detail and timeline). Mirrors + * runStateOf: blank or unrecognised input is the safe `unknown` fallback. + */ +export function runStateOf(status) { + switch (String(status ?? "").trim().toLowerCase()) { + case "running": + return "running"; + case "queued": + return "queued"; + case "waiting": + return "waiting"; + case "active": + return "active"; + case "succeeded": + case "success": + case "completed": + case "done": + return "succeeded"; + case "failed": + case "error": + return "failed"; + case "canceled": + case "cancelled": + return "canceled"; + case "interrupted": + return "interrupted"; + case "blocked": + return "blocked"; + case "skipped": + return "skipped"; + default: + return "unknown"; + } +} + +// --------------------------------------------------------------------------- +// Identity, wording and time formatting +// --------------------------------------------------------------------------- + +/** + * The runs list's two identity lines: `label` is the run's primary line and + * `pipeline` is the pipeline the run belongs to, shown as a second line only + * when the label is a stored title. A run with no title falls back to the + * pipeline name as its only line — never a title followed by an empty one. + * Mirrors ui/RunIdentity.kt runIdentity. + */ +export function runIdentity(title, name) { + const stored = String(title ?? "").trim(); + return stored + ? { label: stored, pipeline: String(name ?? "") } + : { label: String(name ?? ""), pipeline: null }; +} + +/** The version chip label, e.g. `v5` (mirrors RunHistoryScreen.VersionChip). */ +export function versionLabel(version) { + return `v${version}`; +} + +/** + * A visit count in the app's one singular/plural spelling (`1 visit` / + * `n visits`), mirroring ui/Format.kt visitCount so the same run is never + * described inconsistently. + */ +export function visitCount(count, adjective) { + const n = Number(count) || 0; + return `${n} ${adjective} ${n === 1 ? "visit" : "visits"}`; +} + +/** Parses an RFC3339 timestamp to epoch millis, or null when blank/unparseable. */ +export function parseInstant(text) { + if (text == null) return null; + const value = String(text).trim(); + if (!value) return null; + const ms = Date.parse(value); + return Number.isNaN(ms) ? null : ms; +} + +/** + * Non-negative whole seconds between two RFC3339 timestamps, or null when either + * is blank/unparseable or the end precedes the start. Mirrors Format.durationSeconds + * (truncating toward zero), so a sort key and the printed duration never disagree. + */ +export function durationSeconds(start, end) { + const from = parseInstant(start); + const to = parseInstant(end); + if (from == null || to == null) return null; + const seconds = Math.trunc((to - from) / 1000); + return seconds >= 0 ? seconds : null; +} + +/** + * Non-negative whole seconds from a [start] RFC3339 timestamp to [nowMillis], or + * null when [start] is blank/unparseable. A future start (clock skew) reads as 0, + * never a negative. Mirrors Format.secondsSince. + */ +export function secondsSince(start, nowMillis) { + const from = parseInstant(start); + if (from == null) return null; + return Math.max(0, Math.trunc((nowMillis - from) / 1000)); +} + +/** + * Human duration for a whole number of seconds: `Ns`, `Nm Ss`, `Hh Mm`. Mirrors + * Format.formatDuration (a negative total renders as `0s`). + */ +export function formatDuration(totalSeconds) { + const seconds = Math.max(0, Math.trunc(Number(totalSeconds) || 0)); + if (seconds < 60) return `${seconds}s`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`; + return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`; +} + +/** + * An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`, + * e.g. `17 Oct 21:26`), or null when blank/unparseable so a caller omits the + * value rather than printing a blank. [options] may carry a `zone` (IANA name) + * and `locale` for deterministic tests; both default to the runtime's. + */ +export function formatLocalTimestamp(instant, options = {}) { + const ms = parseInstant(instant); + if (ms == null) return null; + return formatInZone(ms, options, (parts) => `${parts.day} ${parts.month} ${parts.hour}:${parts.minute}`); +} + +/** The run's calendar day (`YYYY-MM-DD`) in [zone], or null when unparseable. */ +export function localDayKey(value, zone) { + const ms = value instanceof Date ? value.getTime() : parseInstant(value); + if (ms == null || !Number.isFinite(ms)) return null; + try { + const fmt = new Intl.DateTimeFormat("en-CA", { + year: "numeric", + month: "2-digit", + day: "2-digit", + timeZone: zone, + }); + return fmt.format(new Date(ms)); + } catch { + return null; + } +} + +/** + * The day header for a run: `Today`, `Yesterday`, `d MMM yyyy`, or `Unknown date` + * for a blank/unparseable timestamp. [today] may be a day-key string or a Date. + * Mirrors RunHistoryScreen.dayLabel. + */ +export function dayLabel(createdAt, today, zone) { + const key = localDayKey(createdAt, zone); + if (key == null) return "Unknown date"; + const todayKey = typeof today === "string" ? today : localDayKey(today, zone); + if (todayKey == null) return "Unknown date"; + if (key === todayKey) return "Today"; + if (key === addDays(todayKey, -1)) return "Yesterday"; + return formatDayKey(key); +} + +/** + * The runs list's meta line: `run {id} · {local d MMM HH:mm} · {duration}` for a + * finished run, and `run {id} · {live elapsed}` for an executing one (elapsed + * computed from its server start timestamp against [nowMillis]). Mirrors + * RunHistoryScreen.metaText. + */ +export function metaText(run, nowMillis, options = {}) { + const parts = [`run ${run.id}`]; + if (run.executing) { + const elapsed = secondsSince(run.created_at, nowMillis); + if (elapsed != null) parts.push(formatDuration(elapsed)); + } else { + const stamp = formatLocalTimestamp(run.created_at, options); + if (stamp != null) parts.push(stamp); + const duration = durationSeconds(run.created_at, run.finished_at); + if (duration != null) parts.push(formatDuration(duration)); + } + return parts.join(" · "); +} + +/** + * Progress from the fields a summary actually has: an optional resource-wait + * line, completed visits, then the current stage. Mirrors + * RunHistoryScreen.progressText. + */ +export function progressText(run) { + const parts = []; + if (run.resource_wait != null) { + parts.push(`Waiting for resource ${String(run.resource_wait.resource ?? "")}`); + } + parts.push(visitCount(run.completed_steps, "completed")); + const stage = String(run.current_stage ?? "").trim(); + if (stage) parts.push(`stage ${stage}`); + return parts.join(" · "); +} + +// --------------------------------------------------------------------------- +// Filters +// --------------------------------------------------------------------------- + +/** The run-list time windows offered by the filter control. */ +export const RUN_TIME_RANGES = [ + { value: "any_time", label: "Any time" }, + { value: "today", label: "Today" }, + { value: "last_7_days", label: "Last 7 days" }, + { value: "last_30_days", label: "Last 30 days" }, +]; + +export const DEFAULT_TIME_RANGE = "any_time"; + +/** The runs-list filters, each defaulting to "no narrowing". */ +export function defaultRunFilters() { + return { statuses: new Set(), pipelineId: null, timeRange: DEFAULT_TIME_RANGE }; +} + +/** The number of active facets (one per status/pipeline/time choice). */ +export function runFiltersActiveCount(filters) { + return ( + (filters.statuses && filters.statuses.size > 0 ? 1 : 0) + + (filters.pipelineId != null ? 1 : 0) + + (filters.timeRange && filters.timeRange !== DEFAULT_TIME_RANGE ? 1 : 0) + ); +} + +/** True when [run] is in [statuses]; an empty set means "any status". */ +export function runMatchesStatuses(run, statuses) { + if (!statuses || statuses.size === 0) return true; + return statuses.has(runStateOf(run.status)); +} + +/** True when [run] belongs to [pipelineId]; null means "any pipeline". */ +export function runMatchesPipeline(run, pipelineId) { + return pipelineId == null || run.pipeline_id === pipelineId; +} + +/** + * True when [run] falls inside [range] relative to [today]. A blank/unparseable + * timestamp and a future-dated run never match a finite window; `any_time` + * matches everything. The window is inclusive calendar days ending today. + */ +export function runMatchesTimeRange(run, range, today, zone) { + if (!range || range === DEFAULT_TIME_RANGE) return true; + const key = localDayKey(run.created_at, zone); + if (key == null) return false; + const todayKey = typeof today === "string" ? today : localDayKey(today, zone); + if (todayKey == null) return false; + if (key > todayKey) return false; + switch (range) { + case "today": + return key === todayKey; + case "last_7_days": + return key >= addDays(todayKey, -6); + case "last_30_days": + return key >= addDays(todayKey, -29); + default: + return true; + } +} + +/** Every run facet combined with AND. */ +export function runMatchesFilters(run, filters, today, zone) { + return ( + runMatchesStatuses(run, filters.statuses) && + runMatchesPipeline(run, filters.pipelineId) && + runMatchesTimeRange(run, filters.timeRange, today, zone) + ); +} + +/** Narrows [runs] by [filters]; the default filters change nothing. */ +export function filterRuns(runs, filters, today, zone) { + if (runFiltersActiveCount(filters) === 0) return runs; + return (runs ?? []).filter((run) => runMatchesFilters(run, filters, today, zone)); +} + +/** One selectable pipeline in the run filter, named from its runs. */ +export function pipelineFilterOptions(runs) { + const names = new Map(); + for (const run of runs ?? []) { + const current = names.get(run.pipeline_id); + if (current == null || current.trim() === "") names.set(run.pipeline_id, run.name ?? ""); + } + return [...names.entries()] + .map(([id, name]) => ({ id, name: name.trim() === "" ? `Pipeline ${id}` : name })) + .sort((a, b) => caseInsensitiveCompare(a.name, b.name) || a.id - b.id); +} + +// --------------------------------------------------------------------------- +// Sort +// --------------------------------------------------------------------------- + +/** The run-list orderings offered by the sort control. */ +export const RUN_SORTS = [ + { value: "newest_first", label: "Newest first" }, + { value: "oldest_first", label: "Oldest first" }, + { value: "longest_duration", label: "Longest duration" }, + { value: "shortest_duration", label: "Shortest duration" }, + { value: "pipeline_name", label: "Pipeline name" }, + { value: "status", label: "Status" }, +]; + +export const DEFAULT_RUN_SORT = "newest_first"; + +/** + * The pure comparator for [sort]. Every case ends in an explicit id tie-break + * (`id` is unique) so runs that compare equal on the primary key always order + * the same way. A blank/unparseable timestamp and a run with no recorded + * duration (still executing) sort last regardless of direction and never crash. + * Mirrors ListSort.runComparator. + */ +export function runComparator(sort) { + switch (sort) { + case "oldest_first": + return (a, b) => + ascending(instantOr(a.created_at, Infinity), instantOr(b.created_at, Infinity)) || + ascending(a.id, b.id); + case "longest_duration": + return (a, b) => { + const da = durationSeconds(a.created_at, a.finished_at); + const db = durationSeconds(b.created_at, b.finished_at); + return ( + ascending(da == null ? 1 : 0, db == null ? 1 : 0) || + descending(da ?? -Infinity, db ?? -Infinity) || + descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) || + descending(a.id, b.id) + ); + }; + case "shortest_duration": + return (a, b) => { + const da = durationSeconds(a.created_at, a.finished_at); + const db = durationSeconds(b.created_at, b.finished_at); + return ( + ascending(da == null ? 1 : 0, db == null ? 1 : 0) || + ascending(da ?? Infinity, db ?? Infinity) || + descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) || + descending(a.id, b.id) + ); + }; + case "pipeline_name": + return (a, b) => + caseInsensitiveCompare(a.name, b.name) || + descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) || + descending(a.id, b.id); + case "status": + return (a, b) => + caseInsensitiveCompare(a.status, b.status) || + descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) || + descending(a.id, b.id); + case "newest_first": + default: + return (a, b) => + descending(instantOr(a.created_at, -Infinity), instantOr(b.created_at, -Infinity)) || + descending(a.id, b.id); + } +} + +/** Orders [runs] by [sort], returning a new array. */ +export function sortRuns(runs, sort) { + return [...(runs ?? [])].sort(runComparator(sort)); +} + +// --------------------------------------------------------------------------- +// Day grouping and the list's slots +// --------------------------------------------------------------------------- + +/** + * Groups runs by calendar day in [zone], preserving the order [order] puts them + * in and the order within a day. A blank/unparseable timestamp gets a safe + * "Unknown date" group. Mirrors RunHistoryScreen.groupRunsByDay. + */ +export function groupRunsByDay(runs, today, zone, order = runComparator(DEFAULT_RUN_SORT)) { + const groups = new Map(); + for (const run of [...(runs ?? [])].sort(order)) { + const label = dayLabel(run.created_at, today, zone); + if (!groups.has(label)) groups.set(label, []); + groups.get(label).push(run); + } + return [...groups.entries()].map(([label, list]) => ({ label, runs: list })); +} + +export const NO_RUNS_MESSAGE = "No runs have been recorded yet."; +export const NO_MATCH_MESSAGE = "No runs match the current filters."; +export const CLEAR_FILTERS_LABEL = "Clear filters"; + +/** + * The runs list's slots in layout order: the usage block when there is one, then + * either the single empty line (nothing recorded, or nothing matching the + * filters) or the day groups, then the inline error row. Pure and single-sourced + * with the renderer, so its size is exactly the list's entry count. Mirrors + * RunHistoryScreen.runListEntries. + */ +export function runListEntries(usage, nothingRecorded, nothingMatched, groups, error) { + const entries = []; + if (usage != null) entries.push({ kind: "usage", key: "usage", usage }); + if (nothingRecorded) { + entries.push({ kind: "empty", key: "runs-empty", message: NO_RUNS_MESSAGE, actionLabel: null }); + } else if (nothingMatched) { + entries.push({ + kind: "empty", + key: "runs-filtered-empty", + message: NO_MATCH_MESSAGE, + actionLabel: CLEAR_FILTERS_LABEL, + }); + } else { + for (const group of groups ?? []) { + entries.push({ kind: "day", key: `day-${group.label}`, label: group.label }); + for (const run of group.runs) entries.push({ kind: "run", key: `run-${run.id}`, run }); + } + } + if (error) entries.push({ kind: "error", key: "runs-error", message: error }); + return entries; +} + +// --------------------------------------------------------------------------- +// Internals +// --------------------------------------------------------------------------- + +/** Ascending compare of two numbers/strings, safe on the -Infinity sentinels. */ +function ascending(x, y) { + if (x < y) return -1; + if (x > y) return 1; + return 0; +} + +/** Descending compare: the larger value sorts first. */ +function descending(x, y) { + return ascending(y, x); +} + +function instantOr(iso, fallback) { + const ms = parseInstant(iso); + return ms == null ? fallback : ms; +} + +function caseInsensitiveCompare(a, b) { + const left = String(a ?? "").toLowerCase(); + const right = String(b ?? "").toLowerCase(); + if (left < right) return -1; + if (left > right) return 1; + return 0; +} + +/** `dayKey` shifted by [days] calendar days (keys are `YYYY-MM-DD`). */ +function addDays(dayKey, days) { + const [year, month, day] = dayKey.split("-").map(Number); + const shifted = new Date(Date.UTC(year, month - 1, day) + days * 86400000); + return `${shifted.getUTCFullYear()}-${pad2(shifted.getUTCMonth() + 1)}-${pad2(shifted.getUTCDate())}`; +} + +function pad2(value) { + return String(value).padStart(2, "0"); +} + +function formatDayKey(dayKey) { + const [year, month, day] = dayKey.split("-").map(Number); + const parts = zoneParts(Date.UTC(year, month - 1, day), "UTC", "en-GB"); + return `${parts.day} ${parts.month} ${parts.year}`; +} + +function formatInZone(ms, options, assemble) { + const parts = zoneParts(ms, options.zone, options.locale); + return parts ? assemble(parts) : null; +} + +/** The named parts of `ms` in [zone], or null when the zone is unusable. */ +function zoneParts(ms, zone, locale) { + try { + const fmt = new Intl.DateTimeFormat(locale ?? "en-GB", { + day: "numeric", + month: "short", + year: "numeric", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + timeZone: zone, + }); + return Object.fromEntries(fmt.formatToParts(new Date(ms)).map((part) => [part.type, part.value])); + } catch { + return null; + } +} diff --git a/web/styles.css b/web/styles.css index f753f440..bf3e21d3 100644 --- a/web/styles.css +++ b/web/styles.css @@ -95,9 +95,6 @@ button.ghost { background: transparent; } .row-head { display: flex; gap: 8px; justify-content: space-between; align-items: center; } .row-title { font-weight: 600; } .row-meta { display: block; color: var(--muted); font-size: 12px; margin-top: 2px; } -.row-diag { display: block; color: var(--warn); font-size: 12px; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } - -.usage { display: flex; gap: 12px; padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 12px; } .detail { padding: 16px; } .detail h2 { margin: 0 0 12px; display: flex; gap: 10px; align-items: center; } @@ -120,9 +117,17 @@ button.ghost { background: transparent; } .artifacts a { color: var(--accent); margin-right: 10px; } .chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; border: 1px solid var(--border); color: var(--muted); } -.chip-running, .chip-queued { color: var(--warn); border-color: var(--warn); } +/* The app-owned status hues (RunStatusPalette): status is never colour-only, + every chip still carries its own label. */ +.chip-running, .chip-active { color: #7fb2f0; border-color: #7fb2f0; } +.chip-waiting { color: #8edff5; border-color: #8edff5; } .chip-succeeded { color: var(--ok); border-color: var(--ok); } .chip-failed { color: var(--bad); border-color: var(--bad); } +.chip-canceled { color: #889391; border-color: #889391; } +.chip-interrupted { color: var(--warn); border-color: var(--warn); } +.chip-queued { color: #9aa6a2; border-color: #9aa6a2; } +.chip-blocked { color: #f0a35e; border-color: #f0a35e; } +.chip-skipped { color: #a8b8c8; border-color: #a8b8c8; } .dot::before { content: "●"; margin-right: 6px; } .dot.ok::before { color: var(--ok); } @@ -142,3 +147,175 @@ button.ghost { background: transparent; } .banner.error { background: #2c1616; color: var(--bad); } code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-size: 12px; } + +/* --------------------------------------------------------------------------- + Runs history: toolbar, filter/sort menus, usage roll-up, sticky day headers + and the run rows. Hand-written, dark palette, no framework. + --------------------------------------------------------------------------- */ + +.list.runs { + display: flex; + flex-direction: column; + /* The filter/sort menus hang below the toolbar; keep them unclipped so their + bounded, scrollable box can be reached over the rows beneath. */ + overflow: visible; +} + +.run-toolbar { + display: flex; + gap: 8px; + align-items: center; + padding: 8px 12px; + border-bottom: 1px solid var(--border); +} +.run-toolbar .spacer { flex: 1; } +.run-toolbar button.ghost { padding: 4px 10px; font-size: 12px; } +.filter-btn.active { border-color: var(--accent); color: var(--accent); } + +.menu-anchor { position: relative; } +.menu { + position: absolute; + top: calc(100% + 4px); + left: 0; + z-index: 6; + min-width: 210px; + /* The filter menu lists every pipeline, so with a busy history it is taller + than the viewport. Bound it to the viewport and scroll it in place: every + section (Status, Pipeline, Time range) and the Clear filters/Done actions + stay reachable instead of being clipped off-screen. */ + max-height: min(70vh, 600px); + overflow-y: auto; + overscroll-behavior: contain; + padding: 6px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 10px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45); + display: grid; + gap: 2px; +} +.menu-section { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--muted); + padding: 6px 8px 2px; +} +.menu-divider { height: 1px; background: var(--border); margin: 6px 0; } +.menu-actions { display: flex; justify-content: space-between; gap: 8px; margin-top: 6px; } +.menu-actions button { padding: 4px 8px; font-size: 12px; } +.menu-item { + display: block; + width: 100%; + text-align: left; + border: 0; + background: transparent; + padding: 6px 8px; + border-radius: 6px; + font-size: 13px; +} +.menu-item:hover { background: var(--surface); } +.menu-item.selected { color: var(--accent); } + +.filter-check { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + padding: 4px 8px; + border-radius: 6px; + font-size: 13px; + cursor: pointer; +} +/* Pipeline names can be long; keep each option on one line inside the bounded + menu width rather than wrapping to two or three lines. */ +.filter-check span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.filter-check:hover { background: var(--surface); } +.filter-check input { accent-color: var(--accent); } +.filter-menu { min-width: 240px; max-width: 340px; grid-template-columns: minmax(0, 1fr); } + +/* The list body is the scroll container so the day headers can stick to its top + without depending on the (wrapping) top bar's height. */ +.run-scroll { + max-height: calc(100vh - 210px); + overflow-y: auto; +} + +.metrics { + display: flex; + flex-wrap: wrap; + gap: 20px; + padding: 12px 16px; + border-bottom: 1px solid var(--border); +} +.metric { display: flex; flex-direction: column; min-width: 56px; } +.metric-value { font-size: 18px; font-weight: 600; line-height: 1.2; } +.metric-label { font-size: 11px; color: var(--muted); } +.metric-succeeded .metric-value { color: var(--ok); } +.metric-failed .metric-value { color: var(--bad); } +.metric-canceled .metric-value { color: #889391; } +.metric-interrupted .metric-value { color: var(--warn); } +.metric-active .metric-value { color: #7fb2f0; } + +.day-header { + position: sticky; + top: 0; + z-index: 1; + padding: 7px 16px; + background: var(--surface); + border-bottom: 1px solid var(--border); + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--muted); +} + +.run-row { display: block; padding: 10px 14px; } +.run-row-head { display: flex; align-items: center; gap: 8px; } +.run-row-title { flex: 1; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.run-row-pipeline { display: flex; align-items: center; gap: 8px; margin-top: 2px; color: var(--muted); font-size: 12px; } +.run-row-pipeline-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.run-row-progress, +.run-row-meta, +.run-row-diag { + display: block; + margin-top: 2px; + color: var(--muted); + font-size: 12px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.run-row-diag.error { color: var(--bad); } + +.version-chip { + flex: none; + padding: 0 7px; + border-radius: 999px; + border: 1px solid var(--border); + background: var(--surface-2); + color: var(--muted); + font-size: 11px; +} + +.spinner { + flex: none; + width: 12px; + height: 12px; + border: 2px solid var(--border); + border-top-color: #7fb2f0; + border-radius: 50%; + display: inline-block; + animation: spin 0.8s linear infinite; +} +@keyframes spin { to { transform: rotate(360deg); } } + +.empty-state { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 10px; + padding: 16px; + color: var(--muted); +} +.run-list-error { padding: 12px 16px; color: var(--bad); } diff --git a/web/test/runs.test.mjs b/web/test/runs.test.mjs new file mode 100644 index 00000000..ee7bce32 --- /dev/null +++ b/web/test/runs.test.mjs @@ -0,0 +1,393 @@ +// Pure unit tests for the runs-list helpers: filtering (status/pipeline/time, +// AND-combined), every sort comparator with its id tie-break, day grouping, +// the wording helpers and the list's slot model. No server, no DOM. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + RUN_STATES, + RUN_TIME_RANGES, + RUN_SORTS, + runStateOf, + runIdentity, + versionLabel, + visitCount, + progressText, + metaText, + formatDuration, + secondsSince, + durationSeconds, + localDayKey, + dayLabel, + defaultRunFilters, + runFiltersActiveCount, + runMatchesTimeRange, + filterRuns, + pipelineFilterOptions, + runComparator, + sortRuns, + groupRunsByDay, + runListEntries, + NO_RUNS_MESSAGE, + NO_MATCH_MESSAGE, +} from "../src/runs.js"; + +/** A finished run on the Today of the tests, with every field the list reads. */ +function run(overrides = {}) { + return { + id: 1, + pipeline_id: 1, + name: "Pipe", + title: null, + version: 1, + status: "succeeded", + executing: false, + current_stage: "", + completed_steps: 0, + created_at: "2026-10-19T10:00:00Z", + finished_at: "2026-10-19T10:01:00Z", + diagnostic: "", + resource_wait: null, + ...overrides, + }; +} + +const TODAY = "2026-10-19"; +const ZONE = "UTC"; +const TIME_OPTS = { zone: ZONE, locale: "en-GB" }; + +// --------------------------------------------------------------------------- +// Vocabulary and wording +// --------------------------------------------------------------------------- + +test("runStateOf maps the server vocabulary and the outcome synonyms", () => { + assert.equal(runStateOf("running"), "running"); + assert.equal(runStateOf("succeeded"), "succeeded"); + assert.equal(runStateOf("success"), "succeeded"); + assert.equal(runStateOf("completed"), "succeeded"); + assert.equal(runStateOf("done"), "succeeded"); + assert.equal(runStateOf("error"), "failed"); + assert.equal(runStateOf("cancelled"), "canceled"); + assert.equal(runStateOf(" INTERRUPTED "), "interrupted"); + assert.equal(runStateOf(""), "unknown"); + assert.equal(runStateOf("nonsense"), "unknown"); +}); + +test("RUN_STATES is exactly the server run vocabulary in display order", () => { + assert.deepEqual(RUN_STATES, [ + "queued", + "running", + "waiting", + "succeeded", + "failed", + "canceled", + "interrupted", + ]); +}); + +test("runIdentity falls back to the pipeline name and only splits when titled", () => { + assert.deepEqual(runIdentity(" Fix the thing ", "Plan and land"), { + label: "Fix the thing", + pipeline: "Plan and land", + }); + assert.deepEqual(runIdentity(null, "Plan and land"), { label: "Plan and land", pipeline: null }); + assert.deepEqual(runIdentity(" ", "Plan and land"), { label: "Plan and land", pipeline: null }); +}); + +test("versionLabel and visitCount use the app's singular/plural spelling", () => { + assert.equal(versionLabel(5), "v5"); + assert.equal(visitCount(1, "completed"), "1 completed visit"); + assert.equal(visitCount(0, "completed"), "0 completed visits"); + assert.equal(visitCount(3, "completed"), "3 completed visits"); +}); + +test("progressText carries resource wait, completed visits and the stage", () => { + assert.equal( + progressText(run({ completed_steps: 2, current_stage: "implementer" })), + "2 completed visits · stage implementer", + ); + assert.equal( + progressText( + run({ completed_steps: 1, current_stage: "reviewer", resource_wait: { resource: "pixel-9" } }), + ), + "Waiting for resource pixel-9 · 1 completed visit · stage reviewer", + ); + assert.equal(progressText(run({ completed_steps: 0 })), "0 completed visits"); +}); + +test("metaText shows a live elapsed while executing and id/start/duration at rest", () => { + const executing = run({ + id: 7, + executing: true, + created_at: "2026-10-19T09:30:00Z", + finished_at: "", + }); + assert.equal(metaText(executing, Date.parse("2026-10-19T09:31:05Z"), TIME_OPTS), "run 7 · 1m 5s"); + // A future start (clock skew) reads as 0s, never a negative. + assert.equal(metaText(executing, Date.parse("2026-10-19T09:00:00Z"), TIME_OPTS), "run 7 · 0s"); + + const done = run({ + id: 7, + created_at: "2026-10-19T09:30:00Z", + finished_at: "2026-10-19T09:32:05Z", + }); + assert.equal(metaText(done, 0, TIME_OPTS), "run 7 · 19 Oct 09:30 · 2m 5s"); +}); + +test("formatDuration, secondsSince and durationSeconds mirror Format.kt", () => { + assert.equal(formatDuration(0), "0s"); + assert.equal(formatDuration(59), "59s"); + assert.equal(formatDuration(60), "1m 0s"); + assert.equal(formatDuration(125), "2m 5s"); + assert.equal(formatDuration(3725), "1h 2m"); + assert.equal(formatDuration(-5), "0s"); + + assert.equal(secondsSince("2026-10-19T09:30:00Z", Date.parse("2026-10-19T09:31:05Z")), 65); + assert.equal(secondsSince("bad", 0), null); + assert.equal(durationSeconds("2026-10-19T09:30:00Z", "2026-10-19T09:32:05Z"), 125); + assert.equal(durationSeconds("2026-10-19T09:32:05Z", "2026-10-19T09:30:00Z"), null); + assert.equal(durationSeconds("", ""), null); +}); + +// --------------------------------------------------------------------------- +// Filters +// --------------------------------------------------------------------------- + +test("default filters change nothing and count as zero active facets", () => { + const runs = [run({ id: 1 }), run({ id: 2, status: "failed" })]; + const filters = defaultRunFilters(); + assert.equal(runFiltersActiveCount(filters), 0); + assert.equal(filterRuns(runs, filters, TODAY, ZONE), runs); +}); + +test("status filter narrows to the selected states; an empty set is any status", () => { + const runs = [ + run({ id: 1, status: "succeeded" }), + run({ id: 2, status: "failed" }), + run({ id: 3, status: "canceled" }), + ]; + const filters = { ...defaultRunFilters(), statuses: new Set(["failed"]) }; + assert.deepEqual( + filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id), + [2], + ); + // "success" resolves to the succeeded state, so selecting it matches. + const succeeded = { ...defaultRunFilters(), statuses: new Set(["succeeded"]) }; + assert.deepEqual( + filterRuns([run({ id: 9, status: "success" })], succeeded, TODAY, ZONE).map((r) => r.id), + [9], + ); + assert.equal(runFiltersActiveCount(filters), 1); +}); + +test("pipeline filter is a single-select; null means any pipeline", () => { + const runs = [run({ id: 1, pipeline_id: 3 }), run({ id: 2, pipeline_id: 4 })]; + const filters = { ...defaultRunFilters(), pipelineId: 4 }; + assert.deepEqual( + filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id), + [2], + ); + assert.equal(runFiltersActiveCount(filters), 1); +}); + +test("time range is inclusive calendar days ending today and rejects future/blank", () => { + const at = (created_at) => run({ created_at }); + assert.equal(runMatchesTimeRange(at("2026-10-19T00:00:00Z"), "today", TODAY, ZONE), true); + assert.equal(runMatchesTimeRange(at("2026-10-18T23:59:59Z"), "today", TODAY, ZONE), false); + // last 7 days covers today and the six days before it (>= 13 Oct). + assert.equal(runMatchesTimeRange(at("2026-10-13T00:00:00Z"), "last_7_days", TODAY, ZONE), true); + assert.equal(runMatchesTimeRange(at("2026-10-12T23:00:00Z"), "last_7_days", TODAY, ZONE), false); + // last 30 days covers >= 20 Sep. + assert.equal(runMatchesTimeRange(at("2026-09-20T00:00:00Z"), "last_30_days", TODAY, ZONE), true); + assert.equal(runMatchesTimeRange(at("2026-09-19T00:00:00Z"), "last_30_days", TODAY, ZONE), false); + // A future-dated run and a blank/unparseable timestamp never match a window. + assert.equal(runMatchesTimeRange(at("2026-10-20T00:00:00Z"), "today", TODAY, ZONE), false); + assert.equal(runMatchesTimeRange(at("not-a-date"), "today", TODAY, ZONE), false); + assert.equal(runMatchesTimeRange(at(""), "last_30_days", TODAY, ZONE), false); + // Any time matches everything, including blank. + assert.equal(runMatchesTimeRange(at(""), "any_time", TODAY, ZONE), true); +}); + +test("the three facets AND-combine and the count is one per facet", () => { + const runs = [ + run({ id: 1, pipeline_id: 3, status: "failed", created_at: "2026-10-19T10:00:00Z" }), + run({ id: 2, pipeline_id: 3, status: "succeeded", created_at: "2026-10-19T10:00:00Z" }), + run({ id: 3, pipeline_id: 4, status: "failed", created_at: "2026-10-19T10:00:00Z" }), + run({ id: 4, pipeline_id: 3, status: "failed", created_at: "2026-08-01T10:00:00Z" }), + ]; + const filters = { + statuses: new Set(["failed"]), + pipelineId: 3, + timeRange: "last_7_days", + }; + assert.equal(runFiltersActiveCount(filters), 3); + assert.deepEqual( + filterRuns(runs, filters, TODAY, ZONE).map((r) => r.id), + [1], + ); +}); + +test("pipelineFilterOptions names each pipeline from its newest non-blank run and sorts by name then id", () => { + const options = pipelineFilterOptions([ + run({ pipeline_id: 5, name: "beta" }), + run({ pipeline_id: 5, name: "" }), + run({ pipeline_id: 2, name: "Alpha" }), + run({ pipeline_id: 9, name: "" }), + ]); + assert.deepEqual(options, [ + { id: 2, name: "Alpha" }, + { id: 5, name: "beta" }, + { id: 9, name: "Pipeline 9" }, + ]); +}); + +// --------------------------------------------------------------------------- +// Sort: every comparator plus an id tie-break +// --------------------------------------------------------------------------- + +test("newest first orders by start descending, then id descending", () => { + const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" }); + const b = run({ id: 2, created_at: "2026-10-19T10:00:00Z" }); + const c = run({ id: 3, created_at: "2026-10-19T11:00:00Z" }); + assert.deepEqual( + sortRuns([a, b, c], "newest_first").map((r) => r.id), + [3, 2, 1], + ); +}); + +test("oldest first orders by start ascending, then id ascending", () => { + const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" }); + const b = run({ id: 2, created_at: "2026-10-19T10:00:00Z" }); + const c = run({ id: 3, created_at: "2026-10-19T11:00:00Z" }); + assert.deepEqual( + sortRuns([a, b, c], "oldest_first").map((r) => r.id), + [1, 2, 3], + ); +}); + +test("longest duration puts a missing duration last, then duration desc, created desc, id desc", () => { + const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z", finished_at: "2026-10-19T10:05:00Z" }); // 300 + const b = run({ id: 2, executing: true, created_at: "2026-10-19T10:00:00Z", finished_at: "" }); // null + const c = run({ id: 3, created_at: "2026-10-19T09:00:00Z", finished_at: "2026-10-19T09:10:00Z" }); // 600 + const d = run({ id: 4, created_at: "2026-10-19T08:00:00Z", finished_at: "2026-10-19T08:05:00Z" }); // 300 + assert.deepEqual( + sortRuns([a, b, c, d], "longest_duration").map((r) => r.id), + [3, 1, 4, 2], + ); +}); + +test("shortest duration puts a missing duration last, then duration asc, created desc, id desc", () => { + const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z", finished_at: "2026-10-19T10:05:00Z" }); // 300 + const b = run({ id: 2, executing: true, created_at: "2026-10-19T10:00:00Z", finished_at: "" }); // null + const c = run({ id: 3, created_at: "2026-10-19T09:00:00Z", finished_at: "2026-10-19T09:10:00Z" }); // 600 + const d = run({ id: 4, created_at: "2026-10-19T08:00:00Z", finished_at: "2026-10-19T08:05:00Z" }); // 300 + assert.deepEqual( + sortRuns([a, b, c, d], "shortest_duration").map((r) => r.id), + [1, 4, 3, 2], + ); +}); + +test("pipeline name sorts case-insensitively, then created desc, id desc", () => { + const x = run({ id: 1, name: "beta", created_at: "2026-10-19T10:00:00Z" }); + const y = run({ id: 2, name: "Alpha", created_at: "2026-10-19T10:00:00Z" }); + const z = run({ id: 3, name: "alpha", created_at: "2026-10-19T11:00:00Z" }); + assert.deepEqual( + sortRuns([x, y, z], "pipeline_name").map((r) => r.id), + [3, 2, 1], + ); +}); + +test("status sorts case-insensitively, then created desc, id desc", () => { + const p = run({ id: 1, status: "succeeded", created_at: "2026-10-19T10:00:00Z" }); + const q = run({ id: 2, status: "failed", created_at: "2026-10-19T10:00:00Z" }); + const r = run({ id: 3, status: "failed", created_at: "2026-10-19T11:00:00Z" }); + assert.deepEqual( + sortRuns([p, q, r], "status").map((r) => r.id), + [3, 2, 1], + ); +}); + +test("an unknown sort falls back to newest first", () => { + const a = run({ id: 1, created_at: "2026-10-19T10:00:00Z" }); + const b = run({ id: 2, created_at: "2026-10-19T11:00:00Z" }); + assert.deepEqual( + sortRuns([a, b], "not_a_sort").map((r) => r.id), + [2, 1], + ); +}); + +test("RUN_SORTS and RUN_TIME_RANGES carry the app's exact labels", () => { + assert.deepEqual( + RUN_SORTS.map((s) => s.label), + ["Newest first", "Oldest first", "Longest duration", "Shortest duration", "Pipeline name", "Status"], + ); + assert.deepEqual( + RUN_TIME_RANGES.map((r) => r.label), + ["Any time", "Today", "Last 7 days", "Last 30 days"], + ); +}); + +// --------------------------------------------------------------------------- +// Day grouping +// --------------------------------------------------------------------------- + +test("dayLabel renders Today / Yesterday / d MMM yyyy / Unknown date", () => { + assert.equal(dayLabel("2026-10-19T01:00:00Z", TODAY, ZONE), "Today"); + assert.equal(dayLabel("2026-10-18T23:00:00Z", TODAY, ZONE), "Yesterday"); + assert.equal(dayLabel("2026-10-16T23:00:00Z", TODAY, ZONE), "16 Oct 2026"); + assert.equal(dayLabel("", TODAY, ZONE), "Unknown date"); + assert.equal(dayLabel("not-a-date", TODAY, ZONE), "Unknown date"); + assert.equal(localDayKey("2026-10-19T01:00:00Z", ZONE), "2026-10-19"); + assert.equal(localDayKey("", ZONE), null); +}); + +test("groupRunsByDay follows the sort order and preserves it within a day", () => { + const r1 = run({ id: 1, created_at: "2026-10-19T10:00:00Z" }); + const r2 = run({ id: 2, created_at: "2026-10-19T09:00:00Z" }); + const r3 = run({ id: 3, created_at: "2026-10-18T12:00:00Z" }); + const r4 = run({ id: 4, created_at: "" }); + const groups = groupRunsByDay([r2, r1, r4, r3], TODAY, ZONE, runComparator("newest_first")); + assert.deepEqual( + groups.map((g) => g.label), + ["Today", "Yesterday", "Unknown date"], + ); + assert.deepEqual( + groups[0].runs.map((r) => r.id), + [1, 2], + ); +}); + +// --------------------------------------------------------------------------- +// The list's slots +// --------------------------------------------------------------------------- + +test("runListEntries orders usage, the empty state, groups and the inline error", () => { + const usage = { total: 3 }; + const recorded = runListEntries(usage, true, true, [], null); + assert.deepEqual( + recorded.map((e) => e.kind), + ["usage", "empty"], + ); + assert.equal(recorded[1].message, NO_RUNS_MESSAGE); + assert.equal(recorded[1].actionLabel, null); + + const matched = runListEntries(null, false, true, [], "boom"); + assert.deepEqual( + matched.map((e) => e.kind), + ["empty", "error"], + ); + assert.equal(matched[0].message, NO_MATCH_MESSAGE); + assert.equal(matched[0].actionLabel, "Clear filters"); + + const groups = [{ label: "Today", runs: [run({ id: 1 }), run({ id: 2 })] }]; + const body = runListEntries(null, false, false, groups, null); + assert.deepEqual( + body.map((e) => e.kind), + ["day", "run", "run"], + ); + assert.equal(body[0].label, "Today"); + assert.deepEqual( + body.filter((e) => e.kind === "run").map((e) => e.run.id), + [1, 2], + ); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index c39dfc6e..74ff5095 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -79,10 +79,177 @@ try { await page.waitForSelector(".detail h2"); shots.push(await page.screenshot(`${out}/02-pipeline-detail.png`)); - step("switching to Runs and opening a run detail"); + step("switching to Runs: day-grouped list + usage roll-up"); await page.clickText("nav.tabs button.tab", "Runs"); - await page.waitForSelector(".list button.row", { timeout: 25000 }); - await page.click(".list button.row"); + await page.waitForSelector(".list.runs .day-header", { timeout: 25000 }); + await page.waitForSelector(".metrics .metric", { timeout: 25000 }); + const usageLabels = await page.evaluate( + `[...document.querySelectorAll(".metrics .metric-label")].map((n) => n.textContent)`, + ); + for (const label of ["Total", "Succeeded", "Failed", "Canceled", "Interrupted", "Active"]) { + if (!usageLabels.includes(label)) throw new Error(`usage metric missing: ${label}`); + } + const dayHeaders = await page.evaluate( + `[...document.querySelectorAll(".list.runs .day-header")].map((n) => n.textContent)`, + ); + if (!dayHeaders.length) throw new Error("no day header rendered"); + if (!dayHeaders.includes("Today")) { + throw new Error(`the list does not start with Today: ${dayHeaders.join(" | ")}`); + } + const fullDateHeader = dayHeaders.find((label) => /^\d{1,2} \w{3} \d{4}$/.test(label)); + if (!fullDateHeader) throw new Error(`no full-date day header: ${dayHeaders.join(" | ")}`); + shots.push(await page.screenshot(`${out}/04-runs-day-groups.png`)); + console.log(` usage: ${usageLabels.join(", ")}`); + console.log(` day headers: ${dayHeaders.slice(0, 3).join(" | ")}`); + + step(`scrolling the list to the older day group (${fullDateHeader})`); + const scrolledTo = await page.evaluate(`(() => { + const scroll = document.querySelector(".run-scroll"); + const header = [...document.querySelectorAll(".list.runs .day-header")] + .find((n) => /^\\d{1,2} \\w{3} \\d{4}$/.test(n.textContent)); + if (!scroll || !header) return null; + scroll.scrollTop += header.getBoundingClientRect().top - scroll.getBoundingClientRect().top; + return header.textContent; + })()`); + if (!scrolledTo) throw new Error("could not scroll to the older day group"); + shots.push(await page.screenshot(`${out}/07-runs-older-day-group.png`)); + console.log(` scrolled to: ${scrolledTo}`); + + step("opening the filter menu: it must stay in the viewport and be reachable"); + await page.click("#runFilterBtn"); + await page.waitForSelector("#runFilterMenu"); + const menuLabels = await page.evaluate( + `[...document.querySelectorAll("#runFilterMenu .filter-check span")].map((n) => n.textContent)`, + ); + for (const label of [ + "queued", + "running", + "waiting", + "succeeded", + "failed", + "canceled", + "interrupted", + "Any pipeline", + "Any time", + "Today", + "Last 7 days", + "Last 30 days", + ]) { + if (!menuLabels.includes(label)) throw new Error(`filter menu missing: ${label}`); + } + const menuActions = await page.evaluate( + `[...document.querySelectorAll("#runFilterMenu .menu-actions button")].map((n) => n.textContent)`, + ); + for (const label of ["Clear filters", "Done"]) { + if (!menuActions.includes(label)) throw new Error(`filter menu action missing: ${label}`); + } + // The gate is reachability, not DOM presence: with a busy history the menu is + // taller than the viewport, so it must be bounded and scroll its own box rather + // than being clipped by an ancestor with no way for a user to reach the actions. + const reach = await page.evaluate(`(() => { + const menu = document.querySelector("#runFilterMenu"); + const overflowY = getComputedStyle(menu).overflowY; + const rect = menu.getBoundingClientRect(); + menu.scrollTop = menu.scrollHeight; + const actions = menu.querySelector(".menu-actions").getBoundingClientRect(); + return { + overflowY, + height: Math.round(rect.height), + viewport: window.innerHeight, + fitsViewport: rect.height <= window.innerHeight && rect.bottom <= window.innerHeight + 1, + actionsReachable: actions.bottom <= window.innerHeight + 1 && actions.top >= -1, + }; + })()`); + if (reach.overflowY !== "auto" && reach.overflowY !== "scroll") { + throw new Error(`the filter menu does not scroll its own box: overflow-y=${reach.overflowY}`); + } + if (!reach.fitsViewport) { + throw new Error(`the filter menu overflows the viewport: ${JSON.stringify(reach)}`); + } + if (!reach.actionsReachable) { + throw new Error(`the filter menu actions are unreachable: ${JSON.stringify(reach)}`); + } + shots.push(await page.screenshot(`${out}/08-runs-filter-menu.png`)); + console.log(` filter menu ${reach.height}px tall in a ${reach.viewport}px viewport; actions reachable`); + + step("applying a status filter"); + await page.evaluate( + `document.querySelector('#runFilterMenu input[data-status="failed"]').click()`, + ); + const filterLabel = await page.evaluate(`document.querySelector("#runFilterBtn").textContent`); + if (!filterLabel.includes("(1)")) { + throw new Error(`filter control is missing the active count: ${filterLabel}`); + } + await page.click("#runFilterBtn"); // close the menu so the list is unobstructed + const filteredChips = await page.evaluate( + `[...document.querySelectorAll(".list.runs .run-row .run-row-head .chip")].map((n) => n.textContent)`, + ); + if (!filteredChips.length) throw new Error("the status filter produced no rows"); + if (!filteredChips.every((chip) => chip === "failed")) { + throw new Error(`filtered rows are not all failed: ${filteredChips.join(",")}`); + } + shots.push(await page.screenshot(`${out}/05-runs-filtered.png`)); + console.log(` filtered rows: ${filteredChips.length}, all failed`); + + step("filtering to a state with no runs: the filtered-empty state + Clear filters"); + await page.click("#runFilterBtn"); + await page.waitForSelector("#runFilterMenu"); + await page.evaluate( + `document.querySelector('#runFilterMenu input[data-status="failed"]').click()`, + ); + await page.evaluate( + `document.querySelector('#runFilterMenu input[data-status="interrupted"]').click()`, + ); + await page.click("#runFilterBtn"); // close the menu to see the list + await page.waitForSelector(".list.runs .empty-state"); + const emptyMessage = await page.evaluate( + `document.querySelector(".list.runs .empty-state span")?.textContent ?? ""`, + ); + if (emptyMessage !== "No runs match the current filters.") { + throw new Error(`unexpected filtered-empty message: ${emptyMessage}`); + } + const clearAction = await page.evaluate( + `document.querySelector(".list.runs .empty-state button")?.textContent ?? null`, + ); + if (clearAction !== "Clear filters") { + throw new Error(`the filtered-empty state should offer Clear filters, got: ${clearAction}`); + } + shots.push(await page.screenshot(`${out}/09-runs-filtered-empty.png`)); + console.log(` empty state: ${emptyMessage} (+ ${clearAction})`); + + step("clearing the filters from the empty state and changing the sort"); + await page.click(".list.runs .empty-state button"); + await page.waitForSelector(".list.runs .day-header", { timeout: 25000 }); + const resetLabel = await page.evaluate(`document.querySelector("#runFilterBtn").textContent`); + if (resetLabel.includes("(")) throw new Error(`Clear filters did not reset the count: ${resetLabel}`); + await page.click("#runSortBtn"); + await page.waitForSelector("#runSortMenu"); + const sortItems = await page.evaluate( + `[...document.querySelectorAll("#runSortMenu .menu-item")].map((n) => n.textContent)`, + ); + for (const label of [ + "Newest first", + "Oldest first", + "Longest duration", + "Shortest duration", + "Pipeline name", + "Status", + "Reset", + ]) { + if (!sortItems.includes(label)) throw new Error(`sort menu missing: ${label}`); + } + shots.push(await page.screenshot(`${out}/10-runs-sort-menu.png`)); + await page.clickText("#runSortMenu .menu-item", "Pipeline name"); + const sortLabel = await page.evaluate(`document.querySelector("#runSortBtn").textContent`); + if (!sortLabel.includes("Pipeline name")) { + throw new Error(`the sort control did not change: ${sortLabel}`); + } + await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); + shots.push(await page.screenshot(`${out}/06-runs-sorted.png`)); + console.log(` sort control now: ${sortLabel}`); + + step("opening a run detail"); + await page.click(".list.runs .run-row"); await page.waitForSelector(".detail h2", { timeout: 25000 }); shots.push(await page.screenshot(`${out}/03-run-detail.png`)); From 13404b2a2ba288dcc4215544e9f23cc0188f9e0f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 02:52:35 +0100 Subject: [PATCH 3/3] web: pipeline list, filter/sort and detail (P1/P2/P3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Close three rows of the browser client's parity checklist, matching the Android app's wording and behaviour: - P1 pipeline list: name; "id {id} · v{version} · {N stages}"; "updated d MMM HH:mm"; a last-run line joined from list_runs (status chip plus "{ago} · {duration} · run {id}", or "no runs recorded"). - P2 filter + sort: Filter menu (name contains, Runs Any/Has runs/No runs, the seven server run statuses, Clear filters) and Sort menu (Server order default, Name A-Z/Z-A, Most recent run, Fewest/Most stages, Reset). Server order is preserved. - P3 pipeline detail: Summary/Graph/Source tabs; Summary shows the content hash (monospace), latest version, created/updated and a collapsed-by-default Versions section. The Graph tab carries the browser guidance note only; the rendered graph stays P6. New src/pipelines.js holds the pure, DOM-free helpers (timestamps, durations, last-run join, comparators, filter, empty states); app.js is wiring only. web/test/pipelines.test.mjs covers the helpers; web/test/ui-smoke.mjs captures the list, controls and detail against the live server. All server strings are set with textContent. --- web/PARITY.md | 6 +- web/src/app.js | 375 ++++++++++++++++++++++++--- web/src/pipelines.js | 493 ++++++++++++++++++++++++++++++++++++ web/styles.css | 49 ++++ web/test/pipelines.test.mjs | 397 +++++++++++++++++++++++++++++ web/test/ui-smoke.mjs | 100 +++++++- 6 files changed, 1368 insertions(+), 52 deletions(-) create mode 100644 web/src/pipelines.js create mode 100644 web/test/pipelines.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index 5df4f4e4..e2f0d126 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -21,9 +21,9 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu ## Pipelines | # | Feature | Protocol | Status | | --- | --- | --- | --- | -| P1 | Pipeline list | `list_pipelines` | partial (list + count only) | -| P2 | Filter + sort (status/name/updated) | client-side | todo | -| P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | todo | +| P1 | Pipeline list | `list_pipelines` | done — row: name; `id {id} · v{version} · {N stages}`; `updated d MMM HH:mm`; last-run line joined from `list_runs` (status chip + `{ago} · {duration} · run {id}`, or `no runs recorded`) | +| P2 | Filter + sort (status/name/updated) | client-side | done — Filter menu (name contains, Runs Any/Has runs/No runs, Last run status over the 7 server states, Clear filters) + Sort menu (Server order default, Name A–Z/Z–A, Most recent run, Fewest/Most stages, Reset); server order preserved | +| P3 | Pipeline detail: stages, graph, versions, last run, content hash | `get_pipeline` | done — Summary/Graph/Source tabs; Summary shows content hash (monospace), latest version (`v{n}` or blank), created/updated, and a collapsed-by-default Versions section. Graph tab shows the browser guidance note only; the rendered graph is P6 | | P4 | Templates gallery + template detail | `list_templates` | todo | | P5 | Create pipeline from a template (validate then submit) | `validate`, `submit` | todo | | P6 | Workflow graph rendering (nodes, edges, stage panes) | `get_pipeline` | todo | diff --git a/web/src/app.js b/web/src/app.js index 1af401e1..0e96dbe5 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -4,6 +4,25 @@ 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"; @@ -43,6 +62,16 @@ const state = { 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: "", }; @@ -199,28 +228,234 @@ function tabButton(view, label) { function renderPipelineList() { const list = h("div", { class: "list" }); - if (state.loading && !state.pipelines.length) { - list.append(h("div", { class: "muted pad", text: "Loading…" })); - return list; - } - if (!state.pipelines.length) { - list.append(h("div", { class: "muted pad", text: "No pipelines." })); - return list; - } - for (const p of state.pipelines) { - list.append( + 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", { - class: `row${state.selectedPipelineId === p.id ? " selected" : ""}`, - onclick: () => selectPipeline(p), + id: "filterToggle", + class: `control${panel === "filter" ? " active" : ""}`, + onclick: () => { + state.pipelineMenu = panel === "filter" ? null : "filter"; + renderContent(); + }, }, - h("span", { class: "row-title", text: p.name || `pipeline ${p.id}` }), - h("span", { class: "row-meta", text: `#${p.id} · v${p.version} · ${p.stages} stage${p.stages === 1 ? "" : "s"}` }), + 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 }), ), ); } - return list; + 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() { @@ -230,40 +465,91 @@ function renderPipelineDetail() { 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("h2", { text: d.name || `pipeline ${d.id}` }), h( "div", - { class: "kv" }, - kv("ID / version", `#${d.id} · v${d.version}`), - kv("Stages", String(d.stages ?? (d.graph?.stages?.length ?? 0))), - kv("Content hash", d.content_hash || "—"), - kv("Created", fmtTime(d.created_at)), - kv("Updated", fmtTime(d.updated_at)), - kv("Latest version", d.latest_version ? String(d.latest_version) : "—"), + { 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(); + }, + }), + ), ), ); - const stages = d.graph?.stages ?? []; - if (stages.length) { - pane.append(h("h3", { text: "Stages" })); - const ul = h("ul", { class: "stages" }); - for (const s of stages) { - const outcomes = Object.keys(s.edges ?? {}).join(", "); - ul.append( - h( - "li", - {}, - h("code", { text: s.key }), - s.type ? h("span", { class: "chip", text: s.type }) : null, - outcomes ? h("span", { class: "muted", text: `→ ${outcomes}` }) : null, - ), - ); + 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(ul); + 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) { @@ -451,10 +737,19 @@ async function loadCurrentView(force = false) { 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(); @@ -470,6 +765,8 @@ async function loadCurrentView(force = false) { 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); diff --git a/web/src/pipelines.js b/web/src/pipelines.js new file mode 100644 index 00000000..0891f461 --- /dev/null +++ b/web/src/pipelines.js @@ -0,0 +1,493 @@ +// Pure pipeline-list/detail logic for the web client. Deliberately DOM-free: +// every helper here is a plain function a `node --test` can exercise without a +// browser, exactly like `client.js`. The DOM wiring lives in `app.js`. +// +// The wording and behaviour mirror the Android app one-for-one — the same +// singular/plural spelling, the same status vocabulary, the same comparator +// tie-breaks and the same empty-state sentences — because the web client's goal +// is feature parity, not a re-invention: +// ui/Format.kt, ui/screens/ListSort.kt, ui/screens/ListFilter.kt, +// ui/screens/PipelineLastRun.kt, ui/screens/PipelineDetailScreen.kt, +// ui/components/RunStatus.kt. + +// --------------------------------------------------------------------------- +// Timestamps and durations (ui/Format.kt) +// --------------------------------------------------------------------------- + +/** + * Parses an RFC3339 timestamp to epoch millis, or null when blank or + * unparseable. The single parser every time-reading helper shares, so a bad + * timestamp is handled the same way everywhere. + */ +export function parseInstant(text) { + if (typeof text !== "string" || text.trim() === "") return null; + const ms = Date.parse(text); + return Number.isNaN(ms) ? null : ms; +} + +/** + * An RFC3339 timestamp as the app's one human, local rendering (`d MMM HH:mm`, + * e.g. `17 Oct 21:26`), or null when blank/unparseable so the caller omits the + * value rather than printing a blank. The day/month/hour/minute parts are + * assembled from `Intl.DateTimeFormat.formatToParts`, so no locale's list comma + * leaks into the string and the shape is the same everywhere. `timeZone` is + * accepted for deterministic tests; `locale` defaults to a fixed English so the + * month abbreviation matches the app's `d MMM` wording rather than drifting with + * the host locale. + */ +export function formatLocalTimestamp(instant, options = {}) { + const ms = parseInstant(instant); + if (ms === null) return null; + const { timeZone, locale = "en-GB" } = options; + const parts = new Intl.DateTimeFormat(locale, { + day: "numeric", + month: "short", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + ...(timeZone ? { timeZone } : {}), + }).formatToParts(new Date(ms)); + const get = (type) => parts.find((part) => part.type === type)?.value ?? ""; + return `${get("day")} ${get("month")} ${get("hour")}:${get("minute")}`; +} + +/** + * Human duration for a whole number of seconds: `45s`, `2m 5s`, `1h 2m`. The + * single duration rule every surface shares. A negative total renders as `0s` + * so a clamped value never prints a negative. + */ +export function formatDuration(totalSeconds) { + const seconds = Math.max(0, Math.trunc(totalSeconds)); + if (seconds < 60) return `${seconds}s`; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`; + return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`; +} + +/** + * Non-negative whole seconds between two RFC3339 timestamps, or null when either + * is blank/unparseable or the end precedes the start. + */ +export function durationSeconds(start, end) { + const from = parseInstant(start); + const to = parseInstant(end); + if (from === null || to === null) return null; + const seconds = Math.floor((to - from) / 1000); + return seconds >= 0 ? seconds : null; +} + +/** + * Non-negative whole seconds from a `start` timestamp to `nowMillis`, or null + * when `start` is blank/unparseable. Clamps a future/unparseable elapsed to 0 so + * a live timer never prints a negative. + */ +export function secondsSince(start, nowMillis) { + const from = parseInstant(start); + if (from === null) return null; + return Math.max(0, Math.floor((nowMillis - from) / 1000)); +} + +/** + * The time a run has taken so far: while it is still executing, its live elapsed + * from its start to `nowMs`; once finished, its stored total duration. Null when + * the needed timestamps are unusable, so the caller omits the value. + */ +export function runDurationText(run, nowMs) { + if (run && run.executing) { + const elapsed = secondsSince(run.created_at, nowMs); + return elapsed === null ? null : formatDuration(elapsed); + } + const total = durationSeconds(run?.created_at, run?.finished_at); + return total === null ? null : formatDuration(total); +} + +/** + * A compact "how long ago" for a run's start: `just now` under a minute, then + * `Nm ago`/`Nh ago`/`Nd ago`. Null when the timestamp is blank/unparseable so + * the caller omits the fragment instead of printing a blank. A future start + * (clock skew) reads as `just now`, never a negative age. + */ +export function formatRanAgo(createdAt, nowMs) { + const start = parseInstant(createdAt); + if (start === null) return null; + const seconds = Math.max(0, Math.floor((nowMs - start) / 1000)); + if (seconds < 60) return "just now"; + if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; + if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; + return `${Math.floor(seconds / 86400)}d ago`; +} + +/** + * A stage count in the app's one singular/plural spelling (`1 stage` / + * `n stages`), shared by the list and the detail so a single-stage pipeline + * never reads "1 stages". + */ +export function stageCountText(count) { + const n = Number(count) || 0; + return `${n} ${n === 1 ? "stage" : "stages"}`; +} + +// --------------------------------------------------------------------------- +// Run states (ui/components/RunStatus.kt) +// --------------------------------------------------------------------------- + +const RUN_STATE_ALIASES = { + running: "running", + queued: "queued", + waiting: "waiting", + active: "active", + succeeded: "succeeded", + success: "succeeded", + completed: "succeeded", + done: "succeeded", + failed: "failed", + error: "failed", + canceled: "canceled", + cancelled: "canceled", + interrupted: "interrupted", + blocked: "blocked", + skipped: "skipped", +}; + +/** + * Maps a server status or outcome word to the app's run-state word, accepting + * the server's own vocabulary only. A blank or unrecognised value falls back to + * `unknown` so a bad value never crashes the UI. + */ +export function runStateOf(status) { + const key = String(status ?? "").trim().toLowerCase(); + return RUN_STATE_ALIASES[key] ?? "unknown"; +} + +// --------------------------------------------------------------------------- +// Last-run join and badge (ui/screens/PipelineLastRun.kt) +// --------------------------------------------------------------------------- + +/** Shown for a pipeline that has recorded no run. */ +export const NO_RUNS_RECORDED = "no runs recorded"; + +/** + * Timestamps decide recency; the higher run id breaks an exact tie (or a bad + * timestamp). The one recency rule, shared by the per-pipeline last-run join + * and the "most recent run" ordering. + */ +export function isMoreRecent(candidate, current) { + const a = parseInstant(candidate.created_at); + const b = parseInstant(current.created_at); + if (a !== null && b !== null && a !== b) return a > b; + return candidate.id > current.id; +} + +/** + * Joins the whole run history onto pipelines by pipeline id: the most recent + * run per pipeline. The input order never matters — recency is decided from the + * timestamps, with the higher run id breaking an exact tie — so a pipeline with + * no runs is simply absent from the result (the caller renders + * [NO_RUNS_RECORDED] for it). + */ +export function latestRunByPipeline(runs) { + const latest = new Map(); + for (const run of runs ?? []) { + const current = latest.get(run.pipeline_id); + if (current === undefined || isMoreRecent(run, current)) latest.set(run.pipeline_id, run); + } + return latest; +} + +/** The display facts one pipeline row shows for `run`, anchored to `nowMs`. */ +export function runBadge(run, nowMs) { + return { + runId: run.id, + state: runStateOf(run.status), + ranAgo: formatRanAgo(run.created_at, nowMs), + duration: runDurationText(run, nowMs), + }; +} + +/** + * The last-run secondary line, e.g. `2h ago · 1m 5s · run 42`. Missing + * fragments (an unparseable start, a run still executing) are omitted so no + * blank separator is ever printed; the run id is always present. + */ +export function runBadgeMetaLine(badge) { + const fragments = [badge.ranAgo, badge.duration, `run ${badge.runId}`]; + return fragments.filter((fragment) => fragment != null && fragment !== "").join(" · "); +} + +// --------------------------------------------------------------------------- +// Sorting (ui/screens/ListSort.kt) +// --------------------------------------------------------------------------- + +/** The pipeline-list orderings offered by the sort control; Server order is the default. */ +export const PIPELINE_SORTS = [ + { key: "server_order", label: "Server order" }, + { key: "name_asc", label: "Name A\u2013Z" }, + { key: "name_desc", label: "Name Z\u2013A" }, + { key: "recent_run", label: "Most recent run" }, + { key: "fewest_stages", label: "Fewest stages" }, + { key: "most_stages", label: "Most stages" }, +]; + +/** Case-insensitive string comparison, matching String.CASE_INSENSITIVE_ORDER for ASCII. */ +function compareInsensitive(a, b) { + const x = String(a ?? "").toUpperCase(); + const y = String(b ?? "").toUpperCase(); + if (x < y) return -1; + if (x > y) return 1; + return 0; +} + +/** Plain (case-sensitive) string comparison for the comparator's second key. */ +function compareSensitive(a, b) { + const x = String(a ?? ""); + const y = String(b ?? ""); + if (x < y) return -1; + if (x > y) return 1; + return 0; +} + +/** + * The pure pipeline comparator for `sort`. Every case ends in an explicit + * tie-break (`id` is unique), so pipelines that compare equal on the primary + * key always order the same way rather than depending on the input order. + * + * `latestRuns` maps a pipeline id to that pipeline's most recent run (see + * [latestRunByPipeline]); only "Most recent run" uses it but it is passed in + * once so the fold is never repeated per comparison. + */ +export function pipelineComparator(sort, latestRuns = new Map()) { + const runFor = (pipeline) => + latestRuns instanceof Map ? latestRuns.get(pipeline.id) : latestRuns[pipeline.id]; + switch (sort) { + case "name_asc": + return (a, b) => + compareInsensitive(a.name, b.name) || + compareSensitive(a.name, b.name) || + a.id - b.id; + case "name_desc": + return (a, b) => + -compareInsensitive(a.name, b.name) || + compareSensitive(a.name, b.name) || + a.id - b.id; + case "recent_run": + return (a, b) => { + const ra = runFor(a); + const rb = runFor(b); + const noRunA = ra == null ? 1 : 0; + const noRunB = rb == null ? 1 : 0; + if (noRunA !== noRunB) return noRunA - noRunB; + const ta = ra ? parseInstant(ra.created_at) : null; + const tb = rb ? parseInstant(rb.created_at) : null; + const na = ta == null ? -Infinity : ta; + const nb = tb == null ? -Infinity : tb; + if (na !== nb) return na > nb ? -1 : 1; + const ia = ra ? ra.id : -Infinity; + const ib = rb ? rb.id : -Infinity; + if (ia !== ib) return ia > ib ? -1 : 1; + return a.id - b.id; + }; + case "fewest_stages": + return (a, b) => + (Number(a.stages) || 0) - (Number(b.stages) || 0) || + compareInsensitive(a.name, b.name) || + a.id - b.id; + case "most_stages": + return (a, b) => + (Number(b.stages) || 0) - (Number(a.stages) || 0) || + compareInsensitive(a.name, b.name) || + a.id - b.id; + // Server order (and any unknown stored value): the identity comparator, so + // a stable sort preserves the server's own ordering exactly. + case "server_order": + default: + return () => 0; + } +} + +/** Orders `pipelines` by `sort` without mutating the input, folding the run history once. */ +export function sortPipelines(pipelines, sort, latestRuns = new Map()) { + return [...(pipelines ?? [])].sort(pipelineComparator(sort, latestRuns)); +} + +// --------------------------------------------------------------------------- +// Filtering (ui/screens/ListFilter.kt) +// --------------------------------------------------------------------------- + +/** + * The statuses a filter can select: the server's own run vocabulary. The + * app-only `active` bucket, the stage-outcome words (`blocked`/`skipped`) and + * the `unknown` fallback are deliberately not offered, so a status filter + * always names a real run state. + */ +export const RUN_STATUS_FILTERS = [ + "queued", + "running", + "waiting", + "succeeded", + "failed", + "canceled", + "interrupted", +]; + +/** The has/no-runs narrowing offered by the filter's Runs section. */ +export const RUN_PRESENCES = [ + { key: "any", label: "Any" }, + { key: "has_runs", label: "Has runs" }, + { key: "no_runs", label: "No runs" }, +]; + +/** The default, no-narrowing pipeline filter. */ +export const EMPTY_PIPELINE_FILTERS = { presence: "any", lastRunStatuses: [], name: "" }; + +/** Whether a run-history facet (presence or last-run status) is set. */ +export function hasRunFacets(filters) { + return (filters?.presence ?? "any") !== "any" || (filters?.lastRunStatuses ?? []).length > 0; +} + +/** True when the filters actually narrow anything. */ +export function pipelineFiltersActive(filters) { + return hasRunFacets(filters) || String(filters?.name ?? "").trim() !== ""; +} + +/** The number of active facets, used for the control's badge. */ +export function pipelineFilterCount(filters) { + return ( + ((filters?.presence ?? "any") !== "any" ? 1 : 0) + + ((filters?.lastRunStatuses ?? []).length > 0 ? 1 : 0) + + (String(filters?.name ?? "").trim() !== "" ? 1 : 0) + ); +} + +/** True when `name` is blank, or when `pipelineName` contains it, ignoring case. */ +export function pipelineMatchesName(name, pipelineName) { + const needle = String(name ?? "").trim(); + return needle === "" || String(pipelineName ?? "").toLowerCase().includes(needle.toLowerCase()); +} + +/** True when `presence` is satisfied by whether the pipeline has a run. */ +export function pipelineMatchesPresence(presence, hasRun) { + switch (presence) { + case "has_runs": + return hasRun; + case "no_runs": + return !hasRun; + case "any": + default: + return true; + } +} + +/** + * True when `latestRun`'s status is in `statuses`; an empty set means "any + * status" and a pipeline with no run never matches a selected status, so the + * filter genuinely narrows. + */ +export function pipelineMatchesLastRunStatus(latestRun, statuses) { + const wanted = statuses ?? []; + if (wanted.length === 0) return true; + return latestRun != null && wanted.includes(runStateOf(latestRun.status)); +} + +/** + * Narrows `pipelines` by `filters`: the name narrowing and both run facets + * combined with AND. The name facet never depends on the run history, so it + * applies immediately; the run facets do, so while that history is still + * unknown (`runsKnown == false`) they are skipped rather than briefly hiding + * every pipeline. + */ +export function filterPipelines(pipelines, filters, latestRuns = new Map(), runsKnown = true) { + const all = pipelines ?? []; + if (!pipelineFiltersActive(filters)) return all; + const runFacets = hasRunFacets(filters); + const getRun = (pipeline) => + latestRuns instanceof Map ? latestRuns.get(pipeline.id) : latestRuns[pipeline.id]; + return all.filter((pipeline) => { + if (!pipelineMatchesName(filters?.name, pipeline.name)) return false; + if (runFacets && runsKnown) { + const latestRun = getRun(pipeline) ?? null; + if (!pipelineMatchesPresence(filters.presence, latestRun != null)) return false; + if (!pipelineMatchesLastRunStatus(latestRun, filters.lastRunStatuses)) return false; + } + return true; + }); +} + +/** + * The empty-state sentence for the pipeline list plus its optional reset action. + * Returns null when there is something to show. `Clear filters` is only offered + * when pipelines exist (nothing exists to reveal otherwise). + */ +export function pipelineListEmptyState(all, items, filters) { + if ((items ?? []).length > 0) return null; + const every = all ?? []; + if (every.length === 0) { + return { message: "No pipelines are defined on this server.", clearAction: null }; + } + const name = String(filters?.name ?? ""); + const message = + name.trim() !== "" && !hasRunFacets(filters) + ? `No pipelines match "${name}".` + : "No pipelines match the current filters."; + return { message, clearAction: "Clear filters" }; +} + +// --------------------------------------------------------------------------- +// List row and detail text +// --------------------------------------------------------------------------- + +/** The pipeline row's secondary line: `id {id} · v{version} · {N stages}`. */ +export function pipelineSubtitle(pipeline) { + const stages = pipeline.stages ?? pipeline.graph?.stages?.length ?? 0; + return `id ${pipeline.id} · v${pipeline.version} · ${stageCountText(stages)}`; +} + +/** The row's `updated …` line, or null when the timestamp is unparseable. */ +export function pipelineUpdatedLine(pipeline) { + const formatted = formatLocalTimestamp(pipeline.updated_at); + return formatted ? `updated ${formatted}` : null; +} + +/** The pipeline-detail tabs, Summary first (the version list lives inside it). */ +export const PIPELINE_DETAIL_TABS = [ + { key: "summary", label: "Summary" }, + { key: "graph", label: "Graph" }, + { key: "source", label: "Source" }, +]; + +/** + * The Summary tab's key/value rows, in the app's order: Content hash + * (monospace), Latest version (`v{n}` or blank — never a dash), Version created, + * Pipeline created, Pipeline updated. + */ +export function summaryFields(detail) { + const latest = Number(detail?.latest_version) || 0; + return [ + { key: "Content hash", value: detail?.content_hash ?? "", monospace: true }, + { key: "Latest version", value: latest > 0 ? `v${latest}` : "" }, + { key: "Version created", value: formatLocalTimestamp(detail?.version_created_at) ?? "" }, + { key: "Pipeline created", value: formatLocalTimestamp(detail?.created_at) ?? "" }, + { key: "Pipeline updated", value: formatLocalTimestamp(detail?.updated_at) ?? "" }, + ]; +} + +/** One Version row: `v{n}` plus its stage count and (parseable) created time. */ +export function versionRow(version) { + return { + versionLabel: `v${version?.version}`, + stagesText: stageCountText(version?.stages), + createdText: formatLocalTimestamp(version?.created_at), + }; +} + +/** + * The Graph tab's guidance note, adapted for a browser: mouse-wheel zoom and + * click replace the app's pinch and tap. The graph itself is the separate P6 + * item. + */ +export const GRAPH_NOTE = + "Mouse wheel to zoom, drag to pan, click a stage for details. " + + "Edges are labelled with their outcome; error* is the implicit fallback."; + +/** The guidance note string (a function so callers need no constant import). */ +export function graphNote() { + return GRAPH_NOTE; +} diff --git a/web/styles.css b/web/styles.css index f753f440..71c8c17b 100644 --- a/web/styles.css +++ b/web/styles.css @@ -142,3 +142,52 @@ button.ghost { background: transparent; } .banner.error { background: #2c1616; color: var(--bad); } code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-size: 12px; } + +/* Pipeline list: filter + sort controls. */ +.list-controls { border-bottom: 1px solid var(--border); } +.list-toolbar { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; padding: 8px 12px; } +.control { font-size: 12px; padding: 4px 10px; } +.control.active { border-color: var(--accent); color: var(--accent); } +.control .count { color: var(--accent); } +.clear { font-size: 12px; padding: 4px 10px; } + +.menu-panel { border-top: 1px solid var(--border); padding: 8px 12px 12px; background: var(--surface); } +.filter-section { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin: 10px 0 4px; } +.filter-field { display: block; } +.filter-field-label { display: block; color: var(--muted); font-size: 12px; margin-bottom: 4px; } +.filter-field input[type="text"] { flex: none; width: 100%; min-width: 0; } +.filter-item { display: flex; gap: 8px; align-items: center; padding: 3px 0; font-size: 13px; cursor: pointer; } +.filter-item input { accent-color: var(--accent); } +.filter-actions { margin-top: 10px; display: flex; gap: 8px; } +.sort-option { display: block; width: 100%; text-align: left; border: 1px solid transparent; background: transparent; padding: 5px 8px; border-radius: 6px; font-size: 13px; } +.sort-option:hover { background: var(--surface-2); } +.sort-option.active { border-color: var(--accent); color: var(--accent); } + +.row-run { display: flex; gap: 8px; align-items: center; margin-top: 3px; } +.row-run .row-meta { margin-top: 0; } + +.empty { display: grid; gap: 10px; justify-items: start; } + +/* Pipeline detail: tab strip, collapsible sections, source block. */ +.detail-tabs { display: flex; gap: 4px; margin: 10px 0 12px; border-bottom: 1px solid var(--border); } +.detail-tab { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; color: var(--muted); padding: 6px 10px; } +.detail-tab:hover { border-color: transparent; color: var(--text); } +.detail-tab.active { color: var(--accent); border-bottom-color: var(--accent); } +.detail-subtitle { font-size: 12px; margin-bottom: 10px; } +.monospace { font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; font-size: 12px; } + +.section-toggle { display: flex; gap: 8px; align-items: center; width: 100%; text-align: left; margin-top: 16px; border: 0; border-radius: 8px; background: var(--surface-2); padding: 8px 10px; font-weight: 600; } +.section-toggle .chevron { color: var(--muted); } +.section-body { padding: 8px 4px 0; display: grid; gap: 6px; } +.version-row { display: flex; gap: 12px; align-items: baseline; border: 1px solid var(--border); border-radius: 8px; padding: 6px 10px; } +.version-title { font-weight: 600; } + +.source-code { margin: 0; background: var(--surface-2); border: 1px solid var(--border); border-radius: 10px; padding: 12px; overflow: auto; max-height: 60vh; } +.source-code code { background: transparent; padding: 0; font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-word; } + +.graph-note { margin: 0; max-width: 60ch; } + +.chip-waiting { color: var(--warn); border-color: var(--warn); } +.chip-canceled { color: var(--muted); border-color: var(--muted); } +.chip-interrupted { color: var(--muted); border-color: var(--muted); } +.chip-unknown { color: var(--muted); border-color: var(--muted); } diff --git a/web/test/pipelines.test.mjs b/web/test/pipelines.test.mjs new file mode 100644 index 00000000..46c34dc6 --- /dev/null +++ b/web/test/pipelines.test.mjs @@ -0,0 +1,397 @@ +// Unit tests for the pure pipeline helpers (src/pipelines.js): timestamp and +// duration formatting, the last-run join, the sort comparators, the filter and +// the empty-state strings. No DOM and no server: `node --test test/` proves the +// module is pure. Wording is asserted against the Android app's own strings. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + PIPELINE_DETAIL_TABS, + PIPELINE_SORTS, + RUN_PRESENCES, + RUN_STATUS_FILTERS, + durationSeconds, + filterPipelines, + formatDuration, + formatLocalTimestamp, + formatRanAgo, + graphNote, + isMoreRecent, + latestRunByPipeline, + parseInstant, + pipelineComparator, + pipelineFilterCount, + pipelineListEmptyState, + pipelineMatchesLastRunStatus, + pipelineMatchesName, + pipelineMatchesPresence, + pipelineSubtitle, + pipelineUpdatedLine, + runBadge, + runBadgeMetaLine, + runDurationText, + runStateOf, + sortPipelines, + stageCountText, + summaryFields, + versionRow, +} from "../src/pipelines.js"; + +const LOCAL_STAMP = /^\d{1,2} [A-Z][a-z]{2} \d{2}:\d{2}$/; + +// --------------------------------------------------------------------------- +// Timestamps, durations and stage counts +// --------------------------------------------------------------------------- + +test("stageCountText spells 1 singular and everything else plural", () => { + assert.equal(stageCountText(0), "0 stages"); + assert.equal(stageCountText(1), "1 stage"); + assert.equal(stageCountText(2), "2 stages"); + assert.equal(stageCountText(5), "5 stages"); +}); + +test("parseInstant accepts RFC3339 and rejects blank/unparseable input", () => { + assert.equal(parseInstant("2026-10-17T21:57:31Z"), Date.parse("2026-10-17T21:57:31Z")); + assert.equal(parseInstant(""), null); + assert.equal(parseInstant(" "), null); + assert.equal(parseInstant("not a date"), null); + assert.equal(parseInstant(undefined), null); +}); + +test("formatLocalTimestamp renders 'd MMM HH:mm' and null on bad input", () => { + assert.equal(formatLocalTimestamp("2026-10-17T21:57:31Z", { timeZone: "UTC" }), "17 Oct 21:57"); + assert.equal(formatLocalTimestamp("2026-01-05T00:00:00Z", { timeZone: "UTC" }), "5 Jan 00:00"); + assert.equal(formatLocalTimestamp("2026-10-17T21:57:31Z", { timeZone: "Europe/London" }), "17 Oct 22:57"); + assert.equal(formatLocalTimestamp("", { timeZone: "UTC" }), null); + assert.equal(formatLocalTimestamp("nope", { timeZone: "UTC" }), null); +}); + +test("formatDuration matches the app's s / m s / h m rhythm", () => { + assert.equal(formatDuration(0), "0s"); + assert.equal(formatDuration(45), "45s"); + assert.equal(formatDuration(59), "59s"); + assert.equal(formatDuration(60), "1m 0s"); + assert.equal(formatDuration(125), "2m 5s"); + assert.equal(formatDuration(3599), "59m 59s"); + assert.equal(formatDuration(3600), "1h 0m"); + assert.equal(formatDuration(3725), "1h 2m"); + assert.equal(formatDuration(-5), "0s"); +}); + +test("durationSeconds is null when the end precedes the start or a timestamp is bad", () => { + assert.equal(durationSeconds("2026-10-17T21:00:00Z", "2026-10-17T21:02:05Z"), 125); + assert.equal(durationSeconds("2026-10-17T21:02:05Z", "2026-10-17T21:00:00Z"), null); + assert.equal(durationSeconds("", "2026-10-17T21:00:00Z"), null); + assert.equal(durationSeconds("2026-10-17T21:00:00Z", "nope"), null); +}); + +test("runDurationText is live while executing and stored once finished", () => { + const start = "2026-10-17T21:00:00Z"; + const now = Date.parse(start) + 100_000; + assert.equal(runDurationText({ created_at: start, finished_at: "", executing: true }, now), "1m 40s"); + assert.equal( + runDurationText({ created_at: start, finished_at: "2026-10-17T21:02:05Z", executing: false }, now), + "2m 5s", + ); + assert.equal(runDurationText({ created_at: "", finished_at: "", executing: true }, now), null); + assert.equal(runDurationText({ created_at: start, finished_at: "", executing: false }, now), null); +}); + +test("a running run with a future start reads as 0s, never negative", () => { + const start = "2026-10-17T21:00:00Z"; + const now = Date.parse(start) - 5_000; + assert.equal(runDurationText({ created_at: start, finished_at: "", executing: true }, now), "0s"); +}); + +test("formatRanAgo buckets by minute/hour/day and nulls a bad start", () => { + const start = Date.parse("2026-10-17T21:00:00Z"); + const ago = (seconds) => formatRanAgo("2026-10-17T21:00:00Z", start + seconds * 1000); + assert.equal(ago(0), "just now"); + assert.equal(ago(59), "just now"); + assert.equal(ago(60), "1m ago"); + assert.equal(ago(90), "1m ago"); + assert.equal(ago(3600), "1h ago"); + assert.equal(ago(7200), "2h ago"); + assert.equal(ago(86400), "1d ago"); + assert.equal(ago(3 * 86400), "3d ago"); + assert.equal(formatRanAgo("2026-10-17T21:00:00Z", start - 10_000), "just now"); + assert.equal(formatRanAgo("", start), null); + assert.equal(formatRanAgo("nope", start), null); +}); + +// --------------------------------------------------------------------------- +// Run states and the last-run join +// --------------------------------------------------------------------------- + +test("runStateOf accepts the server vocabulary and falls back to unknown", () => { + assert.equal(runStateOf("succeeded"), "succeeded"); + assert.equal(runStateOf("RUNNING"), "running"); + assert.equal(runStateOf("success"), "succeeded"); + assert.equal(runStateOf("error"), "failed"); + assert.equal(runStateOf("cancelled"), "canceled"); + assert.equal(runStateOf("interrupted"), "interrupted"); + assert.equal(runStateOf(""), "unknown"); + assert.equal(runStateOf(undefined), "unknown"); +}); + +test("latestRunByPipeline picks the newest run per pipeline independent of input order", () => { + const runs = [ + { id: 1, pipeline_id: 7, created_at: "2026-10-01T00:00:00Z" }, + { id: 3, pipeline_id: 7, created_at: "2026-10-03T00:00:00Z" }, + { id: 2, pipeline_id: 7, created_at: "2026-10-02T00:00:00Z" }, + { id: 5, pipeline_id: 9, created_at: "2026-10-01T00:00:00Z" }, + ]; + const forward = latestRunByPipeline(runs); + const backward = latestRunByPipeline([...runs].reverse()); + assert.equal(forward.get(7).id, 3); + assert.equal(backward.get(7).id, 3); + assert.equal(forward.get(9).id, 5); + assert.equal(forward.size, 2); +}); + +test("isMoreRecent breaks an exact timestamp tie (and a bad timestamp) with the higher id", () => { + const sameTime = { created_at: "2026-10-01T00:00:00Z" }; + assert.equal(isMoreRecent({ id: 7, ...sameTime }, { id: 5, ...sameTime }), true); + assert.equal(isMoreRecent({ id: 5, ...sameTime }, { id: 7, ...sameTime }), false); + assert.equal(isMoreRecent({ id: 8, created_at: "bad" }, { id: 6, created_at: "also bad" }), true); + assert.equal(isMoreRecent({ id: 6, created_at: "bad" }, { id: 8, created_at: "bad" }), false); +}); + +test("runBadgeMetaLine omits missing fragments but always prints the run id", () => { + assert.equal(runBadgeMetaLine({ ranAgo: "2h ago", duration: "1m 5s", runId: 42 }), "2h ago · 1m 5s · run 42"); + assert.equal(runBadgeMetaLine({ ranAgo: null, duration: "1m 5s", runId: 42 }), "1m 5s · run 42"); + assert.equal(runBadgeMetaLine({ ranAgo: "2h ago", duration: null, runId: 42 }), "2h ago · run 42"); + assert.equal(runBadgeMetaLine({ ranAgo: null, duration: null, runId: 42 }), "run 42"); + assert.equal(runBadgeMetaLine({ ranAgo: "", duration: "", runId: 7 }), "run 7"); +}); + +test("runBadge bundles the state, age, duration and run id", () => { + const start = "2026-10-17T21:00:00Z"; + const badge = runBadge( + { id: 12, status: "failed", created_at: start, finished_at: "2026-10-17T21:02:05Z", executing: false }, + Date.parse(start) + 3600_000, + ); + assert.deepEqual(badge, { runId: 12, state: "failed", ranAgo: "1h ago", duration: "2m 5s" }); +}); + +// --------------------------------------------------------------------------- +// Sorting +// --------------------------------------------------------------------------- + +const P = (id, name, stages) => ({ id, name, stages, version: 1 }); + +function ids(list) { + return list.map((p) => p.id); +} + +test("the sort list matches the app's labels with Server order default", () => { + assert.deepEqual( + PIPELINE_SORTS.map((option) => option.label), + ["Server order", "Name A\u2013Z", "Name Z\u2013A", "Most recent run", "Fewest stages", "Most stages"], + ); + assert.equal(PIPELINE_SORTS[0].key, "server_order"); +}); + +test("server order preserves the server's own ordering (and never mutates the input)", () => { + const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)]; + assert.deepEqual(ids(sortPipelines(pipelines, "server_order")), [3, 1, 2, 4]); + assert.deepEqual(ids(pipelines), [3, 1, 2, 4], "input list is untouched"); +}); + +test("name comparators ignore case and tie-break on the exact name then the id", () => { + const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)]; + assert.deepEqual(ids(sortPipelines(pipelines, "name_asc")), [1, 2, 3, 4]); + assert.deepEqual(ids(sortPipelines(pipelines, "name_desc")), [4, 3, 1, 2]); +}); + +test("stage-count comparators tie-break on the name then the id", () => { + const pipelines = [P(3, "beta", 2), P(1, "Alpha", 3), P(2, "alpha", 1), P(4, "Gamma", 1)]; + assert.deepEqual(ids(sortPipelines(pipelines, "fewest_stages")), [2, 4, 3, 1]); + assert.deepEqual(ids(sortPipelines(pipelines, "most_stages")), [1, 3, 2, 4]); +}); + +test("most-recent-run puts no-run pipelines last and orders by run recency then run id", () => { + const pipelines = [P(1, "One", 1), P(2, "Two", 1), P(3, "Three", 1), P(4, "Four", 1)]; + const latestRuns = new Map([ + [1, { id: 11, pipeline_id: 1, created_at: "2026-10-03T00:00:00Z" }], + [3, { id: 10, pipeline_id: 3, created_at: "2026-10-01T00:00:00Z" }], + [4, { id: 9, pipeline_id: 4, created_at: "not a date" }], + ]); + assert.deepEqual(ids(sortPipelines(pipelines, "recent_run", latestRuns)), [1, 3, 4, 2]); +}); + +test("most-recent-run breaks an exact timestamp tie with the higher run id", () => { + const pipelines = [P(1, "One", 1), P(2, "Two", 1)]; + const at = "2026-10-01T00:00:00Z"; + const latestRuns = new Map([ + [1, { id: 4, pipeline_id: 1, created_at: at }], + [2, { id: 9, pipeline_id: 2, created_at: at }], + ]); + assert.deepEqual(ids(sortPipelines(pipelines, "recent_run", latestRuns)), [2, 1]); +}); + +test("every comparator ends in a deterministic id tie-break", () => { + // Identical names and stage counts: only the id can decide, whatever the input order. + const pipelines = [P(5, "same", 2), P(2, "same", 2), P(9, "same", 2)]; + assert.deepEqual(ids(sortPipelines(pipelines, "name_asc")), [2, 5, 9]); + assert.deepEqual(ids(sortPipelines([...pipelines].reverse(), "name_asc")), [2, 5, 9]); + assert.deepEqual(ids(sortPipelines(pipelines, "fewest_stages")), [2, 5, 9]); + assert.equal(typeof pipelineComparator("server_order"), "function"); +}); + +// --------------------------------------------------------------------------- +// Filtering and empty states +// --------------------------------------------------------------------------- + +test("the status filter vocabulary is exactly the server's seven run states", () => { + assert.deepEqual(RUN_STATUS_FILTERS, [ + "queued", + "running", + "waiting", + "succeeded", + "failed", + "canceled", + "interrupted", + ]); + assert.deepEqual( + RUN_PRESENCES.map((p) => p.label), + ["Any", "Has runs", "No runs"], + ); +}); + +const FILTER_PIPELINES = [P(1, "Android", 3), P(2, "Beta", 2), P(3, "Gamma", 1)]; +const FILTER_RUNS = new Map([ + [1, { id: 1, pipeline_id: 1, status: "succeeded" }], + [2, { id: 2, pipeline_id: 2, status: "failed" }], +]); +const FILTERS = (overrides = {}) => ({ presence: "any", lastRunStatuses: [], name: "", ...overrides }); + +test("the name facet narrows case-insensitively and needs no run history", () => { + assert.ok(pipelineMatchesName("", "anything")); + assert.ok(pipelineMatchesName("and", "Android")); + assert.ok(!pipelineMatchesName("zzz", "Android")); + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ name: "and" }), FILTER_RUNS, false).map((p) => p.id), + [1], + ); +}); + +test("run facets AND together and a no-run pipeline never matches a selected status", () => { + assert.ok(pipelineMatchesPresence("any", false)); + assert.ok(pipelineMatchesPresence("has_runs", true)); + assert.ok(!pipelineMatchesPresence("has_runs", false)); + assert.ok(pipelineMatchesPresence("no_runs", false)); + assert.ok(pipelineMatchesLastRunStatus(null, [])); + assert.ok(!pipelineMatchesLastRunStatus(null, ["failed"])); + + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs" }), FILTER_RUNS, true).map((p) => p.id), + [1, 2], + ); + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "no_runs" }), FILTER_RUNS, true).map((p) => p.id), + [3], + ); + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ lastRunStatuses: ["failed"] }), FILTER_RUNS, true).map((p) => p.id), + [2], + ); +}); + +test("a run facet is skipped while the run history is unknown, and the name still applies", () => { + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs" }), FILTER_RUNS, false).map((p) => p.id), + [1, 2, 3], + ); + assert.deepEqual( + filterPipelines(FILTER_PIPELINES, FILTERS({ presence: "has_runs", name: "Beta" }), FILTER_RUNS, false).map((p) => p.id), + [2], + ); +}); + +test("pipelineFilterCount counts one per active facet", () => { + assert.equal(pipelineFilterCount(FILTERS()), 0); + assert.equal(pipelineFilterCount(FILTERS({ name: "a" })), 1); + assert.equal(pipelineFilterCount(FILTERS({ presence: "has_runs", lastRunStatuses: ["failed"], name: "a" })), 3); +}); + +test("empty states use the app's three exact sentences and only offer a reset when pipelines exist", () => { + assert.deepEqual(pipelineListEmptyState([], [], FILTERS()), { + message: "No pipelines are defined on this server.", + clearAction: null, + }); + assert.deepEqual(pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ name: "zzz" })), { + message: 'No pipelines match "zzz".', + clearAction: "Clear filters", + }); + assert.deepEqual(pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ presence: "has_runs" })), { + message: "No pipelines match the current filters.", + clearAction: "Clear filters", + }); + // A name narrowing combined with a run facet is no longer name-only. + assert.equal( + pipelineListEmptyState(FILTER_PIPELINES, [], FILTERS({ name: "zzz", presence: "has_runs" })).message, + "No pipelines match the current filters.", + ); + assert.equal(pipelineListEmptyState(FILTER_PIPELINES, FILTER_PIPELINES, FILTERS()), null); +}); + +// --------------------------------------------------------------------------- +// List row and detail text +// --------------------------------------------------------------------------- + +test("pipelineSubtitle is 'id {id} · v{version} · {N stages}' with a singular stage", () => { + assert.equal(pipelineSubtitle({ id: 20, version: 10, stages: 5 }), "id 20 · v10 · 5 stages"); + assert.equal(pipelineSubtitle({ id: 3, version: 1, stages: 1 }), "id 3 · v1 · 1 stage"); + assert.equal(pipelineSubtitle({ id: 4, version: 2, graph: { stages: [{}, {}] } }), "id 4 · v2 · 2 stages"); +}); + +test("pipelineUpdatedLine is 'updated d MMM HH:mm' or null for a bad timestamp", () => { + const line = pipelineUpdatedLine({ updated_at: "2026-10-17T21:57:31Z" }); + assert.ok(LOCAL_STAMP.test(line.replace(/^updated /, "")), line); + assert.equal(pipelineUpdatedLine({ updated_at: "" }), null); + assert.equal(pipelineUpdatedLine({ updated_at: "nope" }), null); +}); + +test("the detail tabs are Summary / Graph / Source in order", () => { + assert.deepEqual(PIPELINE_DETAIL_TABS.map((tab) => tab.label), ["Summary", "Graph", "Source"]); +}); + +test("summaryFields render the app's rows; latest version is v{n} or blank, never a dash", () => { + const fields = summaryFields({ + content_hash: "abc123", + latest_version: 10, + version_created_at: "2026-10-18T23:41:08Z", + created_at: "2026-10-17T21:57:31Z", + updated_at: "2026-10-18T23:41:08Z", + }); + assert.deepEqual(fields.map((f) => f.key), [ + "Content hash", + "Latest version", + "Version created", + "Pipeline created", + "Pipeline updated", + ]); + assert.equal(fields[0].value, "abc123"); + assert.equal(fields[0].monospace, true); + assert.equal(fields[1].value, "v10"); + for (const field of fields.slice(2)) assert.ok(LOCAL_STAMP.test(field.value), field.value); + + const blank = summaryFields({ content_hash: "", latest_version: 0 }); + assert.equal(blank[1].value, ""); + assert.equal(blank[2].value, ""); +}); + +test("versionRow shows v{n} plus its stage count and created time", () => { + const row = versionRow({ version: 2, stages: 1, created_at: "2026-10-18T19:04:13Z" }); + assert.equal(row.versionLabel, "v2"); + assert.equal(row.stagesText, "1 stage"); + assert.ok(LOCAL_STAMP.test(row.createdText)); + assert.equal(versionRow({ version: 3, stages: 4 }).createdText, null); +}); + +test("the graph note is the browser wording and leaves the graph to P6", () => { + const note = graphNote(); + assert.match(note, /Mouse wheel to zoom, drag to pan, click a stage for details/); + assert.match(note, /Edges are labelled with their outcome/); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index c39dfc6e..319e17cb 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -37,6 +37,16 @@ function step(label) { console.log(`• ${label}`); } +async function shot(name) { + const path = `${out}/${name}`; + shots.push(await page.screenshot(path)); + console.log(` capture ${path}`); + return path; +} + +const text = (selector) => + page.evaluate(`document.querySelector(${JSON.stringify(selector)})?.textContent ?? ""`); + try { await mkdir(out, { recursive: true }); @@ -67,24 +77,94 @@ try { await page.waitForSelector(".row-title", { timeout: 25000 }); await page.waitForText("connected", { timeout: 25000 }); const pipelineCount = await page.evaluate( - `document.querySelectorAll(".list button.row").length`, + `document.querySelectorAll("#pipelineRows button.row").length`, ); if (!pipelineCount) throw new Error("connected but no pipelines rendered"); - - shots.push(await page.screenshot(`${out}/01-pipelines.png`)); console.log(` pipelines rendered: ${pipelineCount}`); - step("opening a pipeline detail"); - await page.click(".list button.row"); - await page.waitForSelector(".detail h2"); - shots.push(await page.screenshot(`${out}/02-pipeline-detail.png`)); + // 1. The list with its filter menu open: the name field, the Runs section, the + // Last run status multi-select and the Clear filters reset (P1 + P2). + step("capturing the pipeline list with the filter menu open"); + await page.click("#filterToggle"); + await page.waitForSelector(".filter-panel"); + await shot("01-pipelines-controls.png"); + // 2. The sort menu, and exercising it changes the ordering (P2). + step("capturing and exercising the sort menu"); + await page.click("#sortToggle"); + await page.waitForSelector(".sort-panel"); + await shot("02-pipelines-sort.png"); + await page.clickText(".sort-panel .sort-option", "Name A\u2013Z"); + const sorted = await text("#sortToggle"); + if (!sorted.includes("Name A\u2013Z")) throw new Error(`sort did not apply: ${sorted}`); + await page.click("#sortToggle"); + await page.waitForSelector(".sort-panel"); + await page.clickText(".sort-panel button", "Reset"); + const reset = await text("#sortToggle"); + if (!reset.includes("Server order")) throw new Error(`sort reset failed: ${reset}`); + + // 3. The name facet narrows live; an unmatched name shows the name-only empty state. + step("narrowing by name and capturing the name-only empty state"); + await page.click("#filterToggle"); + await page.waitForSelector(".filter-panel"); + await page.fill("#pipelineNameFilter", "Android"); + const narrowed = await page.evaluate( + `document.querySelectorAll("#pipelineRows button.row").length`, + ); + if (!narrowed || narrowed >= pipelineCount) { + throw new Error(`name filter did not narrow (${narrowed} of ${pipelineCount})`); + } + console.log(` name filter narrowed ${pipelineCount} -> ${narrowed}`); + await page.fill("#pipelineNameFilter", "zzz-no-such-pipeline"); + await page.waitForText('No pipelines match "zzz-no-such-pipeline".'); + await shot("03-pipelines-empty-name.png"); + await page.click(".empty button"); + await page.waitForSelector("#pipelineRows button.row"); + + // 4. A run facet with no matches shows the general empty state and a reset. + step("capturing the run-facet empty state"); + await page.click("#status-interrupted"); + await page.waitForText("No pipelines match the current filters."); + await shot("04-pipelines-empty-filters.png"); + await page.click(".empty button"); + await page.waitForSelector("#pipelineRows button.row"); + await page.click("#filterToggle"); + + // 5. Pipeline detail: Summary (name, subtitle, content hash, created/updated). + step("opening a pipeline detail (Summary)"); + await page.click("#pipelineRows button.row"); + await page.waitForSelector(".detail h2"); + await page.waitForSelector(".monospace"); + await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`); + await shot("05-pipeline-summary.png"); + + // 6. The Versions section is collapsed by default; expanding shows its rows. + step("expanding the Versions section"); + await page.click(".section-toggle"); + await page.waitForSelector(".versions-list"); + await page.evaluate(`document.querySelector(".versions-list")?.scrollIntoView({ block: "start" })`); + await shot("06-pipeline-summary-versions.png"); + + // 7. Source tab: the rendered pipeline source in a monospace block. + step("opening the Source tab"); + await page.clickText(".detail-tabs button", "Source"); + await page.waitForSelector(".source-code"); + await page.evaluate(`document.querySelector(".detail")?.scrollIntoView({ block: "start" })`); + await shot("07-pipeline-source.png"); + + // 8. Graph tab: the guidance note only; the rendered graph is P6. + step("opening the Graph tab (guidance note only)"); + await page.clickText(".detail-tabs button", "Graph"); + await page.waitForSelector(".graph-note"); + await shot("08-pipeline-graph.png"); + + // 9. Runs regression: the pre-existing run list + detail still work. step("switching to Runs and opening a run detail"); await page.clickText("nav.tabs button.tab", "Runs"); - await page.waitForSelector(".list button.row", { timeout: 25000 }); - await page.click(".list button.row"); + await page.waitForSelector("#content .list button.row", { timeout: 25000 }); + await page.click("#content .list button.row"); await page.waitForSelector(".detail h2", { timeout: 25000 }); - shots.push(await page.screenshot(`${out}/03-run-detail.png`)); + await shot("09-run-detail.png"); console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`);