Merge branch 'main' into web-runs-home
# Conflicts: # web/src/app.js # web/styles.css # web/test/ui-smoke.mjs
This commit is contained in:
+336
-39
@@ -4,6 +4,25 @@
|
||||
import { PipelinesClient } from "./client.js";
|
||||
import { PipelinesRepository } from "./repository.js";
|
||||
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
|
||||
import {
|
||||
PIPELINE_SORTS,
|
||||
PIPELINE_DETAIL_TABS,
|
||||
RUN_PRESENCES,
|
||||
RUN_STATUS_FILTERS,
|
||||
EMPTY_PIPELINE_FILTERS,
|
||||
filterPipelines,
|
||||
graphNote,
|
||||
latestRunByPipeline,
|
||||
pipelineFilterCount,
|
||||
pipelineListEmptyState,
|
||||
pipelineSubtitle,
|
||||
pipelineUpdatedLine,
|
||||
runBadge,
|
||||
runBadgeMetaLine,
|
||||
sortPipelines,
|
||||
summaryFields,
|
||||
versionRow,
|
||||
} from "./pipelines.js";
|
||||
import {
|
||||
RUN_STATES,
|
||||
RUN_TIME_RANGES,
|
||||
@@ -63,6 +82,16 @@ const state = {
|
||||
runDetail: null,
|
||||
selectedPipelineId: null,
|
||||
selectedRunId: null,
|
||||
// Pipelines view: client-side filter/sort/detail-tab state. The run history is
|
||||
// fetched alongside the pipelines so the list can show each pipeline's last
|
||||
// run; runsLoaded tells a genuinely empty history apart from one not in hand.
|
||||
pipelineFilters: { ...EMPTY_PIPELINE_FILTERS },
|
||||
pipelineSort: "server_order",
|
||||
pipelineMenu: null,
|
||||
pipelineTab: "summary",
|
||||
versionsExpanded: false,
|
||||
pipelinesLoaded: false,
|
||||
runsLoaded: false,
|
||||
loading: false,
|
||||
error: "",
|
||||
runFilters: defaultRunFilters(),
|
||||
@@ -231,28 +260,234 @@ function tabButton(view, label) {
|
||||
|
||||
function renderPipelineList() {
|
||||
const list = h("div", { class: "list" });
|
||||
if (state.loading && !state.pipelines.length) {
|
||||
list.append(h("div", { class: "muted pad", text: "Loading…" }));
|
||||
return list;
|
||||
}
|
||||
if (!state.pipelines.length) {
|
||||
list.append(h("div", { class: "muted pad", text: "No pipelines." }));
|
||||
return list;
|
||||
}
|
||||
for (const p of state.pipelines) {
|
||||
list.append(
|
||||
list.append(renderPipelineControls());
|
||||
const rows = h("div", { id: "pipelineRows" });
|
||||
fillPipelineRows(rows);
|
||||
list.append(rows);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's filter + sort toolbar and (when open) the matching menu panel. The
|
||||
* rows themselves live in the separate `#pipelineRows` container so a keystroke
|
||||
* in the name filter can refresh just the rows without rebuilding (and so
|
||||
* blurring) the input the operator is typing in.
|
||||
*/
|
||||
function renderPipelineControls() {
|
||||
const filters = state.pipelineFilters;
|
||||
const count = pipelineFilterCount(filters);
|
||||
const panel = state.pipelineMenu;
|
||||
const controls = h(
|
||||
"div",
|
||||
{ class: "list-controls" },
|
||||
h(
|
||||
"div",
|
||||
{ class: "list-toolbar" },
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: `row${state.selectedPipelineId === p.id ? " selected" : ""}`,
|
||||
onclick: () => selectPipeline(p),
|
||||
id: "filterToggle",
|
||||
class: `control${panel === "filter" ? " active" : ""}`,
|
||||
onclick: () => {
|
||||
state.pipelineMenu = panel === "filter" ? null : "filter";
|
||||
renderContent();
|
||||
},
|
||||
},
|
||||
h("span", { class: "row-title", text: p.name || `pipeline ${p.id}` }),
|
||||
h("span", { class: "row-meta", text: `#${p.id} · v${p.version} · ${p.stages} stage${p.stages === 1 ? "" : "s"}` }),
|
||||
h("span", { text: "Filter" }),
|
||||
h("span", { id: "filterCount", class: "count", text: count ? ` (${count})` : "" }),
|
||||
),
|
||||
h("button", {
|
||||
id: "sortToggle",
|
||||
class: `control${panel === "sort" ? " active" : ""}`,
|
||||
text: `Sort: ${pipelineSortLabel(state.pipelineSort)}`,
|
||||
onclick: () => {
|
||||
state.pipelineMenu = panel === "sort" ? null : "sort";
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
h("button", {
|
||||
id: "clearFilters",
|
||||
class: "ghost clear",
|
||||
text: "Clear filters",
|
||||
hidden: count === 0,
|
||||
onclick: clearPipelineFilters,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (panel === "filter") controls.append(renderFilterPanel());
|
||||
if (panel === "sort") controls.append(renderSortPanel());
|
||||
return controls;
|
||||
}
|
||||
|
||||
function renderFilterPanel() {
|
||||
const filters = state.pipelineFilters;
|
||||
const panel = h("div", { class: "menu-panel filter-panel" });
|
||||
panel.append(h("div", { class: "filter-section", text: "Name" }));
|
||||
panel.append(
|
||||
h(
|
||||
"label",
|
||||
{ class: "filter-field" },
|
||||
h("span", { class: "filter-field-label", text: "Pipeline name contains" }),
|
||||
h("input", {
|
||||
id: "pipelineNameFilter",
|
||||
type: "text",
|
||||
value: filters.name,
|
||||
spellcheck: "false",
|
||||
oninput: (e) => {
|
||||
state.pipelineFilters = { ...state.pipelineFilters, name: e.target.value };
|
||||
// Targeted refresh: the input keeps focus and its value while the
|
||||
// list narrows behind it.
|
||||
refreshPipelineRows();
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
panel.append(h("div", { class: "filter-section", text: "Runs" }));
|
||||
for (const presence of RUN_PRESENCES) {
|
||||
panel.append(
|
||||
h(
|
||||
"label",
|
||||
{ class: "filter-item" },
|
||||
h("input", {
|
||||
type: "radio",
|
||||
name: "runPresence",
|
||||
checked: filters.presence === presence.key,
|
||||
onchange: () => {
|
||||
state.pipelineFilters = { ...state.pipelineFilters, presence: presence.key };
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
h("span", { text: presence.label }),
|
||||
),
|
||||
);
|
||||
}
|
||||
return list;
|
||||
panel.append(h("div", { class: "filter-section", text: "Last run status" }));
|
||||
for (const status of RUN_STATUS_FILTERS) {
|
||||
panel.append(
|
||||
h(
|
||||
"label",
|
||||
{ class: "filter-item" },
|
||||
h("input", {
|
||||
id: `status-${status}`,
|
||||
type: "checkbox",
|
||||
checked: filters.lastRunStatuses.includes(status),
|
||||
onchange: (e) => {
|
||||
const next = e.target.checked
|
||||
? [...state.pipelineFilters.lastRunStatuses, status]
|
||||
: state.pipelineFilters.lastRunStatuses.filter((s) => s !== status);
|
||||
state.pipelineFilters = { ...state.pipelineFilters, lastRunStatuses: next };
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
h("span", { text: status }),
|
||||
),
|
||||
);
|
||||
}
|
||||
panel.append(
|
||||
h("div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearPipelineFilters })),
|
||||
);
|
||||
return panel;
|
||||
}
|
||||
|
||||
function renderSortPanel() {
|
||||
const panel = h("div", { class: "menu-panel sort-panel" });
|
||||
for (const option of PIPELINE_SORTS) {
|
||||
panel.append(
|
||||
h("button", {
|
||||
class: `sort-option${state.pipelineSort === option.key ? " active" : ""}`,
|
||||
text: option.label,
|
||||
onclick: () => {
|
||||
state.pipelineSort = option.key;
|
||||
state.pipelineMenu = null;
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
panel.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "filter-actions" },
|
||||
h("button", {
|
||||
class: "ghost",
|
||||
text: "Reset",
|
||||
onclick: () => {
|
||||
state.pipelineSort = "server_order";
|
||||
state.pipelineMenu = null;
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
return panel;
|
||||
}
|
||||
|
||||
/** Re-renders the rows and the toolbar's active-filter badge after a filter change. */
|
||||
function refreshPipelineRows() {
|
||||
const rows = document.getElementById("pipelineRows");
|
||||
if (rows) fillPipelineRows(rows);
|
||||
const count = pipelineFilterCount(state.pipelineFilters);
|
||||
const badge = document.getElementById("filterCount");
|
||||
if (badge) badge.textContent = count ? ` (${count})` : "";
|
||||
const clear = document.getElementById("clearFilters");
|
||||
if (clear) clear.hidden = count === 0;
|
||||
}
|
||||
|
||||
/** Sorts, filters and renders the pipeline rows (or the matching empty state) into `rowsEl`. */
|
||||
function fillPipelineRows(rowsEl) {
|
||||
const latestRuns = latestRunByPipeline(state.runs);
|
||||
const runsKnown = state.runsLoaded;
|
||||
const now = Date.now();
|
||||
const nodes = [];
|
||||
if (state.loading && !state.pipelines.length) {
|
||||
nodes.push(h("div", { class: "muted pad", text: "Loading pipelines…" }));
|
||||
} else if (!state.pipelinesLoaded) {
|
||||
nodes.push(h("div", { class: "muted pad", text: "Connect to the server to load pipelines." }));
|
||||
} else {
|
||||
const sorted = sortPipelines(state.pipelines, state.pipelineSort, latestRuns);
|
||||
const items = filterPipelines(sorted, state.pipelineFilters, latestRuns, runsKnown);
|
||||
if (items.length) {
|
||||
for (const pipeline of items) nodes.push(renderPipelineRow(pipeline, latestRuns, runsKnown, now));
|
||||
} else {
|
||||
const empty = pipelineListEmptyState(state.pipelines, items, state.pipelineFilters);
|
||||
const box = h("div", { class: "empty pad" }, h("div", { class: "muted", text: empty.message }));
|
||||
if (empty.clearAction) {
|
||||
box.append(h("button", { class: "ghost", text: empty.clearAction, onclick: clearPipelineFilters }));
|
||||
}
|
||||
nodes.push(box);
|
||||
}
|
||||
}
|
||||
rowsEl.replaceChildren(...nodes);
|
||||
}
|
||||
|
||||
function renderPipelineRow(pipeline, latestRuns, runsKnown, now) {
|
||||
const children = [
|
||||
h("span", { class: "row-title", text: pipeline.name || `pipeline ${pipeline.id}` }),
|
||||
h("span", { class: "row-meta", text: pipelineSubtitle(pipeline) }),
|
||||
];
|
||||
const updated = pipelineUpdatedLine(pipeline);
|
||||
if (updated) children.push(h("span", { class: "row-meta", text: updated }));
|
||||
if (runsKnown) {
|
||||
const run = latestRuns.get(pipeline.id);
|
||||
if (!run) {
|
||||
children.push(h("span", { class: "row-meta muted", text: "no runs recorded" }));
|
||||
} else {
|
||||
const badge = runBadge(run, now);
|
||||
children.push(
|
||||
h(
|
||||
"span",
|
||||
{ class: "row-run" },
|
||||
h("span", { class: `chip chip-${badge.state}`, text: badge.state }),
|
||||
h("span", { class: "row-meta", text: runBadgeMetaLine(badge) }),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
return h(
|
||||
"button",
|
||||
{ class: `row${state.selectedPipelineId === pipeline.id ? " selected" : ""}`, onclick: () => selectPipeline(pipeline) },
|
||||
...children,
|
||||
);
|
||||
}
|
||||
|
||||
function renderPipelineDetail() {
|
||||
@@ -262,40 +497,91 @@ function renderPipelineDetail() {
|
||||
pane.append(h("div", { class: "muted pad", text: "Select a pipeline." }));
|
||||
return pane;
|
||||
}
|
||||
pane.append(h("h2", { text: d.name || `pipeline ${d.id}` }));
|
||||
pane.append(
|
||||
h("h2", { text: d.name || `pipeline ${d.id}` }),
|
||||
h(
|
||||
"div",
|
||||
{ class: "kv" },
|
||||
kv("ID / version", `#${d.id} · v${d.version}`),
|
||||
kv("Stages", String(d.stages ?? (d.graph?.stages?.length ?? 0))),
|
||||
kv("Content hash", d.content_hash || "—"),
|
||||
kv("Created", fmtTime(d.created_at)),
|
||||
kv("Updated", fmtTime(d.updated_at)),
|
||||
kv("Latest version", d.latest_version ? String(d.latest_version) : "—"),
|
||||
{ class: "detail-tabs" },
|
||||
...PIPELINE_DETAIL_TABS.map((tab) =>
|
||||
h("button", {
|
||||
class: `detail-tab${state.pipelineTab === tab.key ? " active" : ""}`,
|
||||
text: tab.label,
|
||||
onclick: () => {
|
||||
state.pipelineTab = tab.key;
|
||||
renderContent();
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const stages = d.graph?.stages ?? [];
|
||||
if (stages.length) {
|
||||
pane.append(h("h3", { text: "Stages" }));
|
||||
const ul = h("ul", { class: "stages" });
|
||||
for (const s of stages) {
|
||||
const outcomes = Object.keys(s.edges ?? {}).join(", ");
|
||||
ul.append(
|
||||
h(
|
||||
"li",
|
||||
{},
|
||||
h("code", { text: s.key }),
|
||||
s.type ? h("span", { class: "chip", text: s.type }) : null,
|
||||
outcomes ? h("span", { class: "muted", text: `→ ${outcomes}` }) : null,
|
||||
),
|
||||
);
|
||||
if (state.pipelineTab === "graph") {
|
||||
pane.append(h("p", { class: "graph-note muted", text: graphNote() }));
|
||||
return pane;
|
||||
}
|
||||
if (state.pipelineTab === "source") {
|
||||
pane.append(h("pre", { class: "source-code" }, h("code", { text: d.source || "" })));
|
||||
return pane;
|
||||
}
|
||||
pane.append(h("div", { class: "detail-subtitle muted", text: pipelineSubtitle({ ...d, stages: d.graph?.stages?.length ?? d.stages }) }));
|
||||
const rows = h("div", { class: "kv" });
|
||||
for (const field of summaryFields(d)) {
|
||||
rows.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "kv-row" },
|
||||
h("span", { class: "kv-key", text: field.key }),
|
||||
h("span", { class: `kv-val${field.monospace ? " monospace" : ""}`, text: field.value }),
|
||||
),
|
||||
);
|
||||
}
|
||||
pane.append(rows);
|
||||
pane.append(
|
||||
h(
|
||||
"button",
|
||||
{
|
||||
class: "section-toggle",
|
||||
onclick: () => {
|
||||
state.versionsExpanded = !state.versionsExpanded;
|
||||
renderContent();
|
||||
},
|
||||
},
|
||||
h("span", { class: "chevron", text: state.versionsExpanded ? "\u25be" : "\u25b8" }),
|
||||
h("span", { text: "Versions" }),
|
||||
),
|
||||
);
|
||||
if (state.versionsExpanded) {
|
||||
const versions = d.versions ?? [];
|
||||
const body = h("div", { class: "section-body versions-list" });
|
||||
if (!versions.length) {
|
||||
body.append(h("div", { class: "muted", text: "No versions recorded." }));
|
||||
} else {
|
||||
for (const version of versions) {
|
||||
const row = versionRow(version);
|
||||
body.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "version-row" },
|
||||
h("span", { class: "version-title", text: row.versionLabel }),
|
||||
h("span", { class: "muted", text: row.stagesText }),
|
||||
row.createdText ? h("span", { class: "muted", text: row.createdText }) : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
pane.append(ul);
|
||||
pane.append(body);
|
||||
}
|
||||
return pane;
|
||||
}
|
||||
|
||||
function pipelineSortLabel(key) {
|
||||
return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label;
|
||||
}
|
||||
|
||||
function clearPipelineFilters() {
|
||||
state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS };
|
||||
renderContent();
|
||||
}
|
||||
|
||||
function renderRunList() {
|
||||
const pane = h("div", { class: "list runs" });
|
||||
pane.append(renderRunToolbar());
|
||||
@@ -725,10 +1011,19 @@ async function loadCurrentView(force = false) {
|
||||
try {
|
||||
if (state.view === "pipelines") {
|
||||
state.pipelines = await repo.listPipelines();
|
||||
state.pipelinesLoaded = true;
|
||||
// The last-run line joins list_runs onto the pipelines, so the history is
|
||||
// fetched alongside them; runsLoaded distinguishes a genuinely empty
|
||||
// history from one that has not arrived yet.
|
||||
const { runs, usage } = await repo.listRuns();
|
||||
state.runs = runs;
|
||||
if (usage) state.usage = usage;
|
||||
state.runsLoaded = true;
|
||||
} else {
|
||||
const { runs, usage } = await repo.listRuns();
|
||||
state.runs = runs;
|
||||
state.usage = usage;
|
||||
state.runsLoaded = true;
|
||||
}
|
||||
state.loading = false;
|
||||
renderContent();
|
||||
@@ -744,6 +1039,8 @@ async function loadCurrentView(force = false) {
|
||||
async function selectPipeline(summary) {
|
||||
state.selectedPipelineId = summary.id;
|
||||
state.pipelineDetail = null;
|
||||
state.pipelineTab = "summary";
|
||||
state.versionsExpanded = false;
|
||||
renderContent();
|
||||
try {
|
||||
state.pipelineDetail = await repo.getPipeline(summary.id, summary.version);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user