web: URL routes, deep links and history navigation (L6)

This commit is contained in:
2026-10-19 14:45:57 +01:00
parent bcc3835fba
commit 895ed9d8b7
8 changed files with 1669 additions and 60 deletions
+540 -44
View File
@@ -1,7 +1,7 @@
// Spike web UI: pipeline list + run detail over the live WebSocket protocol.
// Deliberately small and DOM-only (no framework, no build step). Every value
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesClient, ProtocolError } from "./client.js";
import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js";
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
@@ -56,8 +56,10 @@ import {
PIPELINE_GRAPH_EMPTY,
RUN_GRAPH_MISSING,
RUN_GRAPH_NOTE,
layoutGraph,
mount as mountGraph,
} from "./graph.js";
import { DEFAULT_ROUTE, parseRoute, serializeRoute } from "./routes.js";
import {
PIPELINE_SORTS,
PIPELINE_DETAIL_TABS,
@@ -407,6 +409,18 @@ const state = {
runDetail: null,
selectedPipelineId: null,
selectedRunId: null,
// The version the selected pipeline detail was requested at (0 = latest), and
// the stage whose definition pane is open. Both are part of the URL route.
pipelineRequestedVersion: 0,
pipelineGraphSelection: null,
// The URL route model (L6): the route currently rendered, the one pending until
// the first successful connection opens it, whether that first connection has
// happened, and a re-entrancy guard for popstate-driven application.
route: { ...DEFAULT_ROUTE },
pendingRoute: null,
routeFirstConnect: false,
routeApplying: false,
popPending: false,
// 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.
@@ -1082,13 +1096,12 @@ function tabButton(view, label) {
class: `tab${state.view === view ? " active" : ""}`,
text: label,
onclick: () => {
state.view = view;
state.error = "";
renderContent();
if (view === "runs" && !state.runs.length) loadCurrentView();
if (view === "pipelines" && !state.pipelines.length) loadCurrentView();
if (view === "templates" && !state.templates.length) loadCurrentView();
if (view === "chat" && !state.chatLoaded) loadCurrentView();
// A top-level tab is a real destination: it updates the URL and lets one
// route application set the view, selection and any list load. Pushing
// first means a load failure can still replace the URL honestly.
const route = { kind: view };
pushRoute(route);
applyRoute(route);
},
});
}
@@ -1368,11 +1381,9 @@ function resetTemplateSelection() {
* unchanged — this is the same destination the Templates tab opens.
*/
function openTemplatesFromSettings() {
state.view = "templates";
state.error = "";
resetTemplateSelection();
renderContent();
if (!state.templates.length) loadCurrentView();
const route = { kind: "templates" };
pushRoute(route);
applyRoute(route);
}
function renderSettingsTemplates() {
@@ -1668,6 +1679,20 @@ function renderPipelineDetail() {
pane.append(host);
state.pipelineGraph = mountGraph(host, d.graph, {
expanded: state.pipelineGraphExpanded,
selectedKey: state.pipelineGraphSelection,
onSelectionChange: (key) => {
// The graph has already opened or closed its own definition pane; record
// the destination in the URL without rebuilding the graph.
state.pipelineGraphSelection = key;
const id = state.selectedPipelineId;
if (!id) return;
const version = state.pipelineRequestedVersion ?? 0;
pushRoute(
key
? { kind: "pipelineStage", id, version, stageKey: key }
: { kind: "pipeline", id, version },
);
},
onExpandedChange: (value) => {
state.pipelineGraphExpanded = value;
},
@@ -3083,19 +3108,30 @@ function openArtifactFromVerdict(artifact, step, resolved) {
}
/** Open the stage pane for one visit of a stage and move focus into it. */
function openStagePane(stageKey, visitIndex) {
function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) {
state.runStagePane = { stageKey, visitIndex };
state.runStageSections = new Set();
if (updateRoute && state.selectedRunId) {
pushRoute({
kind: "runStage",
id: state.selectedRunId,
stageKey,
visit: Number.isSafeInteger(visitIndex) && visitIndex >= 0 ? visitIndex : null,
});
}
renderContent();
document.querySelector(".stage-pane-back")?.focus();
}
/** Close the stage pane, returning focus to the timeline row that opened it. */
function closeStagePane() {
function closeStagePane({ updateRoute = true } = {}) {
const closing = state.runStagePane;
if (!closing) return;
state.runStagePane = null;
state.runStageSections = new Set();
if (updateRoute && state.selectedRunId) {
pushRoute({ kind: "run", id: state.selectedRunId });
}
renderContent();
const row = [...document.querySelectorAll(".timeline-row")].find(
(node) => node.dataset.stageKey === closing.stageKey && node.dataset.visitIndex === String(closing.visitIndex),
@@ -6619,7 +6655,300 @@ async function onConnected() {
// the Settings card is the one `loadCurrentView` already performs (Settings is
// local, so that path is a single render and nothing is fetched twice).
renderBanner();
// A URL opened before the socket was up is the pending destination: the first
// successful connection loads its list and then its detail/stage. Later
// reconnects keep the ordinary current-view refresh and never replay a link.
if (!state.routeFirstConnect) {
state.routeFirstConnect = true;
const route = state.pendingRoute ?? state.route ?? DEFAULT_ROUTE;
state.pendingRoute = null;
await applyRoute(route);
return;
}
await loadCurrentView();
// A reconnect after a network drop must also re-hydrate an open detail: the
// route (and its URL) can survive a drop, but a detail that was never loaded —
// or was cleared while disconnected — has to be fetched again, otherwise the
// URL and the rendered view disagree. Only the URL-bearing detail routes do
// this; the list destinations were just refreshed above.
const route = state.route;
if (
route &&
(route.kind === "run" ||
route.kind === "runStage" ||
route.kind === "pipeline" ||
route.kind === "pipelineStage")
) {
await applyRoute(route);
}
}
// ---------------------------------------------------------------------------
// URL routes (L6)
// ---------------------------------------------------------------------------
/** The view a route renders in: details belong to their list's destination. */
function viewForRoute(route) {
switch (route?.kind) {
case "pipeline":
case "pipelineStage":
return "pipelines";
case "run":
case "runStage":
return "runs";
case "template":
return "templates";
case "runs":
case "chat":
case "settings":
case "templates":
return route.kind;
default:
return "pipelines";
}
}
/** Record a user move in history. Only a real URL change pushes an entry. */
function pushRoute(route) {
const url = serializeRoute(route);
const current = `${location.pathname}${location.search}`;
if (url !== current) {
try {
history.pushState(null, "", url);
} catch {
// A non-HTTP location (file://) may refuse history; local state still moves.
}
}
state.route = route;
// Only an untouched boot deep link is replayed after connecting. A move the
// operator made while still disconnected (a tab, a selection, Back/Forward) is
// now the destination the URL shows, so the stale boot link must not win.
state.pendingRoute = null;
}
/** Correct the current entry in place (a missing entity, a consumed action). */
function replaceRoute(route) {
const url = serializeRoute(route);
const current = `${location.pathname}${location.search}`;
if (url !== current) {
try {
history.replaceState(null, "", url);
} catch {
// See pushRoute.
}
}
state.route = route;
state.pendingRoute = null;
}
/**
* Apply a route to the local view and, when connected, load exactly what it
* needs: the destination list first on a boot deep link, then the requested
* detail/stage. Same-id data already in hand is not refetched, so Back from a
* stage route only closes the pane. Total: every failure ends in an honest list
* fallback rather than a throw.
*/
async function applyRoute(route) {
const r = route && typeof route === "object" ? route : { ...DEFAULT_ROUTE };
state.routeApplying = true;
const connected = () => state.connection.kind === "connected";
try {
state.route = r;
// Applying a route is itself a navigation decision (popstate, a push, or the
// boot link): the pending boot link is never allowed to override it later.
state.pendingRoute = null;
state.error = "";
state.loading = false;
state.view = viewForRoute(r);
// A run detail's poll belongs to the Runs view only. Moving to any other
// destination stops it, including a destination that keeps the selection id.
if (state.view !== "runs") stopRunPoll();
if (r.kind === "pipelines") {
// A default destination reached from an unknown or malformed path (a boot
// deep link or a Back entry) corrects the address bar so the URL and the
// rendered list agree; on the canonical /pipelines this is a no-op.
if (`${location.pathname}${location.search}` !== "/pipelines") {
replaceRoute({ kind: "pipelines" });
}
state.selectedPipelineId = null;
resetPipelineDetailState();
renderContent();
// Mirror the old tab handler: an unfetched destination while disconnected
// still says `Connect to the server first.` rather than showing a silent
// empty list. Once connected this is the list load the route needs.
if (!state.pipelines.length) await loadCurrentView();
return;
}
if (r.kind === "runs") {
state.selectedRunId = null;
state.runDetail = null;
state.runStagePane = null;
state.runStageSections = new Set();
state.decisionOpen = false;
state.runDecision = null;
stopRunPoll();
renderContent();
if (!state.runs.length) await loadCurrentView();
return;
}
if (r.kind === "pipeline" || r.kind === "pipelineStage") {
const version = Number.isSafeInteger(r.version) ? r.version : 0;
const same =
state.selectedPipelineId === r.id &&
state.pipelineDetail != null &&
state.pipelineRequestedVersion === version;
state.view = "pipelines";
if (same) {
if (r.kind === "pipelineStage") {
if (!pipelineHasStage(state.pipelineDetail, r.stageKey)) {
state.pipelineGraphSelection = null;
state.pipelineTab = "graph";
replaceRoute({ kind: "pipeline", id: r.id, version });
renderContent();
return;
}
state.pipelineTab = "graph";
state.pipelineGraphSelection = r.stageKey;
} else {
// The detail route itself does not name a section; keep the tab and
// only close the stage pane.
state.pipelineGraphSelection = null;
}
renderContent();
return;
}
state.selectedPipelineId = r.id;
state.pipelineRequestedVersion = version;
state.pipelineDetail = null;
state.pipelineTab = r.kind === "pipelineStage" ? "graph" : "summary";
state.pipelineGraphSelection = r.kind === "pipelineStage" ? r.stageKey : null;
renderContent();
if (!connected()) return;
if (!state.pipelinesLoaded) await loadCurrentView();
await selectPipeline({ id: r.id, version }, { updateRoute: false });
if (r.kind === "pipelineStage" && state.view === "pipelines" && state.pipelineDetail) {
if (!pipelineHasStage(state.pipelineDetail, r.stageKey)) {
// A path naming a stage the loaded graph does not declare is accepted by
// the (data-blind) parser but cannot open a pane: mirror the missing-entity
// fallbacks and replace the URL with the pipeline itself.
state.pipelineGraphSelection = null;
state.pipelineTab = "graph";
replaceRoute({ kind: "pipeline", id: r.id, version });
renderContent();
return;
}
state.pipelineTab = "graph";
state.pipelineGraphSelection = r.stageKey;
renderContent();
}
return;
}
if (r.kind === "run" || r.kind === "runStage") {
state.view = "runs";
const same = state.selectedRunId === r.id && state.runDetail != null;
if (!same) {
state.selectedRunId = r.id;
resetRunDetailState();
renderContent();
if (!connected()) return;
if (!state.runsLoaded) await loadCurrentView();
await selectRun(r.id, { updateRoute: false });
}
if (!connected() || !state.runDetail || state.runDetail.id !== r.id) return;
if (r.kind === "runStage") {
// No ?visit means the stage's most recent visit, exactly as the graph's
// own node click opens it; the URL stays without a visit. A valid but
// out-of-range index is clamped to the stage's last visit and the entry
// corrected, so the address bar and the pane agree (renderStagePane
// already clamps, which is why the two must not diverge).
const visits = runTimeline(state.runDetail.steps ?? []).visitsByStage.get(r.stageKey) ?? [];
// A key that is neither visited nor a node of the loaded run graph cannot
// open a pane. Mirror the pipeline-stage fallback: show the run itself and
// correct the URL rather than leaving an empty pane under a stage path.
if (!visits.length && !layoutGraph(state.runDetail.graph).nodes.some((node) => node.key === r.stageKey)) {
state.runStagePane = null;
state.runStageSections = new Set();
replaceRoute({ kind: "run", id: r.id });
renderContent();
return;
}
const wanted = r.visit == null ? Math.max(0, visits.length - 1) : r.visit;
const visit = clampVisitIndex(wanted, visits.length);
state.runStagePane = { stageKey: r.stageKey, visitIndex: visit };
state.runStageSections = new Set();
renderContent();
if (r.visit != null && visit !== r.visit) {
replaceRoute({ kind: "runStage", id: r.id, stageKey: r.stageKey, visit });
}
} else {
if (state.runStagePane) {
state.runStagePane = null;
state.runStageSections = new Set();
renderContent();
}
consumeRunAction(r);
}
return;
}
if (r.kind === "templates") {
// Entering the gallery leaves any template detail (and a create dialog
// opened for it) behind, exactly as the Settings card did before routing.
resetTemplateSelection();
renderContent();
if (!state.templates.length) await loadCurrentView();
return;
}
if (r.kind === "template") {
// A route that names a different template reseeds the detail: a create
// dialog and its typed name belong to the template they were opened on.
// A same-route re-apply keeps them, so a push or replace is not a reset.
if (state.selectedTemplateKey !== r.key) resetTemplateCreateState();
state.selectedTemplateKey = r.key;
renderContent();
if (!state.templates.length) await loadCurrentView();
return;
}
if (r.kind === "chat") {
renderContent();
if (!state.chatLoaded) await loadCurrentView();
return;
}
// Settings is local; the fallback covers any route kind a caller invents.
state.view = "settings";
state.error = "";
renderContent();
} finally {
state.routeApplying = false;
// A Back/Forward that arrived while a load was in flight still wins: apply
// the location the browser actually shows now, once this pass is done.
if (state.popPending) {
state.popPending = false;
applyRoute(parseRoute(location.pathname, location.search));
}
}
}
/**
* A run URL's one-shot `?action=decide` (the notification analogue): after the
* run loads, open the existing decision sheet only when the run is genuinely
* waiting, then replace the entry with the action-free /runs/:id so a refresh
* does not reopen it. Never invents a decision.
*/
function consumeRunAction(route) {
if (!route?.action) return;
const action = route.action;
replaceRoute({ kind: "run", id: route.id });
if (action !== "decide") return;
const decision = pendingDecision(state.runDetail);
if (decision) openDecisionSheet(decision);
}
async function loadCurrentView(force = false) {
@@ -6661,6 +6990,14 @@ async function loadCurrentView(force = false) {
state.runs = runs;
state.usage = usage;
state.runsLoaded = true;
// The nav badge reads `Pipelines (${state.pipelines.length})`, so the Runs
// destination (and a run deep link) loads the pipeline list too when it has
// not been seen: an empty `state.pipelines` would show a false `Pipelines (0)`
// until the Pipelines tab was visited.
if (!state.pipelinesLoaded) {
state.pipelines = await repo.listPipelines();
state.pipelinesLoaded = true;
}
}
state.loading = false;
renderContent();
@@ -6710,57 +7047,185 @@ async function validateTemplate(entry) {
}
function selectTemplate(key) {
state.selectedTemplateKey = key;
if (key) pushRoute({ kind: "template", key });
else pushRoute({ kind: "templates" });
state.selectedTemplateKey = key || null;
resetTemplateCreateState();
renderContent();
}
async function selectPipeline(summary) {
state.selectedPipelineId = summary.id;
/**
* The run/pipeline detail reset a different selection needs: no stale pane,
* dialog or tab from the entity the operator navigated away from. Shared by the
* in-page selection and the URL route so both open the same fresh detail.
*/
function resetRunDetailState() {
state.runGraph?.unmount();
state.runGraph = null;
state.runDetail = null;
state.runTab = "summary";
state.runSections = new Set();
state.runStagePane = null;
state.runStageSections = new Set();
state.runDecision = null;
state.decisionOpen = false;
state.decisionDraft = new DecisionDraft();
state.decisionSending = false;
state.decisionError = "";
state.confirmKind = null;
state.renameValue = null;
state.actionError = "";
}
/**
* A server refusal (its own `type:"error"` reply) means the entity genuinely does
* not exist. A transport failure — a timeout, a socket drop, a client-side
* NotConnectedError — is not a missing entity, so its deep link is kept (and will
* be hydrated again on reconnect) rather than discarded.
*/
function isServerRefusal(err) {
return err instanceof ProtocolError;
}
/**
* A run the server does not have falls back honestly: the selection is cleared,
* the runs list is shown (and loaded if this was a hard deep link), the server's
* own refusal stays in the page banner, and the URL is replaced with /runs. It
* never throws and never leaves an empty run pane carrying a stale identity.
*/
async function missingRunFallback(err) {
stopRunPoll();
resetRunDetailState();
state.selectedRunId = null;
state.view = "runs";
if (state.connection.kind === "connected" && !state.runsLoaded) {
await loadCurrentView();
}
state.error = describeError(err);
replaceRoute({ kind: "runs" });
renderContent();
}
/**
* The pipeline-side reset a different selection (or a refusal) needs. The
* selection ids are the caller's, so only the detail it describes is cleared.
*/
function resetPipelineDetailState() {
state.pipelineDetail = null;
state.pipelineTab = "summary";
state.pipelineGraphSelection = null;
state.versionsExpanded = false;
}
/**
* Whether the loaded graph can select a stage key. The route parser cannot know
* the keys without data, so the wiring checks and falls back honestly. The
* mounted graph selects every laid-out node — named stages and the two terminals
* (`#success`/`#failure`) — and the URL it writes for any of them must re-open
* the same pane, so the check uses the same layout rather than stages alone.
*/
function pipelineHasStage(detail, key) {
return layoutGraph(detail?.graph).nodes.some((node) => node.key === key);
}
/** The pipeline counterpart of missingRunFallback: list, banner, /pipelines. */
async function missingPipelineFallback(err) {
resetPipelineDetailState();
state.selectedPipelineId = null;
state.view = "pipelines";
if (state.connection.kind === "connected" && !state.pipelinesLoaded) {
await loadCurrentView();
}
state.error = describeError(err);
replaceRoute({ kind: "pipelines" });
renderContent();
}
/** The pipeline selection this reply was requested for is still the shown one. */
function pipelineStillSelected(id, version) {
return (
state.view === "pipelines" &&
state.selectedPipelineId === id &&
state.pipelineRequestedVersion === version
);
}
async function selectPipeline(summary, { updateRoute = true } = {}) {
const id = summary.id;
const version = Number.isSafeInteger(summary.version) && summary.version > 0 ? summary.version : 0;
if (updateRoute) pushRoute({ kind: "pipeline", id, version });
state.view = "pipelines";
state.selectedPipelineId = id;
state.pipelineRequestedVersion = version;
resetPipelineDetailState();
// A selection describes only itself: a previous refusal banner must not sit
// above the entity the operator has just opened.
state.error = "";
renderContent();
try {
state.pipelineDetail = await repo.getPipeline(summary.id, summary.version);
const detail = await repo.getPipeline(id, version);
// The operator may have moved on while this reply was in flight (a tab, a
// different pipeline, Back/Forward). A late reply must not repaint an entity
// beside a URL that no longer names it.
if (!pipelineStillSelected(id, version)) return;
state.pipelineDetail = detail;
renderContent();
} catch (err) {
setError(err);
if (!pipelineStillSelected(id, version)) return;
if (isServerRefusal(err)) {
await missingPipelineFallback(err);
return;
}
// A transient failure keeps the deep link; the reconnect re-hydrates it.
state.error = describeError(err);
renderContent();
}
}
async function selectRun(id, { silent = false } = {}) {
/** The run this reply was requested for is still the shown one. */
function runStillSelected(id) {
return state.view === "runs" && state.selectedRunId === id;
}
async function selectRun(id, { silent = false, updateRoute = true } = {}) {
if (!silent && updateRoute) pushRoute({ kind: "run", id });
state.selectedRunId = id;
if (!silent) {
// A different run reseeds the detail: Summary tab, every section closed and
// no stage pane left over from the run the operator navigated away from. Drop
// the mounted run graph first so a live run's timer can never outlive it.
state.runGraph?.unmount();
state.runGraph = null;
state.runDetail = null;
state.runTab = "summary";
state.runSections = new Set();
state.runStagePane = null;
state.runStageSections = new Set();
// A different run reseeds the run-level action state, so a decision sheet,
// confirm dialog, rename field or failure report never leaks across runs.
state.runDecision = null;
state.decisionOpen = false;
state.decisionDraft = new DecisionDraft();
state.decisionSending = false;
state.decisionError = "";
state.confirmKind = null;
state.renameValue = null;
state.actionError = "";
resetRunDetailState();
// See selectPipeline: a refusal about the previous entity is not about this
// one, and a silent poll must never wipe an error the operator should see.
state.error = "";
renderContent();
}
try {
state.runDetail = await repo.getRun(id);
const detail = await repo.getRun(id);
// Ignore a reply for a selection the operator already navigated away from
// (the same guard covers a silent poll whose run was deselected). The poll
// itself is stopped here: a reply discarded for a view that no longer shows
// Runs must not leave a 1 Hz get_run loop running against an unshown run.
if (!runStillSelected(id)) {
stopRunPoll();
return;
}
state.runDetail = detail;
renderContent();
updateRunPoll();
} catch (err) {
if (!silent) setError(err);
else stopRunPoll();
if (!runStillSelected(id)) {
stopRunPoll();
return;
}
if (silent) {
stopRunPoll();
return;
}
if (isServerRefusal(err)) {
await missingRunFallback(err);
return;
}
// A transient failure keeps the deep link; the reconnect re-hydrates it.
state.error = describeError(err);
renderContent();
}
}
@@ -6993,4 +7458,35 @@ window.addEventListener("online", onForegroundActive);
// The attention surface's dismissed identities are loaded once here, before the
// first render, so the bell's badge is correct from the very first paint.
state.attentionDismissed = loadAttentionDismissed();
// One route parse at boot. A deep link is kept pending — the first successful
// connection loads its list and then its detail/stage — while the page paints the
// right destination's shell immediately.
const bootRoute = parseRoute(location.pathname, location.search);
// An unknown or malformed boot path parses to the Pipelines list; correct the
// address bar so the URL and the rendered view agree (the pending deep link, if
// any, is untouched: a real deep link is not the default route).
const bootUrl = `${location.pathname}${location.search}`;
if (bootRoute.kind === "pipelines" && bootUrl !== "/pipelines") {
try {
history.replaceState(null, "", "/pipelines");
} catch {
// A non-HTTP location (file://) may refuse history; the view still renders.
}
}
state.route = bootRoute;
state.pendingRoute = bootRoute;
state.view = viewForRoute(bootRoute);
// Back/Forward move between the views the user actually visited: parse the new
// location and apply it without a document reload. A pop during an in-flight
// application is recorded and re-applied when that pass finishes.
window.addEventListener("popstate", () => {
if (state.routeApplying) {
state.popPending = true;
return;
}
applyRoute(parseRoute(location.pathname, location.search));
});
render();
+45 -6
View File
@@ -932,6 +932,11 @@ function pathFromPoints(points) {
* page's `prefers-reduced-motion` setting; when false the
* active stage keeps a static ring instead of pulsing.
* expanded — start with the taller panel.
* selectedKey — open the definition pane for this node at mount (the
* deep-linked stage route) without a synthetic click.
* onSelectionChange — called with the selected node key, or null when the pane
* closes, after the in-graph selection changes. The caller
* records the URL; it must not rebuild the graph to do so.
* onStageTap — called with the node key on a node click. When supplied
* (the run tab), the click opens the caller's own stage
* pane and no definition pane is drawn.
@@ -1157,7 +1162,7 @@ export function mount(container, graph, options = {}) {
view.append(row);
}
function selectNode(key) {
function selectNode(key, { notify = true } = {}) {
state.selectedKey = key;
const node = layout.nodes.find((candidate) => candidate.key === key) ?? null;
const stage = stagesByKey.get(key) ?? null;
@@ -1169,11 +1174,7 @@ export function mount(container, graph, options = {}) {
head.append(title, type);
const close = el("button", "graph-pane-close", "Close");
close.type = "button";
close.addEventListener("click", () => {
pane.hidden = true;
pane.replaceChildren();
state.selectedKey = null;
});
close.addEventListener("click", () => closePane());
head.append(close);
children.push(head);
@@ -1200,6 +1201,19 @@ export function mount(container, graph, options = {}) {
pane.replaceChildren(...children);
pane.hidden = false;
if (notify && typeof options.onSelectionChange === "function") {
options.onSelectionChange(state.selectedKey);
}
}
/** Close the definition pane, telling the caller so it can restore the URL. */
function closePane({ notify = true } = {}) {
pane.hidden = true;
pane.replaceChildren();
state.selectedKey = null;
if (notify && typeof options.onSelectionChange === "function") {
options.onSelectionChange(null);
}
}
// --- Elapsed badge (live run only) ---------------------------------------
@@ -1327,6 +1341,31 @@ export function mount(container, graph, options = {}) {
});
}
// A deep-linked stage opens its pane after the graph is mounted, without a
// synthetic click and without notifying the caller (the URL already says so).
// Bring the pane itself into view: the graph is tall, so a deep link that only
// revealed the pane's header below the fold would not show the stage.
if (options.selectedKey != null) {
const key = String(options.selectedKey);
if (layout.nodes.some((node) => node.key === key)) {
selectNode(key, { notify: false });
// The pane is still detached while the caller builds the detail, so reveal
// it on the next frame, once renderContent has put it in the document. The
// sticky top bar must stay clear of the pane head: scroll to the pane's top
// minus the bar's own measured height (CSS scroll-margin-top is the
// fallback for browsers that reveal it another way).
const reveal = () => {
if (typeof pane.getBoundingClientRect !== "function") return;
const topbar = document.querySelector(".topbar");
const bar = topbar?.getBoundingClientRect?.().height ?? 0;
const top = pane.getBoundingClientRect().top + (window.scrollY ?? 0) - bar - 12;
window.scrollTo?.({ top: Math.max(0, top), behavior: "instant" });
};
if (typeof requestAnimationFrame === "function") requestAnimationFrame(reveal);
else reveal();
}
}
return {
unmount() {
if (elapsedTimer != null) {
+274
View File
@@ -0,0 +1,274 @@
// The page's URL route model (L6). Pure and DOM-free: the parser is total (a
// malformed or unknown location resolves to the default Pipelines list), and the
// serialiser is its inverse for every route the page can produce.
//
// The Android app's `pipelines://run/<id>` deep link becomes a real page route,
// and every destination the app has becomes a URL:
//
// /pipelines Pipelines list
// /pipelines/:id pipeline detail, latest version
// /pipelines/:id/:version pipeline detail at a version (0 = latest)
// /pipelines/:id[/:version]/stage/:key the definition pane's stage
// /runs Runs list
// /runs/:id run detail (optional ?action=decide)
// /runs/:id/stage/:key[?visit=N] one visit's stage pane
// /chat Chat
// /templates template gallery
// /templates/:key template detail
// /settings Settings
// /settings/templates[/:key] aliases for the two template routes
//
// Where a section sits inside a detail (Summary/Graph/Source, run tabs) is
// in-place state, not a route: only the two stage panes are deep-linkable. Search
// is query state owned by the search panel and is never part of a route; unknown
// query parameters are ignored. `/templates` and `/templates/:key` are the
// canonical forms the serialiser emits; the `/settings/...` aliases still parse
// and round-trip to the same route.
/** The destination an unknown or malformed location opens. */
export const DEFAULT_ROUTE = Object.freeze({ kind: "pipelines" });
const ID_PATTERN = /^[0-9]+$/;
/** Decode one path segment, or null when the percent escapes are malformed. */
function decodeSegment(segment) {
try {
return decodeURIComponent(segment);
} catch {
return null;
}
}
/** A positive safe integer id, or null. Mirrors runLinkFromDeepLink's id > 0. */
function parseId(value) {
if (!ID_PATTERN.test(value)) return null;
const id = Number(value);
return Number.isSafeInteger(id) && id > 0 ? id : null;
}
/** A non-negative safe integer (a pipeline version; 0 means latest), or null. */
function parseVersion(value) {
if (!ID_PATTERN.test(value)) return null;
const version = Number(value);
return Number.isSafeInteger(version) ? version : null;
}
/** The `action` query value verbatim, or null; only `decide` has an effect. */
function parseAction(params) {
if (!params) return null;
const action = params.get("action");
return action != null && action !== "" ? action : null;
}
/**
* The zero-based visit index from `?visit=`, or null. A negative, non-integer or
* absent value drops the query while keeping the stage route, exactly as the
* Android extra is optional.
*/
function parseVisit(params) {
if (!params) return null;
const raw = params.get("visit");
if (raw == null || raw === "") return null;
return parseVersion(raw);
}
function parseParams(search) {
if (!search) return null;
const text = String(search).replace(/^\?/, "");
if (!text) return null;
try {
return new URLSearchParams(text);
} catch {
return null;
}
}
/**
* Parse a location-style pathname (and optional search) into a route. Total:
* anything unrecognised — an unknown path, a malformed percent escape, a zero or
* negative run id, a non-numeric version — returns DEFAULT_ROUTE and never
* throws. Unknown query parameters are ignored; `visit` is dropped when invalid.
*/
export function parseRoute(pathname, search = "") {
let raw = pathname == null ? "" : String(pathname);
let query = search == null ? "" : String(search);
// A full URL is accepted too (the smoke and a pasted link use one); its own
// path and query stand in for the arguments.
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
try {
const url = new URL(raw);
if (!query) query = url.search;
raw = url.pathname;
} catch {
return DEFAULT_ROUTE;
}
}
const hash = raw.indexOf("#");
if (hash !== -1) raw = raw.slice(0, hash);
const mark = raw.indexOf("?");
if (mark !== -1) {
if (!query) query = raw.slice(mark);
raw = raw.slice(0, mark);
}
if (!query && typeof search === "string") query = search;
// Normalise trailing slashes: `/runs/` is `/runs`.
const trimmed = raw.replace(/\/+$/, "");
const segments = trimmed.split("/").filter((segment, index) => index > 0 || segment !== "");
if (trimmed === "" || trimmed === "/") return { ...DEFAULT_ROUTE };
const decoded = [];
for (const segment of segments) {
const value = decodeSegment(segment);
if (value == null || value === "") return { ...DEFAULT_ROUTE };
decoded.push(value);
}
const params = parseParams(query);
const [head, second, third, fourth, fifth, ...rest] = decoded;
if (rest.length) return { ...DEFAULT_ROUTE };
if (head === "pipelines" && second == null) return { kind: "pipelines" };
if (head === "runs" && second == null) return { kind: "runs" };
if (head === "chat" && second == null) return { kind: "chat" };
if (head === "settings" && second == null) return { kind: "settings" };
if (head === "templates") {
if (second == null) return { kind: "templates" };
if (third == null) return { kind: "template", key: second };
return { ...DEFAULT_ROUTE };
}
if (head === "settings" && second === "templates") {
if (third == null) return { kind: "templates" };
if (fourth == null) return { kind: "template", key: third };
return { ...DEFAULT_ROUTE };
}
if (head === "pipelines") {
const id = parseId(second);
if (id == null) return { ...DEFAULT_ROUTE };
if (third == null) return { kind: "pipeline", id, version: 0 };
if (third === "stage" && fourth != null && fifth == null) {
return { kind: "pipelineStage", id, version: 0, stageKey: fourth };
}
const version = parseVersion(third);
if (version == null) return { ...DEFAULT_ROUTE };
if (fourth == null) return { kind: "pipeline", id, version };
if (fourth === "stage" && fifth != null) {
return { kind: "pipelineStage", id, version, stageKey: fifth };
}
return { ...DEFAULT_ROUTE };
}
if (head === "runs") {
const id = parseId(second);
if (id == null) return { ...DEFAULT_ROUTE };
if (third == null) {
const action = parseAction(params);
return action == null ? { kind: "run", id } : { kind: "run", id, action };
}
if (third === "stage" && fourth != null && fifth == null) {
const visit = parseVisit(params);
return visit == null
? { kind: "runStage", id, stageKey: fourth }
: { kind: "runStage", id, stageKey: fourth, visit };
}
return { ...DEFAULT_ROUTE };
}
return { ...DEFAULT_ROUTE };
}
function encode(value) {
return encodeURIComponent(String(value));
}
/**
* An id the parser will accept back (a positive safe integer), or null. A
* numeric string is accepted like the parser's own digit-only form.
*/
function serialId(value) {
if (typeof value === "number") {
return Number.isSafeInteger(value) && value > 0 ? value : null;
}
if (typeof value === "string" && ID_PATTERN.test(value)) {
const id = Number(value);
return Number.isSafeInteger(id) && id > 0 ? id : null;
}
return null;
}
/**
* A version the parser will accept back (a non-negative safe integer), or null
* when the value cannot describe one; the caller then emits the latest form so
* the URL still parses to a canonical route.
*/
function serialVersion(value) {
if (value == null) return 0;
if (typeof value === "number") {
return Number.isSafeInteger(value) && value >= 0 ? value : null;
}
if (typeof value === "string" && ID_PATTERN.test(value)) {
const version = Number(value);
return Number.isSafeInteger(version) ? version : null;
}
return null;
}
/**
* Serialise a route to a path + query. Total: an unrecognised object serialises
* to the default Pipelines route rather than throwing. Version 0/absent is
* omitted (it means latest), an absent visit is omitted, and `action` is emitted
* only when present.
*/
export function serializeRoute(route) {
const r = route ?? DEFAULT_ROUTE;
switch (r.kind) {
case "pipelines":
return "/pipelines";
case "runs":
return "/runs";
case "chat":
return "/chat";
case "settings":
return "/settings";
case "templates":
return "/templates";
case "template":
return typeof r.key === "string" && r.key ? `/templates/${encode(r.key)}` : "/templates";
case "pipeline": {
const id = serialId(r.id);
if (id == null) return "/pipelines";
const version = serialVersion(r.version) ?? 0;
return version > 0 ? `/pipelines/${id}/${version}` : `/pipelines/${id}`;
}
case "pipelineStage": {
const id = serialId(r.id);
if (id == null || typeof r.stageKey !== "string" || !r.stageKey) return "/pipelines";
const version = serialVersion(r.version) ?? 0;
const base = version > 0 ? `/pipelines/${id}/${version}` : `/pipelines/${id}`;
return `${base}/stage/${encode(r.stageKey)}`;
}
case "run": {
const id = serialId(r.id);
if (id == null) return "/runs";
const base = `/runs/${id}`;
return r.action ? `${base}?${new URLSearchParams({ action: r.action }).toString()}` : base;
}
case "runStage": {
const id = serialId(r.id);
if (id == null || typeof r.stageKey !== "string" || !r.stageKey) return "/runs";
const base = `/runs/${id}/stage/${encode(r.stageKey)}`;
// A valid visit is a non-negative integer; anything else is omitted.
const visit = Number.isSafeInteger(r.visit) && r.visit >= 0 ? r.visit : null;
return visit == null ? base : `${base}?visit=${visit}`;
}
default:
return "/pipelines";
}
}
/** Two routes are the same when their canonical serialisations agree. */
export function sameRoute(a, b) {
return serializeRoute(a) === serializeRoute(b);
}