Merge branch 'main' into web-artifacts

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

Checks: node --check on every touched file; node --test test/ 108 pass;
live ui-smoke against ws://127.0.0.1:8080/connect passes (run 430: 18 tiles,
viewer '1 of 10 · image/png', session link .../artifacts/430/8/session.html).
captures/ stays untracked.
This commit is contained in:
2026-10-19 03:05:58 +01:00
13 changed files with 3554 additions and 100 deletions
+397
View File
@@ -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/);
});
+106
View File
@@ -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);
});
+393
View File
@@ -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],
);
});
+87
View File
@@ -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);
});
+278 -12
View File
@@ -44,6 +44,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 });
@@ -74,24 +84,278 @@ 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");
step("switching to Runs and opening a run detail");
// 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");
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}/09-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}/10-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}/11-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}/12-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}/13-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}/14-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}/15-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`));
await shot("16-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}/17-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}/18-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}/19-template-source.png`));
// Artifact URLs resolve against whatever the URL field holds. Point it at the
// real server (the socket stays on the proxy, see the note above) so the tiles
@@ -99,7 +363,9 @@ try {
// not forward.
step(`opening run 430 and capturing its artifacts gallery`);
await page.fill("#url", artifactServerUrl);
await page.clickText(".list button.row", "#430");
await page.clickText("nav.tabs button.tab", "Runs");
await page.waitForSelector(".list.runs .run-row", { timeout: 25000 });
await page.click('.list.runs .run-row-meta[data-run-id="430"]');
await page.waitForSelector(".artifact-gallery .artifact-tile", { timeout: 25000 });
await page.waitForText("recorded", { timeout: 25000 });
const tileCount = await page.evaluate(