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
+887 -78
View File
File diff suppressed because it is too large Load Diff
+493
View File
@@ -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;
}
+5
View File
@@ -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",
+14
View File
@@ -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 };
+512
View File
@@ -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;
}
}
+93
View File
@@ -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;
}