From 895ed9d8b7c45e36edb6eae0c6473bd67f62d5f4 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 14:45:57 +0100 Subject: [PATCH] web: URL routes, deep links and history navigation (L6) --- web/PARITY.md | 2 +- web/serve.mjs | 73 ++++- web/src/app.js | 584 ++++++++++++++++++++++++++++++++++++--- web/src/graph.js | 51 +++- web/src/routes.js | 274 ++++++++++++++++++ web/styles.css | 3 + web/test/routes.test.mjs | 288 +++++++++++++++++++ web/test/ui-smoke.mjs | 454 +++++++++++++++++++++++++++++- 8 files changed, 1669 insertions(+), 60 deletions(-) create mode 100644 web/src/routes.js create mode 100644 web/test/routes.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index 67d64de9..09e05168 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -147,7 +147,7 @@ delete command). | L3 | Narrow layout: bottom section strip + bottom navigation | client-side | todo | | L4 | Responsive switch by viewport width (no hardcoded device) | `WindowSize.kt` analogue | todo | | L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived | todo | -| L6 | Deep links to a run (`pipelines://run/…` analogue → URL route) | — | todo | +| L6 | Deep links to a run (`pipelines://run/…` analogue → URL route) | — | done — the page's destinations are real URLs through a pure, total route model in `src/routes.js`: `/pipelines`, `/runs`, `/chat`, `/settings` and `/templates`; `/pipelines/:id` and `/pipelines/:id/:version` (version 0 or absent = latest); `/pipelines/:id[/:version]/stage/:key`; `/runs/:id` with `?action=decide`; `/runs/:id/stage/:key[?visit=N]`; `/settings/templates` and `/settings/templates/:key` parse as aliases of `/templates` and `/templates/:key`. `visit` is a zero-based index into that stage's visits, dropped when invalid while the stage route stays; a malformed or unknown path (a bad percent escape, a zero/negative run id, a non-numeric version or path, or a trailing extra segment on either stage branch, e.g. `/runs/440/stage/planner/extra`) resolves to the Pipelines list and never throws, and search/query state is never a route. The serialiser percent-encodes path segments, omits version 0 and an absent visit, and round-trips under `parse(serialize(…))`; an id, version or key the parser would reject is never emitted — it falls back to the nearest canonical route (an invalid id to the list, an invalid version to latest) so the address bar can never carry a path the parser would discard. `serve.mjs` serves `index.html` for any page route (a first segment naming a destination, so a stage key that ends in an extension — `plan.js`, `plan.v2` — still deep-links) or any non-asset GET, with a root `` so the shell's relative asset URLs resolve under a deep path, while an asset-looking path outside a page prefix such as `/nope.js` stays 404. Navigation moves the URL with `pushState` only on a real change (top-level tabs, pipeline/run/template selection, Settings' Browse templates, opening/closing either stage pane; a user click on a pipeline graph node pushes `/pipelines/:id/:version/stage/:key` through the shared graph's `onSelectionChange` (a synthetic click is never used); a deep-linked stage instead opens at mount through the graph's `selectedKey` option without notifying), and one `popstate` listener parses and applies Back/Forward without a reload; in-detail tabs (Summary/Graph/Source, run tabs) and search stay in-place. A deep link is parsed at boot, kept pending until the first successful connection, and then loaded list-first (later reconnects never replay it; any move made while still disconnected replaces the pending boot link, so the URL and the first connected view agree). An unknown or malformed boot path renders the Pipelines list and `replaceState`s the address bar to the canonical `/pipelines` so the URL and the view agree. A later reconnect refreshes the lists and re-applies the route: the URL and a detail already in hand survive the drop, while a detail that is not in hand (never loaded, or cleared while disconnected) is fetched again. Only a genuine server refusal — never a timeout or a socket drop — discards the deep link. A run link's `?action=decide` opens the existing decision sheet once, only when the run is genuinely waiting, then `replaceState`s to the action-free `/runs/:id`. A valid but out-of-range `?visit=N` is clamped to the stage's last visit and the entry is corrected, so the address bar and the pane agree; a pipeline-stage path naming a key the loaded graph does not declare falls back to `/pipelines/:id[/:version]` rather than leaving a pane-less stage URL, while a key the mounted graph can select — including its `#success`/`#failure` terminals — re-opens the same definition pane (the graph writes those URLs itself, so the loader accepts them). A run-stage path naming a stage that is neither visited nor a node of the run graph falls back to the plain run detail. A deep link to an executing run installs its 1 Hz refresh; leaving Runs for any other destination stops it, and a reply discarded for a view that no longer shows Runs stops it too, so no get_run loop survives the move (asserted in the smoke when an executing run is live). A deep-linked stage pane is revealed clear of the sticky top bar (its head and the Close control stay visible), which the smoke asserts. A run the server does not have falls back honestly to `/runs` — the real list, the server's own refusal in the banner and no stale pane or throw (the same for a missing pipeline → `/pipelines`). A run or run-stage route also loads the pipeline list when it has not been seen, so the nav badge stays honest (`Pipelines (29)` at capture time, never a false `Pipelines (0)`) — asserted in the smoke. Captured 2026-10-19: `captures/L6-deeplink-run-440.png` (a hard navigation to `/runs/440` opening run 440's detail), `captures/L6-deeplink-pipeline-24.png` (a hard navigation to `/pipelines/24` opening `Plan and land`), `captures/L6-deeplink-pipeline-24-stage.png` (a hard navigation to `/pipelines/24/stage/planner` opening the Graph tab and the stage's definition pane in view), `captures/L6-deeplink-pipeline-24-terminal.png` (a hard navigation to `/pipelines/24/stage/%23failure` re-opening the Failure terminal pane — the live graph's first terminal at capture time — with its URL unchanged), `captures/L6-history-back.png` (an in-page Pipelines→Runs→run-detail sequence, then `history.back()` restoring the Runs list, with a window marker proving no reload), `captures/L6-missing-run.png` (`/runs/900000000` landing on `/runs` with the real list — 407 rows at capture time — and the banner `run not found`) and `captures/L6-missing-pipeline.png` (`/pipelines/900000000` landing on `/pipelines` with the real pipeline rows and the server's refusal banner). Parsing, serialisation, version/visit semantics and round-tripping are unit-tested in `test/routes.test.mjs`. **The live server had no waiting run, so the `?action=decide` path was not exercised live**; `test/ui-smoke.mjs` captures the sheet automatically the moment a waiting run exists | | L7 | Accessibility: focus order, labels, keyboard operation | — | todo | ## Deliberately out of scope diff --git a/web/serve.mjs b/web/serve.mjs index 8911638d..23c55e8d 100644 --- a/web/serve.mjs +++ b/web/serve.mjs @@ -33,6 +33,24 @@ const MIME = { ".map": "application/json; charset=utf-8", }; +// A path is asset-looking when its last segment ends in a known file type, and a +// page route when its first segment names one of the client's destinations. A +// stage key may itself end in an extension (`plan.js`): under a page prefix the +// route still serves the shell, while an asset-looking path elsewhere (`/nope.js`) +// stays an honest 404 and a real file (`/src/app.js`) is still served. +const ASSET_EXTENSIONS = new Set([...Object.keys(MIME), ".woff", ".woff2", ".txt"]); +const PAGE_PREFIXES = new Set(["pipelines", "runs", "chat", "settings", "templates"]); + +/** The decoded first path segment, or "" for the root. */ +function firstSegment(pathname) { + const raw = pathname.split("/").filter(Boolean)[0] ?? ""; + try { + return decodeURIComponent(raw); + } catch { + return raw; + } +} + function flag(argv, name, fallback) { const i = argv.indexOf(name); if (i !== -1 && argv[i + 1]) return argv[i + 1]; @@ -43,22 +61,65 @@ function parsePort(argv) { return Number(flag(argv, "--port", process.env.PORT ?? 8090)); } -/** Resolve a request path to a file inside ROOT, or null if it escapes. */ +/** + * Resolve a request path to a file inside ROOT. Returns null when the percent + * escapes are malformed (a guarded decode, so a bad `%` cannot throw out of the + * request handler) and false when the path escapes ROOT; the caller treats the + * first as an unknown page route and the second as forbidden. + */ function resolvePath(urlPath) { - const decoded = decodeURIComponent(urlPath.split("?")[0]); + let decoded; + try { + decoded = decodeURIComponent(urlPath.split("?")[0]); + } catch { + return null; + } const rel = normalize(decoded).replace(/^([/\\])+/, ""); const target = resolve(join(ROOT, rel || "index.html")); - if (target !== ROOT && !target.startsWith(ROOT + sep)) return null; + if (target !== ROOT && !target.startsWith(ROOT + sep)) return false; return target; } +/** Send index.html (the page shell). The router reads the real URL in the browser. */ +async function serveIndex(res) { + const html = await readFile(join(ROOT, "index.html"), "utf8"); + // A deep URL such as /runs/440 would otherwise resolve the shell's relative + // `./src/app.js` against /runs/. A root keeps the shell's own asset URLs + // absolute without changing the address bar (and without editing index.html). + const body = html.replace(//i, '\n '); + res.writeHead(200, { + "Content-Type": MIME[".html"], + "Cache-Control": "no-store", + }); + res.end(body); +} + const server = createServer(async (req, res) => { const pathname = (req.url ?? "/").split("?")[0]; if (pathname === "/favicon.ico") { res.writeHead(204).end(); // no icon; keeps the console free of a 404 return; } + // SPA fallback: a page route (`/runs/440`, `/pipelines/24/5/stage/plan.js`) or a + // non-asset GET serves the shell, so a hard navigation deep-links and the client + // router opens the destination. A path that looks like an asset outside a page + // prefix (`.js`, `.css`, `.png`, …) stays an honest 404, and a malformed escape + // is handled like any other unknown path rather than rejecting the handler. + const assetLike = ASSET_EXTENSIONS.has(extname(pathname).toLowerCase()); + const pageLike = PAGE_PREFIXES.has(firstSegment(pathname)); + const serveShell = pageLike || !assetLike; const target = resolvePath(req.url ?? "/"); + if (target === null) { + // A malformed percent escape is an unknown page route, not a handler throw. + if (serveShell) { + await serveIndex(res).catch(() => { + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); + }); + return; + } + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); + return; + } if (!target) { res.writeHead(403).end("Forbidden"); return; @@ -74,6 +135,12 @@ const server = createServer(async (req, res) => { }); res.end(body); } catch { + if (serveShell) { + await serveIndex(res).catch(() => { + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); + }); + return; + } res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found"); } }); diff --git a/web/src/app.js b/web/src/app.js index 29d088f6..bc2dcf28 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -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(); diff --git a/web/src/graph.js b/web/src/graph.js index c93f8fb3..059a8173 100644 --- a/web/src/graph.js +++ b/web/src/graph.js @@ -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) { diff --git a/web/src/routes.js b/web/src/routes.js new file mode 100644 index 00000000..247af2a3 --- /dev/null +++ b/web/src/routes.js @@ -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/` 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); +} diff --git a/web/styles.css b/web/styles.css index 89b47ead..9857e774 100644 --- a/web/styles.css +++ b/web/styles.css @@ -686,6 +686,9 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- border: 1px solid var(--border); border-radius: 12px; background: var(--surface); + /* A deep-linked stage is revealed with scrollIntoView; keep its head clear of + the sticky top bar instead of hiding it underneath. */ + scroll-margin-top: 70px; } .graph-pane[hidden] { display: none; } .graph-pane-head { display: flex; align-items: center; gap: 8px; } diff --git a/web/test/routes.test.mjs b/web/test/routes.test.mjs new file mode 100644 index 00000000..9e19e85c --- /dev/null +++ b/web/test/routes.test.mjs @@ -0,0 +1,288 @@ +// Unit tests for the pure URL route model (web/src/routes.js). No DOM and no +// server: every case here is a claim the live UI smoke relies on. +import test from "node:test"; +import assert from "node:assert/strict"; +import { + DEFAULT_ROUTE, + parseRoute, + sameRoute, + serializeRoute, +} from "../src/routes.js"; + +const defaultRoute = () => ({ ...DEFAULT_ROUTE }); + +test("default destination: empty, root, unknown and malformed paths", () => { + for (const path of [ + undefined, + null, + "", + "/", + "///", + "/nope", + "/pipelinesx", + "/runs/abc", + "/runs/0", + "/runs/-1", + "/runs/1x", + "/pipelines/x", + "/pipelines/24/-1", + "/pipelines/24/1x", + "/pipelines/24/5/nope", + "/pipelines/24/5/stage", + "/runs/440/stage", + // A trailing segment on a versionless stage branch is malformed, not a + // dropped visit or an ignored extra: both stage branches require exactly + // four segments (the versioned pipeline branch already rejected extras). + "/runs/440/stage/planner/extra", + "/runs/440/stage/planner/2", + "/pipelines/24/stage/planner/extra", + "/pipelines/24/stage/planner/2", + "/runs/%E0%A4%A", + "/pipelines/%E0%A4%A", + "/templates/%E0%A4%A", + "/runs/440/stage/%E0%A4%A", + ]) { + assert.deepEqual(parseRoute(path), defaultRoute(), `path ${JSON.stringify(path)}`); + } +}); + +test("top-level destinations", () => { + assert.deepEqual(parseRoute("/pipelines"), { kind: "pipelines" }); + assert.deepEqual(parseRoute("/runs"), { kind: "runs" }); + assert.deepEqual(parseRoute("/chat"), { kind: "chat" }); + assert.deepEqual(parseRoute("/settings"), { kind: "settings" }); + assert.deepEqual(parseRoute("/templates"), { kind: "templates" }); +}); + +test("trailing slashes are normalised and location-style strings accepted", () => { + assert.deepEqual(parseRoute("/runs/"), { kind: "runs" }); + assert.deepEqual(parseRoute("/runs/440/"), { kind: "run", id: 440 }); + assert.deepEqual(parseRoute("http://127.0.0.1:8090/runs/440?visit=2"), { + kind: "run", + id: 440, + }); + assert.deepEqual(parseRoute("http://127.0.0.1:8090/runs/440"), { kind: "run", id: 440 }); + assert.deepEqual(parseRoute("/runs/440?action=decide"), { kind: "run", id: 440, action: "decide" }); +}); + +test("pipeline detail: absent and zero versions are the same latest route", () => { + const latest = { kind: "pipeline", id: 24, version: 0 }; + assert.deepEqual(parseRoute("/pipelines/24"), latest); + assert.deepEqual(parseRoute("/pipelines/24/0"), latest); + assert.deepEqual(parseRoute("/pipelines/24/5"), { kind: "pipeline", id: 24, version: 5 }); + assert.equal(serializeRoute(parseRoute("/pipelines/24")), "/pipelines/24"); + assert.equal(serializeRoute(parseRoute("/pipelines/24/0")), "/pipelines/24"); + assert.equal(serializeRoute(parseRoute("/pipelines/24/5")), "/pipelines/24/5"); +}); + +test("run detail and the optional decide action", () => { + assert.deepEqual(parseRoute("/runs/440"), { kind: "run", id: 440 }); + assert.deepEqual(parseRoute("/runs/440?action=decide"), { kind: "run", id: 440, action: "decide" }); + assert.equal(serializeRoute({ kind: "run", id: 440 }), "/runs/440"); + assert.equal(serializeRoute({ kind: "run", id: 440, action: "decide" }), "/runs/440?action=decide"); +}); + +test("run stage: optional zero-based visit, invalid visit dropped", () => { + assert.deepEqual(parseRoute("/runs/440/stage/planner"), { + kind: "runStage", + id: 440, + stageKey: "planner", + }); + assert.deepEqual(parseRoute("/runs/440/stage/planner", "?visit=2"), { + kind: "runStage", + id: 440, + stageKey: "planner", + visit: 2, + }); + assert.deepEqual(parseRoute("/runs/440/stage/planner?visit=0"), { + kind: "runStage", + id: 440, + stageKey: "planner", + visit: 0, + }); + // An invalid visit is dropped while the stage route is kept. + for (const query of ["?visit=-1", "?visit=x", "?visit=", "?visit=1.5"]) { + assert.deepEqual(parseRoute("/runs/440/stage/planner", query), { + kind: "runStage", + id: 440, + stageKey: "planner", + }); + } + assert.equal( + serializeRoute({ kind: "runStage", id: 440, stageKey: "planner" }), + "/runs/440/stage/planner", + ); + assert.equal( + serializeRoute({ kind: "runStage", id: 440, stageKey: "planner", visit: 0 }), + "/runs/440/stage/planner?visit=0", + ); + assert.equal( + serializeRoute({ kind: "runStage", id: 440, stageKey: "planner", visit: -1 }), + "/runs/440/stage/planner", + ); +}); + +test("pipeline stage routes, with and without an explicit version", () => { + assert.deepEqual(parseRoute("/pipelines/24/5/stage/planner"), { + kind: "pipelineStage", + id: 24, + version: 5, + stageKey: "planner", + }); + assert.deepEqual(parseRoute("/pipelines/24/stage/planner"), { + kind: "pipelineStage", + id: 24, + version: 0, + stageKey: "planner", + }); + assert.deepEqual(parseRoute("/pipelines/24/0/stage/planner"), { + kind: "pipelineStage", + id: 24, + version: 0, + stageKey: "planner", + }); + assert.equal( + serializeRoute({ kind: "pipelineStage", id: 24, version: 5, stageKey: "planner" }), + "/pipelines/24/5/stage/planner", + ); + assert.equal( + serializeRoute({ kind: "pipelineStage", id: 24, version: 0, stageKey: "planner" }), + "/pipelines/24/stage/planner", + ); +}); + +test("templates gallery and detail, including the /settings aliases", () => { + assert.deepEqual(parseRoute("/templates"), { kind: "templates" }); + assert.deepEqual(parseRoute("/settings/templates"), { kind: "templates" }); + assert.deepEqual(parseRoute("/templates/plan"), { kind: "template", key: "plan" }); + assert.deepEqual(parseRoute("/settings/templates/plan"), { kind: "template", key: "plan" }); + assert.equal(serializeRoute({ kind: "template", key: "plan" }), "/templates/plan"); + assert.equal( + serializeRoute(parseRoute("/settings/templates/plan")), + "/templates/plan", + ); +}); + +test("unknown query state is ignored; only action and visit are read", () => { + assert.deepEqual(parseRoute("/runs/440", "?q=plan&kind=runs&sort=name"), { + kind: "run", + id: 440, + }); + assert.deepEqual(parseRoute("/runs", "?q=plan&kind=pipelines&sort=newest"), { kind: "runs" }); + assert.deepEqual(parseRoute("/runs/440?visit=2"), { kind: "run", id: 440 }); + assert.deepEqual(parseRoute("/runs/440/stage/planner?visit=2&q=x"), { + kind: "runStage", + id: 440, + stageKey: "planner", + visit: 2, + }); +}); + +test("stage and template keys are percent-encoded and round-trip", () => { + const stageKey = "plan/land & go"; + const templateKey = "a b/c?d#e"; + // A dotted key stays one path segment; serve.mjs must not mistake it for an + // asset when the shell is requested for a hard navigation. + assert.deepEqual(parseRoute(serializeRoute({ kind: "pipelineStage", id: 7, version: 2, stageKey: "plan.v2" })), { + kind: "pipelineStage", + id: 7, + version: 2, + stageKey: "plan.v2", + }); + const stage = parseRoute(serializeRoute({ kind: "runStage", id: 7, stageKey, visit: 3 })); + assert.deepEqual(stage, { kind: "runStage", id: 7, stageKey, visit: 3 }); + assert.equal( + serializeRoute({ kind: "pipelineStage", id: 7, version: 2, stageKey }), + "/pipelines/7/2/stage/plan%2Fland%20%26%20go", + ); + assert.deepEqual(parseRoute(serializeRoute({ kind: "template", key: templateKey })), { + kind: "template", + key: templateKey, + }); + assert.equal(serializeRoute({ kind: "template", key: templateKey }), "/templates/a%20b%2Fc%3Fd%23e"); +}); + +test("serialisation is idempotent and parse(serialize(route)) preserves every route", () => { + const routes = [ + { kind: "pipelines" }, + { kind: "runs" }, + { kind: "chat" }, + { kind: "settings" }, + { kind: "templates" }, + { kind: "template", key: "plan" }, + { kind: "pipeline", id: 24, version: 0 }, + { kind: "pipeline", id: 24, version: 5 }, + { kind: "pipelineStage", id: 24, version: 0, stageKey: "planner" }, + { kind: "pipelineStage", id: 24, version: 5, stageKey: "plan/land" }, + { kind: "run", id: 440 }, + { kind: "run", id: 440, action: "decide" }, + { kind: "runStage", id: 440, stageKey: "planner" }, + { kind: "runStage", id: 440, stageKey: "plan/land", visit: 0 }, + ]; + for (const route of routes) { + const url = serializeRoute(route); + const parsed = parseRoute(url); + assert.equal(serializeRoute(parsed), url, `route ${JSON.stringify(route)}`); + assert.ok(sameRoute(parsed, route), `sameRoute ${JSON.stringify(route)}`); + } +}); + +test("sameRoute compares the canonical serialised form", () => { + assert.ok(sameRoute({ kind: "pipeline", id: 24 }, { kind: "pipeline", id: 24, version: 0 })); + assert.ok( + sameRoute( + parseRoute("/settings/templates/plan"), + { kind: "template", key: "plan" }, + ), + ); + assert.ok(!sameRoute({ kind: "run", id: 440 }, { kind: "run", id: 440, action: "decide" })); + assert.ok(!sameRoute({ kind: "runs" }, { kind: "pipelines" })); +}); + +test("a bad route object serialises to the default, never throws", () => { + assert.equal(serializeRoute(null), "/pipelines"); + assert.equal(serializeRoute({}), "/pipelines"); + assert.equal(serializeRoute({ kind: "unknown" }), "/pipelines"); + assert.equal(serializeRoute({ kind: "pipeline" }), "/pipelines"); + assert.equal(serializeRoute({ kind: "runStage", id: 1 }), "/runs"); +}); + +test("the serialiser rejects ids/versions the parser would not accept", () => { + // An invalid id cannot name an entity; the nearest canonical route is the list. + for (const id of [0, -1, 1.5, NaN, Infinity, "abc", "", null]) { + assert.equal(serializeRoute({ kind: "pipeline", id }), "/pipelines", `pipeline id ${String(id)}`); + assert.equal(serializeRoute({ kind: "run", id }), "/runs", `run id ${String(id)}`); + assert.equal( + serializeRoute({ kind: "runStage", id, stageKey: "planner" }), + "/runs", + `runStage id ${String(id)}`, + ); + } + // An invalid or negative version falls back to the latest form, which parses + // back to the same route instead of emitting a path the parser rejects. + for (const version of [-1, 1.5, NaN, "abc", ""]) { + assert.equal( + serializeRoute({ kind: "pipeline", id: 24, version }), + "/pipelines/24", + `pipeline version ${String(version)}`, + ); + assert.equal( + serializeRoute({ kind: "pipelineStage", id: 24, version, stageKey: "planner" }), + "/pipelines/24/stage/planner", + `pipelineStage version ${String(version)}`, + ); + assert.deepEqual(parseRoute(serializeRoute({ kind: "pipelineStage", id: 24, version, stageKey: "planner" })), { + kind: "pipelineStage", + id: 24, + version: 0, + stageKey: "planner", + }); + } + // A blank or non-string key cannot describe a stage/template. + assert.equal(serializeRoute({ kind: "pipelineStage", id: 24, stageKey: "" }), "/pipelines"); + assert.equal(serializeRoute({ kind: "runStage", id: 440, stageKey: "" }), "/runs"); + assert.equal(serializeRoute({ kind: "template", key: "" }), "/templates"); + // A canonical numeric string is emitted as the number the parser reads back. + assert.equal(serializeRoute({ kind: "run", id: "440" }), "/runs/440"); + assert.equal(serializeRoute({ kind: "pipeline", id: "24", version: "5" }), "/pipelines/24/5"); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index f63d79c8..d35ed45d 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -108,13 +108,38 @@ const showComposer = () => // its `online` handler resets the backoff — and waits for the green banner // before the step reads anything. async function ensureConnected(timeout = 25000) { - const ok = await page.evaluate( - `document.querySelector(".conn-banner")?.classList.contains("conn-ok") ?? false`, - ); - if (!ok) await page.evaluate(`window.dispatchEvent(new Event("online"))`); - await page.waitForSelector(".conn-banner.conn-ok", { timeout }); + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const ok = await page.evaluate( + `document.querySelector(".conn-banner")?.classList.contains("conn-ok") ?? false`, + ); + if (ok) return; + // The page's own recovery path: an `online` event resets the client's + // backoff and re-opens the configured endpoint. A dropped long-lived socket + // can take a few tries on the shared server, so nudge until the deadline. + await page.evaluate(`window.dispatchEvent(new Event("online"))`); + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + // One last honest wait, so the failure names the banner selector. + await page.waitForSelector(".conn-banner.conn-ok", { timeout: 2000 }); } +/** + * Hard-navigate to a page route and connect, exactly as a pasted link would: a + * full document load parses the URL at boot and keeps it pending until the socket + * comes up. The configured endpoint is already in localStorage from the live + * run's first connection, so clicking Connect is the same user action. + */ +async function openDeepLink(path) { + await page.goto(`http://127.0.0.1:${port}${path}`); + await page.waitForSelector("#connectBtn", { timeout: 15000 }); + await page.click("#connectBtn"); + await ensureConnected(30000); +} + +/** The current path+query the page shows. */ +const currentLocation = () => page.evaluate(`location.pathname + location.search`); + // Open a run's detail. The connection is asserted first, and if the socket drops // between steps the page's reconnect does not replay the detail request, so the // click is retried once after re-establishing the connection. @@ -2126,7 +2151,9 @@ try { } step("Closing search clears the query and leaves the view intact (S1)"); - await searchTargets("release", "field"); + // `plan` is known to return field hits (the emphasis step above uses it); the + // close assertion only needs a query in flight, not a particular kind. + await searchTargets(SEARCH_QUERY, "field"); const beforeClose = await viewSnapshot(); await page.click("#searchClose"); await eventually(() => page.evaluate(`!document.querySelector("#searchInput")`), { @@ -4684,6 +4711,421 @@ try { ); console.log(" chat_shells re-fetched after the stream reconnect (real request)"); + // --- L6: URL routes, deep links and history ------------------------------- + // Every later hard navigation records uncaught errors/unhandled rejections, so + // a route that throws can never pass as a rendered fallback. + await page.addInitScript(`(() => { + window.__pipelinesPageErrors = []; + window.addEventListener("error", (event) => { + window.__pipelinesPageErrors.push(String(event.message || event.error || "error")); + }); + window.addEventListener("unhandledrejection", (event) => { + window.__pipelinesPageErrors.push(String(event.reason || "unhandled rejection")); + }); + })()`); + + step("L6: deep links, URL routing and Back/Forward"); + await page.clickText("nav.tabs button.tab", "Runs"); + await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); + const discovered = await page.evaluate(`(() => { + const rows = [...document.querySelectorAll(".list.runs .run-row")]; + const idOf = (row) => + Number(row.querySelector(".run-row-meta[data-run-id]")?.dataset.runId ?? 0); + const ids = rows.map(idOf).filter((id) => id > 0); + const waitingRow = rows.find((row) => row.querySelector(".chip-waiting")); + return { + ids, + preferred: ids.includes(440) ? 440 : (ids[0] ?? 0), + waiting: waitingRow ? idOf(waitingRow) : 0, + }; + })()`); + if (!discovered.preferred) throw new Error("L6: no real run id on the Runs list"); + console.log( + ` live run ids on the list: ${discovered.ids.join(", ")} (using ${discovered.preferred})`, + ); + + // An in-page pipeline selection is a real pushState: the detail route records + // the id and version, and the hard link below uses the id it found. + await page.clickText("nav.tabs button.tab", "Pipelines"); + await page.waitForSelector("#pipelineRows button.row", { timeout: 25000 }); + const pipelineSelection = await page.evaluate(`(async () => { + const rows = [...document.querySelectorAll("#pipelineRows button.row")]; + const row = + rows.find((candidate) => + (candidate.querySelector(".row-title")?.textContent ?? "").includes("Plan and land"), + ) ?? rows[0]; + if (!row) return null; + row.click(); + const deadline = Date.now() + 20000; + while (Date.now() < deadline) { + if (document.querySelector(".detail h2")) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + return { + path: location.search ? location.pathname + location.search : location.pathname, + name: document.querySelector(".detail h2")?.textContent ?? "", + }; + })()`); + if (!pipelineSelection?.path) throw new Error("L6: the pipeline detail did not open"); + const pipelineId = Number((/^\/pipelines\/([0-9]+)/.exec(pipelineSelection.path) ?? [])[1] ?? 0); + if (!pipelineId) throw new Error(`L6: pipeline detail route ${JSON.stringify(pipelineSelection.path)}`); + console.log( + ` in-page pipeline selection pushed ${pipelineSelection.path} (${JSON.stringify(pipelineSelection.name)})`, + ); + + // A hard navigation to a run route: boot parses the URL, the first connection + // loads the runs list and then the run, and the detail owns the requested id. + const runPath = `/runs/${discovered.preferred}`; + await openDeepLink(runPath); + await eventually( + () => + page.evaluate( + `document.querySelector(".run-detail .run-identity")?.textContent?.startsWith("run ${discovered.preferred} ") ?? false`, + ), + { timeout: 30000, what: `the deep-linked run ${discovered.preferred}` }, + ); + const deepRunUrl = await currentLocation(); + if (deepRunUrl !== runPath) throw new Error(`L6: run URL is ${deepRunUrl}, expected ${runPath}`); + // The nav badge reads the pipeline count; a run deep link must not leave a + // false `Pipelines (0)` beside a populated list. + const runNav = await page.evaluate( + `[...document.querySelectorAll("nav.tabs button.tab")].map((b) => b.textContent.trim())`, + ); + const pipelinesTab = runNav.find((label) => label.startsWith("Pipelines")) ?? ""; + if (pipelinesTab === "Pipelines (0)") { + throw new Error(`L6: the run deep link left a false Pipelines (0) in the nav: ${JSON.stringify(runNav)}`); + } + console.log(` hard navigation ${runPath} opened run ${discovered.preferred}'s detail; nav ${JSON.stringify(runNav)}`); + await shot(`L6-deeplink-run-${discovered.preferred}.png`); + + // The same for a pipeline route: /pipelines/:id means latest. + const pipelinePath = `/pipelines/${pipelineId}`; + await openDeepLink(pipelinePath); + await eventually( + () => page.evaluate(`!!document.querySelector(".detail h2")`), + { timeout: 30000, what: `the deep-linked pipeline ${pipelineId}` }, + ); + const deepPipeline = await page.evaluate(`(() => ({ + path: location.pathname + location.search, + name: document.querySelector(".detail h2")?.textContent ?? "", + }))()`); + if (deepPipeline.path !== pipelinePath) { + throw new Error(`L6: pipeline URL is ${deepPipeline.path}, expected ${pipelinePath}`); + } + if (pipelineSelection.name && deepPipeline.name !== pipelineSelection.name) { + throw new Error( + `L6: deep-linked pipeline rendered ${JSON.stringify(deepPipeline.name)}, expected ${JSON.stringify(pipelineSelection.name)}`, + ); + } + console.log(` hard navigation ${pipelinePath} opened ${JSON.stringify(deepPipeline.name)}`); + await shot(`L6-deeplink-pipeline-${pipelineId}.png`); + + // A pipeline-stage route opens the Graph tab and the named definition pane, + // and brings that pane into view (the graph above it is taller than a viewport). + const stagePath = `/pipelines/${pipelineId}/stage/planner`; + await openDeepLink(stagePath); + await eventually( + () => + page.evaluate( + `document.querySelector(".detail-tab.active")?.textContent === "Graph" && + !!document.querySelector(".graph-pane") && !document.querySelector(".graph-pane").hidden`, + ), + { timeout: 30000, what: "the deep-linked pipeline stage pane" }, + ); + const stageState = await page.evaluate(`(() => { + const pane = document.querySelector(".graph-pane"); + const rect = pane.getBoundingClientRect(); + const head = document.querySelector(".graph-pane-head")?.getBoundingClientRect() ?? null; + const close = document.querySelector(".graph-pane-close")?.getBoundingClientRect() ?? null; + const topbar = document.querySelector(".topbar")?.getBoundingClientRect() ?? null; + return { + path: location.pathname + location.search, + tab: document.querySelector(".detail-tab.active")?.textContent ?? "", + title: document.querySelector(".graph-pane-title")?.textContent ?? "", + top: Math.round(rect.top), + viewport: window.innerHeight, + topbarBottom: topbar ? Math.round(topbar.bottom) : 0, + headTop: head ? Math.round(head.top) : null, + headBottom: head ? Math.round(head.bottom) : null, + closeTop: close ? Math.round(close.top) : null, + }; + })()`); + if (stageState.path !== stagePath) throw new Error(`L6: pipeline stage URL is ${stageState.path}`); + if (stageState.tab !== "Graph") throw new Error(`L6: pipeline stage opened tab ${stageState.tab}`); + if (!stageState.title) throw new Error("L6: the pipeline stage pane has no title"); + if (stageState.headTop == null || stageState.headTop < stageState.topbarBottom) { + throw new Error( + `L6: the opened stage pane head (top ${stageState.headTop}) is hidden under the sticky top bar (bottom ${stageState.topbarBottom})`, + ); + } + if (stageState.headBottom > stageState.viewport) { + throw new Error(`L6: the opened stage pane head is below the viewport (bottom ${stageState.headBottom})`); + } + if (stageState.closeTop == null || stageState.closeTop < stageState.topbarBottom) { + throw new Error( + `L6: the stage pane Close control (top ${stageState.closeTop}) is hidden under the top bar (bottom ${stageState.topbarBottom})`, + ); + } + console.log( + ` hard navigation ${stagePath} opened the Graph tab and the ${JSON.stringify(stageState.title)} pane (head ${stageState.headTop}px, top bar ${stageState.topbarBottom}px)`, + ); + await shot(`L6-deeplink-pipeline-${pipelineId}-stage.png`); + + // The graph also selects its terminals, and the URL it pushes for one must + // re-open the same pane (a terminal is not a named stage, but it is a node the + // page itself writes a /stage/ URL for). Find a terminal in the live graph. + const terminalKey = await page.evaluate(`(() => { + const node = [...document.querySelectorAll(".graph-node[data-key]")] + .find((n) => (n.dataset.key ?? "").startsWith("#")); + return node?.dataset.key ?? ""; + })()`); + if (terminalKey) { + const terminalPath = `/pipelines/${pipelineId}/stage/${encodeURIComponent(terminalKey)}`; + await openDeepLink(terminalPath); + await eventually( + () => + page.evaluate( + `!!document.querySelector(".graph-pane") && !document.querySelector(".graph-pane").hidden`, + ), + { timeout: 30000, what: `the deep-linked terminal pane ${terminalKey}` }, + ); + const terminalState = await page.evaluate(`(() => ({ + path: location.pathname + location.search, + title: document.querySelector(".graph-pane-title")?.textContent ?? "", + headTop: Math.round(document.querySelector(".graph-pane-head")?.getBoundingClientRect().top ?? -1), + topbarBottom: Math.round(document.querySelector(".topbar")?.getBoundingClientRect().bottom ?? 0), + }))()`); + if (terminalState.path !== terminalPath) { + throw new Error( + `L6: the terminal stage URL was rewritten to ${terminalState.path}, expected ${terminalPath}`, + ); + } + if (!terminalState.title) throw new Error("L6: the terminal stage pane has no title"); + if (terminalState.headTop < terminalState.topbarBottom) { + throw new Error("L6: the terminal stage pane head is hidden under the top bar"); + } + console.log( + ` hard navigation ${terminalPath} re-opened the ${JSON.stringify(terminalState.title)} terminal pane (URL unchanged)`, + ); + await shot(`L6-deeplink-pipeline-${pipelineId}-terminal.png`); + } else { + console.log(" -- the live graph has no terminal node; skipped the terminal stage deep link"); + } + + // In-page moves: Pipelines -> Runs -> a run detail, then Back/Forward. A window + // marker proves the document was never reloaded. + const marker = `L6-no-reload-${Date.now()}`; + await page.evaluate(`window.__pipelinesNoReload = ${JSON.stringify(marker)}`); + await page.clickText("nav.tabs button.tab", "Runs"); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs" && !!document.querySelector(".list.runs .run-row")`, + ), + { timeout: 25000, what: "the Runs list after a pushState move" }, + ); + console.log(` pushState Pipelines -> Runs: ${await currentLocation()}`); + + const runRowSelector = `.list.runs .run-row-meta[data-run-id="${discovered.preferred}"]`; + const clickedRun = await page.evaluate(`(() => { + const node = document.querySelector(${JSON.stringify(runRowSelector)}); + if (!node) return false; + node.click(); + return true; + })()`); + if (!clickedRun) throw new Error(`L6: run ${discovered.preferred} was not on the Runs list`); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs/${discovered.preferred}" && + (document.querySelector(".run-detail .run-identity")?.textContent?.startsWith("run ${discovered.preferred} ") ?? false)`, + ), + { timeout: 30000, what: `run ${discovered.preferred} after a pushState selection` }, + ); + console.log(` pushState Runs -> run detail: ${await currentLocation()}`); + + await page.evaluate(`history.back()`); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs" && !!document.querySelector(".list.runs .run-row")`, + ), + { timeout: 25000, what: "Back to the Runs list" }, + ); + const backState = await page.evaluate(`(() => ({ + path: location.pathname, + marker: window.__pipelinesNoReload ?? null, + staleDetail: !!document.querySelector(".run-detail .run-identity"), + }))()`); + if (backState.path !== "/runs") throw new Error(`L6: Back landed on ${backState.path}`); + if (backState.staleDetail) throw new Error("L6: Back left a stale run detail rendered"); + if (backState.marker !== marker) throw new Error("L6: Back reloaded the document"); + console.log(` history.back() -> /runs, marker survived (${backState.marker})`); + await shot("L6-history-back.png"); + + await page.evaluate(`history.forward()`); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs/${discovered.preferred}" && + (document.querySelector(".run-detail .run-identity")?.textContent?.startsWith("run ${discovered.preferred} ") ?? false)`, + ), + { timeout: 30000, what: "Forward back to the run detail" }, + ); + const forwardState = await page.evaluate(`(() => ({ + path: location.pathname, + marker: window.__pipelinesNoReload ?? null, + }))()`); + if (forwardState.marker !== marker) throw new Error("L6: Forward reloaded the document"); + console.log(` history.forward() -> ${forwardState.path}, marker survived`); + + // Leaving Runs while an executing run's poll is active must stop that poll: a + // silent get_run loop for a detail the view no longer shows would otherwise run + // forever. Conditional because the live server may have no executing run. + const executingId = await page.evaluate(`(() => { + const row = [...document.querySelectorAll(".list.runs .run-row")].find((n) => n.querySelector(".chip-running")); + const meta = row?.querySelector(".run-row-meta[data-run-id]"); + return meta ? Number(meta.getAttribute("data-run-id")) : null; + })()`); + if (executingId != null) { + await page.click(`.list.runs .run-row-meta[data-run-id="${executingId}"]`); + await eventually( + () => + page.evaluate( + `(document.querySelector(".run-detail .run-identity")?.textContent?.startsWith("run ${executingId} ") ?? false)`, + ), + { timeout: 30000, what: `the executing run ${executingId}` }, + ); + await page.evaluate(`window.__pipelinesSentTypes = []`); + await page.clickText("nav.tabs button.tab", "Pipelines"); + await eventually(() => page.evaluate(`location.pathname === "/pipelines"`), { + timeout: 15000, + what: "Pipelines after leaving the executing run", + }); + await new Promise((resolve) => setTimeout(resolve, 2600)); + const leftoverPolls = await page.evaluate( + `(window.__pipelinesSentTypes || []).filter((type) => type === "get_run").length`, + ); + if (leftoverPolls > 0) { + throw new Error( + `L6: leaving Runs left the executing run's poll active (${leftoverPolls} get_run frame(s) after 2.6s)`, + ); + } + console.log( + ` left executing run ${executingId} for /pipelines; no get_run poll fired in the next 2.6s`, + ); + } else { + console.log(" -- no executing run available; skipped the leave-Runs poll check"); + } + + // The decide deep link is exercised only against a genuinely waiting run; with + // none, say so rather than claiming a capture of a state that never rendered. + if (discovered.waiting) { + await openDeepLink(`/runs/${discovered.waiting}?action=decide`); + await eventually(() => page.evaluate(`!!document.querySelector(".decision-sheet")`), { + timeout: 30000, + what: `the decision sheet for waiting run ${discovered.waiting}`, + }); + const decideUrl = await currentLocation(); + if (decideUrl !== `/runs/${discovered.waiting}`) { + throw new Error(`L6: the decide action was not consumed to /runs/${discovered.waiting}: ${decideUrl}`); + } + console.log( + ` hard navigation /runs/${discovered.waiting}?action=decide opened the decision sheet, action consumed`, + ); + await shot(`L6-deeplink-decide-${discovered.waiting}.png`); + await page.evaluate(`document.querySelector(".decision-sheet .decision-cancel")?.click()`); + await eventually(() => page.evaluate(`!document.querySelector(".decision-sheet")`), { + timeout: 5000, + what: "the decision sheet to close without sending", + }); + } else { + console.log( + " NOTE: the ?action=decide path was not exercised live (no waiting run on the server); test/routes.test.mjs covers its parsing", + ); + } + + // A missing run falls back honestly: the list with real rows, /runs in the URL, + // the server's refusal in the banner and no stale run identity. + await openDeepLink("/runs/900000000"); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs" && document.querySelectorAll(".list.runs .run-row").length > 0`, + ), + { timeout: 30000, what: "the missing-run fallback to the Runs list" }, + ); + const missingState = await page.evaluate(`(() => ({ + path: location.pathname + location.search, + rows: document.querySelectorAll(".list.runs .run-row").length, + staleDetail: !!document.querySelector(".run-detail .run-identity"), + error: document.querySelector(".banner.error")?.textContent ?? "", + pageErrors: window.__pipelinesPageErrors ?? [], + }))()`); + if (missingState.path !== "/runs") throw new Error(`L6: missing run fell back to ${missingState.path}`); + if (!missingState.rows) throw new Error("L6: missing run rendered no run rows"); + if (missingState.staleDetail) throw new Error("L6: missing run left a stale run detail"); + if (!missingState.error) throw new Error("L6: missing run showed no server refusal"); + if (missingState.pageErrors.length) { + throw new Error(`L6: page errors: ${missingState.pageErrors.join(" | ")}`); + } + console.log( + ` missing run -> /runs with ${missingState.rows} real rows, banner ${JSON.stringify(missingState.error.replace(/^Error:\\s*/, ""))}`, + ); + await shot("L6-missing-run.png"); + + // The same honest fallback for a pipeline the server does not have. + await openDeepLink("/pipelines/900000000"); + await eventually( + () => + page.evaluate( + `location.pathname === "/pipelines" && document.querySelectorAll("#pipelineRows button.row").length > 0`, + ), + { timeout: 30000, what: "the missing-pipeline fallback to the Pipelines list" }, + ); + const missingPipeline = await page.evaluate(`(() => ({ + path: location.pathname + location.search, + rows: document.querySelectorAll("#pipelineRows button.row").length, + staleDetail: !!document.querySelector(".detail h2"), + error: document.querySelector(".banner.error")?.textContent ?? "", + pageErrors: window.__pipelinesPageErrors ?? [], + }))()`); + if (missingPipeline.path !== "/pipelines") { + throw new Error(`L6: missing pipeline fell back to ${missingPipeline.path}`); + } + if (!missingPipeline.rows) throw new Error("L6: missing pipeline rendered no pipeline rows"); + if (missingPipeline.staleDetail) throw new Error("L6: missing pipeline left a stale pipeline detail"); + if (!missingPipeline.error) throw new Error("L6: missing pipeline showed no server refusal"); + if (missingPipeline.pageErrors.length) { + throw new Error(`L6: page errors: ${missingPipeline.pageErrors.join(" | ")}`); + } + console.log( + ` missing pipeline -> /pipelines with ${missingPipeline.rows} real rows, banner ${JSON.stringify(missingPipeline.error.replace(/^Error:\\s*/, ""))}`, + ); + await shot("L6-missing-pipeline.png"); + + // A move made before the socket is up must become the destination the first + // connection opens; only an untouched boot deep link is replayed. Load `/`, + // choose Runs while disconnected, then connect and require URL and view to + // agree (regression: the stale boot route used to win at connect time). + await page.goto(`http://127.0.0.1:${port}/`); + await page.waitForSelector("#connectBtn", { timeout: 15000 }); + await page.clickText("nav.tabs button.tab", "Runs"); + const preConnect = await currentLocation(); + if (preConnect !== "/runs") { + throw new Error(`L6: a Runs choice before connecting left ${preConnect}, expected /runs`); + } + await page.click("#connectBtn"); + await ensureConnected(30000); + await eventually( + () => + page.evaluate( + `location.pathname === "/runs" && !!document.querySelector(".list.runs .run-row")`, + ), + { timeout: 30000, what: "the pre-connect Runs choice after connecting" }, + ); + console.log(" a Runs choice made before connecting survived the first connection (/runs, list rendered)"); + console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`); }