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();