Files
pipelines/web/src/app.js
T
alan 72f00cd871 web: restore focus to a row's real control
The a11y work made the chat row a container with its control inside, so Back
focused a non-focusable div and keyboard focus fell to the body. Focus the first
focusable descendant instead (generic for chat, runs, pipelines and templates).
2026-10-19 20:10:28 +01:00

2338 lines
84 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Spike web UI: the page shell. Boot, shared state, the one reused client and
// repository, connection wiring, navigation + URL routes, render dispatch and the
// persistent rail/dock/workspace shell. Feature views live under ./views/ and
// shared DOM/format helpers in ./dom.js and ./format.js. Every server value is set
// with textContent, never innerHTML.
import { PipelinesClient, ProtocolError } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl } from "./serverUrl.js";
import { ForegroundAction, RunStream, foregroundAction } from "./connection.js";
import {
DESTINATIONS,
destinationForView,
destinationIndex,
rovingTabindex,
sectionModel,
shellStatus,
tabIndexForKey,
} from "./shell.js";
import {
foldRunEvent,
foldRunEventDetail,
isTerminalRunStatus,
runDetailNeedsFullSync,
} from "./runEvents.js";
import { SERVER_URL_STORAGE_KEY, readServerUrl, readWorkspace, writeServerUrl } from "./settings.js";
import { layoutGraph } from "./graph.js";
import { DEFAULT_ROUTE, parseRoute, serializeRoute } from "./routes.js";
import { EMPTY_PIPELINE_FILTERS, PIPELINE_DETAIL_TABS } from "./pipelines.js";
import {
DEFAULT_RUN_SORT,
metaText,
formatDuration,
defaultRunFilters,
} from "./runs.js";
import { runDurationText, runTimeline, clampVisitIndex, RENDERED_RUN_TABS } from "./runDetail.js";
import { createAlertLedger } from "./notify.js";
import {
DEFAULT_SEARCH_KIND,
DEFAULT_SEARCH_SORT,
SearchSequencer,
} from "./search.js";
import { DecisionDraft, pendingDecision } from "./actions.js";
import { h } from "./dom.js";
import { describeError, isExecuting } from "./format.js";
import {
createAttentionView,
loadAttentionDismissed,
loadNotifyAsked,
} from "./views/attention.js";
import { createSettingsView } from "./views/settings.js";
import { createPipelinesView } from "./views/pipelines.js";
import { createTemplatesView } from "./views/templates.js";
import { createRunsView } from "./views/runs.js";
import { createDialogsView } from "./views/dialogs.js";
import { createRunDetailView } from "./views/runDetail.js";
import {
createChatView,
readChatScrollStore,
readChatDraftStore,
readChatOverridesStore,
readChatSeenStore,
readEphemeralChatIds,
} from "./views/chat.js";
import { createSearchView } from "./views/search.js";
function defaultServerUrl() {
if (typeof location === "undefined" || !location.host) return "";
const scheme = location.protocol === "https:" ? "wss" : "ws";
return `${scheme}://${location.host}/connect`;
}
const client = new PipelinesClient();
const repo = new PipelinesRepository(client);
// Read the persisted settings once: the server URL falls back to the page's own
// proxy endpoint when unset, and the workspace starts blank when unset. Both the
// configured value and the draft start from storage.
const initialWorkspace = readWorkspace(localStorage);
const state = {
view: "pipelines",
url: readServerUrl(localStorage) || defaultServerUrl(),
// The server URL's own validation message (Android's `urlError`), shown as the
// Settings field's supporting text and cleared as soon as the field is edited.
urlError: "",
// The workspace the operator configured (L1), the analogue of SettingsRepository's
// `workspace` preference. `workspaceDraft` is the field's live value; Save copies
// it into `workspace` and localStorage. Both start from the persisted value.
workspace: initialWorkspace,
workspaceDraft: initialWorkspace,
connection: client.state,
// The live run-stream state (R10), independent of any screen: Offline until a
// watch is established, Connecting while subscribing/re-subscribing after a
// drop, Live once an ack, the first pushed frame or a successful watch read
// proves pushes are arriving. The runs list and the run detail render it as the
// LiveBadge.kt words.
runStream: RunStream.Offline,
// The last `pong` reply is remembered so the banner can name a stale server
// build and warn about a protocol mismatch (T5) without re-pinging.
serverBuild: null,
serverProtocol: null,
// The `pong` reply's server time (L1), shown in the Settings connection card.
serverTime: null,
pipelines: [],
runs: [],
usage: null,
pipelineDetail: null,
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.
pipelineFilters: { ...EMPTY_PIPELINE_FILTERS },
pipelineSort: "server_order",
pipelineMenu: null,
pipelineTab: "summary",
// The mounted workflow graph (P6) and whether its panel is expanded. The
// handle is dropped on every re-render so its listeners can never leak.
pipelineGraph: null,
pipelineGraphExpanded: false,
// The mounted run-mode graph (R5) on the run detail's Graph tab. Dropped on
// every re-render and on a run change, so its wheel/pointer/resize listeners
// and its elapsed timer can never leak.
runGraph: null,
versionsExpanded: false,
pipelinesLoaded: false,
runsLoaded: false,
templates: [],
templateLoading: false,
// key -> graph|null: the parsed definition, cached once per template key. A
// failed/absent validate stores null so the card/detail say "unavailable".
templateGraphs: new Map(),
selectedTemplateKey: null,
templateTab: "summary",
// The create-from-template dialog (P5): whether it is open, the name being
// typed, whether a validate+submit is in flight, the server's refusal text and
// the created pipeline's name (null until a success, which is also what makes
// Cancel read Close and the field lock). The dialog validates the template's
// source first, then submits it create-only; nothing runs.
templateCreateOpen: false,
templateCreateName: "",
templateCreateSending: false,
templateCreateError: "",
templateCreateCreated: null,
loading: false,
error: "",
runFilters: defaultRunFilters(),
runSort: DEFAULT_RUN_SORT,
openMenu: null,
// Run detail: the selected tab (Summary by default) and the per-run
// expand/collapse choices for the input/output field sections and the summary
// artifacts section. The stage pane is the timeline's per-visit panel; its
// section expansion is reseeded each time a pane is opened.
runTab: "summary",
runSections: new Set(),
runStagePane: null,
runStageSections: new Set(),
// The attention / "Needs you" surface (R15). `attentionDismissed` is the set
// of `{runId}:{kind}` identities the operator has explicitly dealt with, loaded
// once at boot from localStorage. `attentionSheetOpen` drives the sheet and
// `attentionSnapshot` holds the entries captured when it opened, so Clear all
// only ever removes identities the operator actually saw.
attentionDismissed: new Set(),
attentionSheetOpen: false,
attentionSnapshot: null,
// Notifications (L5): whether the operator has already been asked, loaded once
// at boot from localStorage. The browser owns the permission itself; this flag
// only changes the honest wording in Settings and is never a claim of consent.
notifyAsked: false,
// Omni-search (S1/S2): the field/panel state, kept beside the view it never
// changes, plus the pure debounce/stale-token sequencer. Opening or closing the
// search leaves state.view, the selection and the loaded data untouched.
searchOpen: false,
searchQuery: "",
searchKind: DEFAULT_SEARCH_KIND,
searchSort: DEFAULT_SEARCH_SORT,
searchResults: [],
searchLoading: false,
searchError: "",
searchLoaded: false,
searchFocusPending: false,
searchSequencer: new SearchSequencer(),
// Run-level operator actions (R11–R14): the decision the open sheet renders
// (retained across a refused send so the server's own reason can be shown even
// after a refresh), the sheet's draft/sending/error, the action awaiting a
// confirm dialog, the in-progress rename title (null when not editing) and the
// one shared Action-failed dialog.
runDecision: null,
decisionOpen: false,
decisionDraft: new DecisionDraft(),
decisionSending: false,
decisionError: "",
confirmKind: null,
renameValue: null,
renameBusy: false,
actionError: "",
// Chat (C1/C3/C4/C7/C14): the server's operator-session list and its load
// state, the operator's narrowing, one open thread per session id and the
// active one. The transcript is untrusted model output, so every server string
// is set with textContent and the markdown renderer builds DOM nodes, never
// innerHTML.
chatSessions: [],
// The verification chats this page itself created (C2's automation flag). The
// server deliberately never lists them; the page keeps its own in-memory row so
// the creator can keep working with the chat it just opened. The set is
// memory-only, so a reload cannot turn one into a permanent list entry.
// Verification chats this tab created (never listed by the server). Kept in
// sessionStorage so a reload of this tab still shows the chat it made, while a
// different tab or a later visit never sees it.
chatEphemeralIds: new Set(readEphemeralChatIds()),
chatLoading: false,
chatLoaded: false,
chatError: "",
chatQuery: "",
chatThreads: new Map(),
chatActiveId: null,
chatPlaced: null,
chatFollowing: true,
chatReasoning: new Set(),
// The tool-call panel (C6): the turns whose panel is open and the individual
// rows the operator has expanded, both keyed the same way as chatReasoning so
// a re-render keeps them.
chatToolPanels: new Set(),
chatToolRows: new Set(),
chatScroll: readChatScrollStore(),
// The scroll restore across a prepended older page, the position captured
// from the live transcript just before a re-render (so a dialog, a refresh or
// the loading frame of a paging fetch never loses the operator's place), and
// the debounced save.
chatAnchor: null,
chatPending: null,
chatScrollTimer: null,
// True only while the operator's own gesture (wheel/pointer/touch) is the
// reason the transcript moved, so a programmatic placement or follow can never
// be mistaken for the operator leaving the bottom.
chatUserIntent: false,
// The session awaiting the Close chat? confirm, and the shared Action-failed
// report for a refused close/reopen.
chatClose: null,
chatBusy: false,
// C13: this device's local titles/hidden ids and the seen watermarks, both
// persisted as one JSON value each. `chatMenu` is the row whose Chat actions
// menu is open, `chatRename` the session whose Rename chat dialog is open, and
// `chatSnackbar` the one in-flight hide report (`{id, sessionId}`) with the
// timer that auto-dismisses it. A new hide replaces the previous report.
chatOverrides: readChatOverridesStore(),
chatSeen: readChatSeenStore(),
chatMenu: null,
chatRename: null,
chatSnackbar: null,
chatSnackbarSeq: 0,
chatSnackbarTimer: null,
// C5: the session ids this connection currently has subscribed to their shared
// live stream. The server detaches a subscription when the connection closes
// (there is no chat_unsubscribe), so this is cleared on every socket drop and
// re-established for the open chat on reconnect. A refused subscription simply
// never joins the set, so the badge reads "not live" honestly.
chatSubscriptions: new Set(),
// C2: the create flow. `chatCreate` is the ChatCreateState analogue (null until
// the New chat entry point is used); the directory reply is cached so cancelling
// and reopening does not re-ask, and a failed load keeps its own reason.
chatDirectories: [],
chatDirectoriesLoading: false,
chatDirectoriesLoaded: false,
chatDirectoriesError: "",
chatCreate: null,
};
// The app-wide run-event watch (R10), owned by the connection rather than any
// screen. `workspace` is the blank string while a watch is established (the
// server-wide "any" scope) and null when nothing is watched; `subscriptionId` is
// the send-only subscribe frame's id so an ack or refusal can be attributed.
// `generation` is bumped on every (re)subscribe and every drop, so an in-flight
// read from a superseded watch can neither write its result nor clear the badge.
const runWatch = {
workspace: null,
subscriptionId: null,
generation: 0,
runsResyncJob: null,
runsResyncQueued: false,
detailSyncJob: null,
detailSyncRequestedRunId: null,
detailDeltaCount: 0,
};
// The coalesced resync retry bound, mirroring AppViewModel: at most three
// retries (four attempts) at 500 ms x attempt, then the badge drops to
// "reconnecting" until a later push or read confirms the stream again.
const RUN_SYNC_RETRY_LIMIT = 3;
const RUN_SYNC_RETRY_BASE_MS = 500;
// The run-notification ledger (L5). It is seeded from the authoritative run list
// and from the subscribe snapshot, then observes pushed `run_event` frames; it
// never feeds the runs list (that is R10's fold above).
const runAlerts = createAlertLedger();
// One shared live clock for the runs list: it ticks only while a shown run is
// executing, and each running row reads its elapsed from it rather than starting
// a timer of its own. Elapsed is derived from the server's start timestamp, so
// it stays correct after a reconnect; a finished history never ticks.
let listClock = null;
let listNow = Date.now();
// The run detail's own live clock: it ticks only while the shown run is
// executing, updating just the Duration row in place (never a full re-render, so
// an open stage pane is not torn down), exactly as the runs list does.
let detailClock = null;
let detailNow = Date.now();
/** Await one delay; used only by the bounded resync retry backoff. */
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// The persistent shell (L2/L3/L4)
// ---------------------------------------------------------------------------
/** One 24px sprite glyph; decorative because every control also has a label. */
function icon(name) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "icon");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttribute("href", `#icon-${name}`);
svg.append(use);
return svg;
}
function isWideLayout() {
return typeof window.matchMedia === "function"
? window.matchMedia("(min-width: 600px)").matches
: true;
}
function destinationTab(destination, mount) {
const rail = mount === "rail";
const children = [
icon(destination.icon),
h("span", { class: rail ? "rail-label" : "dock-item-label", text: destination.label }),
];
// The attention count stays visible from every destination: the bell itself
// lives in the Runs heading, so its badge is mirrored on the Runs tab.
if (destination.key === "runs") {
children.push(
h("span", {
class: rail ? "rail-badge" : "dock-badge",
"data-attention-badge": "runs",
"aria-hidden": "true",
hidden: true,
}),
);
}
const tab = h(
"a",
{
id: `${mount}-dest-${destination.key}`,
class: rail ? "rail-item" : "dock-item",
href: destination.path,
role: "tab",
"aria-controls": "pane-main",
"aria-selected": "false",
tabindex: "-1",
"data-destination": destination.key,
onclick: (event) => {
// A real href keeps middle-click/copy-link honest; a plain click is one
// route application, so Back/Forward behave exactly as before.
event.preventDefault();
goToDestination(destination.key);
},
onkeydown: (event) => onDestinationKeydown(event, mount),
},
...children,
);
return tab;
}
const railDestinations = h(
"nav",
{
id: "railDestinations",
class: "rail-destinations",
role: "tablist",
"aria-label": "Destinations",
"aria-orientation": "vertical",
},
...DESTINATIONS.map((destination) => destinationTab(destination, "rail")),
);
const dockDestinations = h(
"div",
{
id: "dockDestinations",
class: "dock-tabs",
role: "tablist",
"aria-label": "Destinations",
},
...DESTINATIONS.map((destination) => destinationTab(destination, "dock")),
);
const railSearch = h(
"button",
{
id: "searchToggle",
class: "rail-search",
type: "button",
"aria-expanded": "false",
onclick: () => openSearch(),
},
icon("search"),
h("span", { text: "Search" }),
);
const dockSearch = h(
"button",
{
id: "dockSearch",
class: "dock-search",
type: "button",
"aria-expanded": "false",
onclick: () => openSearch(),
},
icon("search"),
h("span", { text: "Search" }),
);
function statusControl(id, mount) {
return h(
"button",
{
id,
class: `shell-status${mount === "dock" ? " dock-status" : ""}`,
type: "button",
"data-state": "idle",
title: "Connection status — open Settings",
onclick: openSettingsFromStatus,
},
h("span", { class: "shell-status-dot", "aria-hidden": "true" }),
h("span", { class: "shell-status-label", text: "Not connected" }),
);
}
const railStatus = statusControl("shellStatus", "rail");
const dockStatus = statusControl("shellStatusNarrow", "dock");
const railSections = h("div", { id: "railSections", class: "rail-sections" });
const sectionStrip = h("nav", {
id: "sectionStrip",
class: "section-strip",
"aria-label": "Detail sections",
});
const appRail = h(
"aside",
{ id: "appRail", class: "app-rail", "aria-label": "Pipelines navigation" },
h(
"div",
{ class: "rail-brand" },
h("span", { class: "rail-brand-mark", "aria-hidden": "true", text: "P" }),
h("span", { text: "Pipelines" }),
),
railDestinations,
railSearch,
h("div", { class: "rail-divider", role: "presentation" }),
railSections,
h("div", { class: "rail-footer" }, railStatus),
);
// The omni-search panel is part of the workspace flow: it takes height from the
// panes and scrolls its own result list, never the document.
const searchHost = h("div", { id: "searchHost", class: "search-host" });
const content = h("div", { id: "content", class: "content" });
// The destination tabs control this panel. It is a nested tabpanel rather than
// the <main> itself, so the page keeps its main landmark as well as complete
// tab semantics; renderHeader points aria-labelledby at the visible mount's tab.
const workspace = h(
"main",
{ class: "workspace", "aria-label": "Workspace" },
h(
"div",
{ id: "pane-main", class: "pane-main", role: "tabpanel", tabindex: "-1" },
searchHost,
content,
),
);
const dock = h(
"nav",
{ id: "destinationDock", class: "destination-dock", "aria-label": "Destinations" },
dockStatus,
h("div", { class: "dock-row" }, dockDestinations, dockSearch),
);
// The attention sheet lives in its own layer so it can overlay any view without
// being torn down by a content re-render; renderAttentionSheet rebuilds it.
const attentionLayer = h("div", { id: "attentionLayer" });
const skipLink = h("a", { class: "skip-link", href: "#pane-main", text: "Skip to detail" });
document.body.append(skipLink);
document.body.append(h("div", { class: "app-root" }, appRail, workspace, dock, attentionLayer));
/** Whether the URL field currently holds a usable endpoint for Reconnect. */
function endpointConfigured() {
return validateServerUrl(state.url).valid;
}
/**
* Whether this browser has an endpoint the operator actually saved. The URL field
* is prefilled with the page's proxy, so "the draft validates" is true on a fresh
* page too; only a saved value (or a connection this session) means configured.
*/
function endpointSaved() {
if (state.connection.kind === "connected") return true;
try {
return localStorage.getItem(SERVER_URL_STORAGE_KEY) !== null;
} catch {
return false;
}
}
/**
* The one server-URL draft (Android's `serverUrlDraft`). Settings is now the
* only place that edits it, so there is no second field to mirror.
*/
function setServerUrlDraft(value, sourceId) {
state.url = value;
clearServerUrlError();
// The shell's status word depends on whether an endpoint is configured: keep it
// in step with the draft instead of leaving the previous word on screen.
renderHeader();
const field = document.getElementById("settingsServerUrl");
if (field && sourceId !== "settingsServerUrl" && field.value !== value) field.value = value;
if (field) views.settings.refreshServerUrlError();
}
/**
* Clear the server-URL validation error, wherever it was surfaced: the Settings
* field's own error always, and the matching page-level banner too, so an edit
* never leaves a stale message claiming the URL is still bad.
*/
function clearServerUrlError() {
if (!state.urlError) return;
const message = state.urlError;
state.urlError = "";
if (state.error === message) {
state.error = "";
for (const banner of document.querySelectorAll("#content .banner.error")) {
if ((banner.textContent ?? "").includes(message)) banner.remove();
}
}
}
/** Repaint the shell chrome in place; the rail itself is never rebuilt. */
function renderHeader() {
const activeKey = destinationForView(state.view);
const activeIndex = destinationIndex(activeKey);
for (const tab of document.querySelectorAll("[data-destination]")) {
const isActive = tab.getAttribute("data-destination") === activeKey;
tab.setAttribute("aria-selected", isActive ? "true" : "false");
tab.setAttribute("tabindex", rovingTabindex(activeIndex, DESTINATIONS.findIndex((d) => d.key === tab.getAttribute("data-destination"))));
if (isActive) tab.setAttribute("aria-current", "page");
else tab.removeAttribute("aria-current");
}
const status = shellStatus(state.connection, { hasEndpoint: endpointSaved() });
for (const control of [railStatus, dockStatus]) {
control.setAttribute("data-state", status.state);
const label = control.querySelector(".shell-status-label");
if (label) label.textContent = status.text;
control.setAttribute("aria-label", `Connection status: ${status.text}. Open Settings`);
}
railSearch.setAttribute("aria-expanded", state.searchOpen ? "true" : "false");
dockSearch.setAttribute("aria-expanded", state.searchOpen ? "true" : "false");
// aria-controls points at #searchPanel only while that panel exists.
for (const control of [railSearch, dockSearch]) {
if (state.searchOpen) control.setAttribute("aria-controls", "searchPanel");
else control.removeAttribute("aria-controls");
}
// The destination tablist controls #pane-main; name the panel from whichever
// mount is visible at this breakpoint.
const panel = document.getElementById("pane-main");
if (panel) panel.setAttribute("aria-labelledby", `${isWideLayout() ? "rail" : "dock"}-dest-${activeKey}`);
// The attention badge on Runs is derived from the same ledger as the bell.
renderDestinationBadges();
// The search panel owns its field's one-shot autofocus (see renderSearch).
renderSectionMounts();
}
/** Mirror the attention count onto the Runs destination in both mounts. */
function renderDestinationBadges(count = views.attention.attentionCount()) {
for (const badge of document.querySelectorAll("[data-attention-badge]")) {
if (count > 0) {
badge.hidden = false;
badge.textContent = String(count);
} else {
badge.hidden = true;
badge.textContent = "";
}
}
}
function goToDestination(key) {
const route = { kind: key };
pushRoute(route);
applyRoute(route);
}
/** One shared roving-tabindex handler for both destination mounts. */
function onDestinationKeydown(event, mount) {
const current = DESTINATIONS.findIndex(
(destination) => destination.key === event.currentTarget.getAttribute("data-destination"),
);
const next = tabIndexForKey(event.key, current, DESTINATIONS.length, {
vertical: mount === "rail",
});
if (next < 0) return;
event.preventDefault();
const destination = DESTINATIONS[next];
// Selection follows focus: activate the destination and then move focus to the
// newly selected tab in the mount the operator is using.
const targetId = `${mount}-dest-${destination.key}`;
goToDestination(destination.key);
document.getElementById(targetId)?.focus();
}
/** The status control is a Settings shortcut, from either mount. */
function openSettingsFromStatus() {
const route = { kind: "settings" };
pushRoute(route);
applyRoute(route);
// The Settings h1 is the route's focus anchor when the load completes; do the
// in-place render's heading now so the click always lands somewhere meaningful.
requestAnimationFrame(() => {
const heading = document.querySelector("#detail-panel h1, #content h1");
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus();
}
});
}
/**
* The detail section model for the open detail: the rail's vertical group on
* wide and the strip above the dock on narrow render the same tabs. A detail
* with one section, or no open detail, gets no tablist at all.
*/
function detailSections() {
if (state.view === "pipelines" && state.selectedPipelineId != null) {
return { label: "Pipeline sections", tabs: PIPELINE_DETAIL_TABS, active: state.pipelineTab };
}
if (state.view === "runs" && state.selectedRunId != null) {
return { label: "Run sections", tabs: RENDERED_RUN_TABS, active: state.runTab };
}
if (state.view === "templates" && state.selectedTemplateKey != null) {
return {
label: "Template sections",
tabs: [
{ key: "summary", label: "Summary" },
{ key: "graph", label: "Graph" },
{ key: "source", label: "Source" },
],
active: state.templateTab,
};
}
return { label: "Detail sections", tabs: [], active: "summary" };
}
function selectSection(key) {
if (state.view === "pipelines") state.pipelineTab = key;
else if (state.view === "runs") state.runTab = key;
else if (state.view === "templates") state.templateTab = key;
renderContent();
focusSectionTab(key);
}
function focusSectionTab(key) {
const railTab = document.getElementById(`rail-tab-${key}`);
const stripTab = document.getElementById(`strip-tab-${key}`);
const visible = isWideLayout() ? railTab : stripTab;
visible?.focus();
}
function onSectionKeydown(event, model) {
const current = model.tabs.findIndex((tab) => tab.key === event.currentTarget.dataset.sectionKey);
const next = tabIndexForKey(event.key, current, model.tabs.length, {
vertical: event.currentTarget.closest(".rail-sections") != null,
});
if (next < 0) return;
event.preventDefault();
selectSection(model.tabs[next].key);
}
function sectionTablist(model, mount) {
const rail = mount === "rail";
const list = h("div", {
id: rail ? "railTablist" : "stripTablist",
class: rail ? "rail-tablist" : "strip-tablist",
role: "tablist",
"aria-label": model.label,
"aria-orientation": rail ? "vertical" : "horizontal",
});
const { tabs, active } = sectionModel(model);
tabs.forEach((tab, index) => {
list.append(
h(
"button",
{
id: `${rail ? "rail" : "strip"}-tab-${tab.key}`,
class: rail ? "rail-tab" : "strip-tab",
type: "button",
role: "tab",
text: tab.label,
"aria-selected": index === active ? "true" : "false",
"aria-controls": "detail-panel",
tabindex: rovingTabindex(active, index),
"data-section-key": tab.key,
onclick: () => selectSection(tab.key),
onkeydown: (event) => onSectionKeydown(event, model),
},
),
);
});
return list;
}
/** Rebuild both section mounts; hidden one is display:none via CSS. */
function renderSectionMounts() {
const model = detailSections();
const has = model.tabs.length > 1;
railSections.classList.toggle("has-sections", has);
if (!has) {
railSections.replaceChildren();
sectionStrip.replaceChildren();
sectionStrip.hidden = true;
return;
}
sectionStrip.hidden = false;
railSections.replaceChildren(
h("p", { class: "rail-heading", text: model.label.replace(/\s+sections$/i, "") }),
sectionTablist(model, "rail"),
);
sectionStrip.replaceChildren(sectionTablist(model, "strip"));
}
/**
* The list pane's heading. On the list-only route the destination is the h1; on
* a detail route the detail title is the route h1 and this becomes the list's h2.
*/
function paneHeading(title, { detailOpen, subtitle = "", actions = [] } = {}) {
const tag = detailOpen ? "h2" : "h1";
const head = h(
"div",
{ class: "pane-head" },
h("div", { class: "pane-head-text" }, h(tag, { class: "pane-title", id: "listTitle", text: title }), subtitle ? h("h2", { class: "pane-subtitle", text: subtitle }) : null),
);
if (actions.length) head.append(h("div", { class: "pane-head-actions" }, ...actions));
return head;
}
function listSubtitle(view) {
switch (view) {
case "runs":
return "Run history";
case "chat":
return "Chat sessions";
case "templates":
return "Available templates";
default:
return "All pipelines";
}
}
function backControl(view) {
return h(
"div",
{ class: "pane-back" },
h(
"button",
{
type: "button",
onclick: () => closeDetail(view),
},
h("span", { "aria-hidden": "true", text: "\u2190" }),
h("span", { text: "Back to list" }),
),
);
}
function closeDetail(view) {
// Remember the row that opened this detail before its selection is cleared, so
// Back returns focus to it (falling back to the list heading if it is gone).
const restore =
view === "chat" && state.chatActiveId != null
? { root: "#chatRows", attribute: "data-session", value: String(state.chatActiveId) }
: view === "templates" && state.selectedTemplateKey != null
? { root: ".cards", attribute: "data-template-key", value: String(state.selectedTemplateKey) }
: view === "pipelines" && state.selectedPipelineId != null
? { root: "#pipelineRows", attribute: "data-pipeline-id", value: String(state.selectedPipelineId) }
: view === "runs" && state.selectedRunId != null
? { root: ".list.runs", attribute: "data-run-id", value: String(state.selectedRunId) }
: null;
if (view === "chat") {
state.chatActiveId = null;
state.chatCreate = null;
renderContent();
restoreListFocus(restore);
return;
}
if (view === "templates") {
const route = { kind: "templates" };
pushRoute(route);
applyRoute(route);
restoreListFocus(restore);
return;
}
const route = { kind: view };
pushRoute(route);
applyRoute(route);
restoreListFocus(restore);
}
function restoreListFocus(restore) {
if (restore) {
const root = document.querySelector(restore.root);
const row = root
? [...root.querySelectorAll(`[${restore.attribute}]`)].find(
(candidate) => candidate.getAttribute(restore.attribute) === restore.value,
)
: null;
if (row) {
// A row may be a plain container whose real control is a child button (the
// a11y work moved the chat session's control inside the row), so focus the
// first focusable descendant rather than a non-focusable div.
const target =
row.matches("button, a, [tabindex]") ? row : row.querySelector("button, a, [tabindex]") ?? row;
target.focus();
return;
}
}
focusListHeading();
}
function focusListHeading() {
const heading = document.getElementById("listTitle");
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus();
}
}
/** The detail's own heading after a row opens it (instead of leaving focus behind). */
function focusDetailHeading() {
// Pipeline/run/template details live inside #detail-panel; the chat conversation
// (and its create pane) is a section.detail-pane with no inner scroll wrapper.
const heading = document.querySelector(
"#detail-panel #detailTitle, #detail-panel h1, .detail-pane #detailTitle, .detail-pane h1, .detail-pane h2",
);
if (heading) {
heading.setAttribute("tabindex", "-1");
heading.focus({ preventScroll: false });
return;
}
// The reply is still in flight on the narrow layout (the list pane is already
// hidden). Park focus on the detail pane itself rather than leaving it inside a
// display:none row; the final render moves it to the heading.
const pane = document.querySelector(".detail-pane:not([hidden]) #detail-panel, .detail-pane #detail-panel");
if (pane && pane.getClientRects().length > 0) {
pane.setAttribute("tabindex", "-1");
pane.focus({ preventScroll: true });
}
}
function detailPaneFor(view, body, { detailOpen, tabs }) {
const pane = h("section", { class: "detail-pane", "aria-label": `${view} detail` });
if (detailOpen) pane.append(backControl(view));
const scroll = h("div", {
id: "detail-panel",
class: "pane-scroll",
role: tabs.length > 1 ? "tabpanel" : null,
tabindex: tabs.length > 1 ? "0" : null,
"aria-label": tabs.length > 1 ? "Detail" : null,
});
scroll.append(body);
pane.append(scroll);
if (tabs.length > 1) pane.append(sectionStrip);
return pane;
}
function render() {
// renderContent repaints the chrome in place, so boot does not build the rail
// tablists twice.
renderSearch();
renderContent();
renderAttentionSheet();
}
function renderContent() {
// The graph owns wheel/pointer/resize listeners; drop the previous mount
// before rebuilding the DOM so a re-render, tab switch or view switch never
// leaves an observer or listener behind.
if (state.pipelineGraph) {
state.pipelineGraph.unmount();
state.pipelineGraph = null;
}
if (state.runGraph) {
state.runGraph.unmount();
state.runGraph = null;
}
renderHeader();
const nodes = [];
if (state.error) {
nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error));
}
// Settings is a single-pane destination: one scrolled column, no sections.
if (state.view === "settings") {
nodes.push(h("div", { class: "settings-pane", id: "detail-panel" }, renderSettingsView()));
captureChatPosition();
content.replaceChildren(...nodes);
stopChatClock();
stopListClock();
stopDetailClock();
return;
}
const view = state.view;
const detailOpen =
view === "pipelines"
? state.selectedPipelineId != null
: view === "runs"
? state.selectedRunId != null
: view === "chat"
? state.chatActiveId != null || state.chatCreate != null
: state.selectedTemplateKey != null;
const activePane = detailOpen ? "detail" : "list";
const model = detailSections();
const layout = h("div", { class: "pane-layout", "data-active-pane": activePane });
if (view === "pipelines") {
layout.append(
h(
"section",
{ class: "list-pane", "aria-label": "Pipelines list" },
paneHeading("Pipelines", {
detailOpen,
subtitle: listSubtitle(view),
actions: [refreshButton()],
}),
renderPipelineList(),
),
detailPaneFor(view, renderPipelineDetail(), { detailOpen, tabs: model.tabs }),
);
} else if (view === "runs") {
layout.append(
h(
"section",
{ class: "list-pane", "aria-label": "Runs list" },
paneHeading("Runs", {
detailOpen,
subtitle: listSubtitle(view),
actions: [renderAttentionBell(), refreshButton()],
}),
renderRunList(),
),
detailPaneFor(view, renderRunDetail(), { detailOpen, tabs: model.tabs }),
);
} else if (view === "templates") {
layout.append(
h(
"section",
{ class: "list-pane", "aria-label": "Templates list" },
paneHeading("Templates", {
detailOpen,
subtitle: listSubtitle(view),
actions: [h("button", { class: "ghost", type: "button", text: "Refresh templates", onclick: () => loadTemplates(true) })],
}),
renderTemplateGallery(),
),
detailPaneFor(view, renderTemplateDetail(), { detailOpen, tabs: model.tabs }),
);
} else {
layout.append(
h(
"section",
{ class: "list-pane", "aria-label": "Chat list" },
paneHeading("Chat", {
detailOpen,
subtitle: listSubtitle(view),
actions: [refreshButton()],
}),
renderChatList(),
),
);
// The transcript, not the pane, is chat's one scroller, so its detail body
// is not wrapped in a second pane-scroll.
const pane = h("section", { class: "detail-pane", "aria-label": "Chat detail" });
if (detailOpen) pane.append(backControl(view));
pane.append(state.chatCreate ? renderChatCreate() : renderChatConversation());
layout.append(pane);
}
nodes.push(layout);
// Capture the live transcript's position before it is replaced, so the very
// next render can put the operator back exactly where they were (a dialog, a
// refresh or a paging frame must not move them).
captureChatPosition();
content.replaceChildren(...nodes);
if (state.view === "chat") {
afterChatRender();
stopListClock();
stopDetailClock();
refreshChatClock();
return;
}
stopChatClock();
if (state.view === "runs") {
refreshListClock();
refreshDetailClock();
} else {
stopListClock();
stopDetailClock();
}
}
function refreshButton() {
return h("button", {
class: "ghost",
type: "button",
text: "Refresh",
onclick: () => loadCurrentView(true),
});
}
// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------
function setError(err) {
state.error = err instanceof Error ? err.message : String(err);
state.loading = false;
renderContent();
}
/**
* Validate the URL field, remember it and open the socket. Shared by Connect,
* the manual Reconnect control and the foreground recovery so all three take the
* same validate → persist → repo.connect path. `repo.connect` resets the
* attempt/backoff inside client.js, cancelling a pending retry delay.
*
* An invalid draft is reported as the Settings field's own error (Android's
* `urlError`) and cleared on the next edit; it is never left as a page-level
* banner. `surfaceError` is false for the background (foreground-recovery)
* caller so a stale, invalid URL field cannot spray an error into the UI on every
* visibilitychange/online event.
*/
function openConfiguredEndpoint({ surfaceError = true } = {}) {
const validated = validateServerUrl(state.url);
if (!validated.valid) {
if (surfaceError) {
state.urlError = validated.message;
// On another view the field is not rendered, so the page-level error is the
// only way to say why nothing happened; on Settings it belongs under the
// field.
if (state.view === "settings") {
refreshServerUrlError();
} else {
state.error = validated.message;
renderContent();
}
}
return;
}
state.error = "";
state.urlError = "";
writeServerUrl(localStorage, state.url);
repo.connect(validated);
}
/**
* The manual reconnect control (T3): re-open the same validated endpoint now.
* `repo.connect` (client.connect) resets the attempt/backoff, so a pending
* retry delay is cancelled and the socket is reopened immediately.
*/
function onReconnectClicked() {
openConfiguredEndpoint();
}
/**
* Return-to-foreground recovery (T4), the page's counterpart of
* ForegroundReconnector: called when the tab becomes visible again or the
* browser comes back online. Idle is the client's own deliberate-disconnect
* state and is left alone; Connecting and Disconnected are driven back to the
* socket at once, cancelling the pending backoff inside client.connect. A
* Connected socket is trusted because the browser's own online/visibility event
* is the liveness signal available to the page (it has no in-page positive ping
* probe like ForegroundReconnector.confirm()); that deviation is recorded in
* web/PARITY.md. Idempotent: repeated events just re-open the same endpoint.
*/
function onForegroundActive() {
if (foregroundAction(state.connection, true) !== ForegroundAction.Reconnect) return;
openConfiguredEndpoint({ surfaceError: false });
}
async function onConnected() {
// Establish the run-event watch immediately once the socket is up (R10): the
// unsubscribe/subscribe pair is sent before anything else is read, and its
// authoritative `list_runs` resync is the one the view then reuses, so a
// connection never stacks two initial history reads. The watch is
// send-only/best-effort; a failure leaves the badge "reconnecting" and the
// ordinary view load proceeds.
const watched = startRunWatch();
let reply;
try {
reply = await repo.ping();
} catch (err) {
setError(err);
return;
}
// Remember the server's build/protocol so the banner can name a stale server
// and warn about a protocol mismatch (T5); the ping is the only source.
state.serverProtocol = reply?.protocol ?? null;
state.serverBuild = reply?.build ?? null;
// The pong carries the server's own time (internal/protocol/message.go `Time`),
// shown in the Settings connection card.
state.serverTime = reply?.time ?? null;
// Update the shell's compact status at once; the Settings status card is
// repainted by the content render `loadCurrentView` already performs.
renderHeader();
// 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;
// The watch is connection-scoped, not route-scoped: it was started above (its
// subscribe is already sent) and its own resync seeds the run list, so opening
// the pending route must not wait for it here.
watched.catch(() => {});
await applyRoute(route);
return;
}
// Seed from the authoritative list first, then watch: the subscribe snapshot
// and its ack are treated as seeds, so a reconnect gap never notifies.
const runsFresh = await watched;
await loadCurrentView(false, { runsFresh });
// 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);
// R10 removed the 1 Hz run poll: a run detail is advanced by pushed
// `run_event` frames and the shared clocks, so a destination change has no
// poll to stop.
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;
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, { runsFresh = false } = {}) {
// Settings is local: it has no server-backed list to (re)load, so switching to
// or refreshing it must never raise the "connect first" error.
if (state.view === "settings") {
renderContent();
return;
}
if (state.connection.kind !== "connected") {
state.error = "Connect to the server first.";
renderContent();
return;
}
if (state.view === "templates") {
await loadTemplates(force);
return;
}
if (state.view === "chat") {
await loadChatSessions(force);
return;
}
state.loading = true;
state.error = "";
renderContent();
try {
if (state.view === "pipelines") {
state.pipelines = await repo.listPipelines();
state.pipelinesLoaded = true;
// The last-run line joins list_runs onto the pipelines, so the history is
// fetched alongside them; runsLoaded distinguishes a genuinely empty
// history from one that has not arrived yet. On connect that history has
// just been read by the run watch's own resync, so it is not read twice.
if (!runsFresh) {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
if (usage) state.usage = usage;
state.runsLoaded = true;
}
} else if (!runsFresh) {
const { runs, usage } = await repo.listRuns();
state.runs = runs;
runAlerts.seed(runs);
state.usage = usage;
state.runsLoaded = true;
}
// The nav badge reads the pipeline count, and the Pipelines destination is
// one click away: load that list once when it has not been seen, whether the
// runs came from the watch's resync or a direct read.
if (!state.pipelinesLoaded) {
try {
state.pipelines = await repo.listPipelines();
state.pipelinesLoaded = true;
} catch {
// The Pipelines destination will report its own load failure.
}
}
state.loading = false;
renderContent();
// The run list the attention surface derives from has just (re)loaded, so
// bring the bell's badge up to date.
refreshAttentionBell();
// Keep the current selection fresh after a refresh.
if (force && state.view === "runs" && state.selectedRunId) {
await selectRun(state.selectedRunId, { silent: true });
}
} catch (err) {
setError(err);
}
}
// ---------------------------------------------------------------------------
// The live run stream (R10)
// ---------------------------------------------------------------------------
/** Render whatever a run-state change touched, without re-reading anything. */
function renderRunState() {
if (state.view === "runs" || state.view === "pipelines") renderContent();
refreshAttentionBell();
}
/** Record the explicit stream state and repaint the badge when it changed. */
function setRunStream(next) {
if (state.runStream === next) return;
state.runStream = next;
renderRunState();
}
/**
* Drop the watch bookkeeping and invalidate any in-flight read. Called on every
* socket drop and before a new subscribe, so a superseded read can neither write
* its result over newer state nor confirm a stream that is gone. The stream's own
* state is set by the caller (streamDown / startRunWatch).
*/
function clearRunWatch() {
runWatch.workspace = null;
runWatch.subscriptionId = null;
runWatch.generation += 1;
runWatch.runsResyncQueued = false;
}
/** Nothing is watched: reflect the connection's own state in the live badge. */
function streamDown() {
clearRunWatch();
state.runStream =
state.connection.kind === "connecting" || state.connection.kind === "disconnected"
? RunStream.Connecting
: RunStream.Offline;
}
/** A subscription ack, a push, or a successful watch read proves the stream is live. */
function confirmStreamLive() {
if (runWatch.workspace === null) return;
setRunStream(RunStream.Live);
}
/** A push-driven read failed: stop claiming live until something confirms it again. */
function markStreamDegraded() {
if (runWatch.workspace !== null) setRunStream(RunStream.Connecting);
}
/**
* Establish the one watch over every workspace the client displays (the blank
* scope, which the server treats as "any"): the runs list is server-wide, so the
* client asks for the runs it shows rather than the one workspace the operator
* configured. It best-effort drops the previous watch first (the server caps
* subscriptions per connection), marks the watch before sending so a push that
* races the send is still attributed to it, then takes one authoritative resync
* of the watched state. Resolves true when that resync succeeded, so the caller
* knows the runs list is already fresh.
*/
async function startRunWatch() {
const generation = ++runWatch.generation;
runWatch.workspace = null;
runWatch.subscriptionId = null;
state.runStream = RunStream.Connecting;
try {
repo.unsubscribeRuns();
} catch {
// The drop failed; the new subscribe is still attempted, but the badge stays
// "reconnecting" until an ack, push or successful read confirms the new watch.
state.runStream = RunStream.Connecting;
}
if (generation !== runWatch.generation || state.connection.kind !== "connected") return false;
runWatch.workspace = "";
// L5: seed from the list already in hand, and treat the subscribe snapshot as
// seeds too (it can arrive before any ack). The authoritative resync below
// then seeds again, so a reconnect gap never notifies late.
runAlerts.seed(state.runs);
runAlerts.beginSeed();
try {
runWatch.subscriptionId = repo.subscribeRuns("", []);
} catch {
runAlerts.endSeed();
clearRunWatch();
setRunStream(RunStream.Offline);
return false;
}
let resynced = false;
try {
resynced = await scheduleRunsResync();
} finally {
runAlerts.endSeed();
}
if (generation !== runWatch.generation) return false;
if (state.runDetail?.id != null) scheduleRunDetailSync(state.runDetail.id);
return resynced;
}
/**
* Re-reads the runs list once for a burst of frames the list could not fold (a
* created run whose summary is not in the compact delta, or a terminal
* transition that changes the usage aggregate) and once after every
* (re)subscribe. Coalesced — at most one in flight with one queued follow-up —
* and it loops while a frame arrived, so no push is ever dropped. A failed read
* stops claiming live and is retried with a bounded backoff before giving up.
* Resolves true when the last read succeeded.
*/
function scheduleRunsResync() {
if (runWatch.runsResyncJob) {
runWatch.runsResyncQueued = true;
return runWatch.runsResyncJob;
}
const job = (async () => {
let attempt = 0;
let ok = true;
for (;;) {
runWatch.runsResyncQueued = false;
const generation = runWatch.generation;
try {
const { runs, usage } = await repo.listRuns();
if (generation !== runWatch.generation) {
// The watch was re-established (or dropped) while this read was in
// flight; its result is superseded, so re-read under the new watch
// instead of writing stale state or clearing the badge.
runWatch.runsResyncQueued = true;
continue;
}
state.runs = runs;
runAlerts.seed(runs);
if (usage) state.usage = usage;
state.runsLoaded = true;
attempt = 0;
ok = true;
confirmStreamLive();
renderRunState();
} catch {
if (generation !== runWatch.generation) {
runWatch.runsResyncQueued = true;
continue;
}
markStreamDegraded();
attempt += 1;
if (attempt > RUN_SYNC_RETRY_LIMIT) {
ok = false;
break;
}
await delay(RUN_SYNC_RETRY_BASE_MS * attempt);
if (generation !== runWatch.generation) {
runWatch.runsResyncQueued = true;
continue;
}
runWatch.runsResyncQueued = true;
ok = false;
}
if (!runWatch.runsResyncQueued) break;
}
return ok;
})();
runWatch.runsResyncJob = job;
job.finally(() => {
if (runWatch.runsResyncJob === job) runWatch.runsResyncJob = null;
});
return job;
}
/**
* Fetches the full run detail once for a burst of settled-step/terminal pushes,
* so the artifacts and output the compact delta omits appear without a timer. A
* response is dropped and retried when a newer frame landed while the fetch was
* in flight, so the fetch can never regress the fold. The queued request is keyed
* by run id, so opening another run mid-fetch fetches that run instead of
* discarding the request; a run the operator has left is never written over.
*/
function scheduleRunDetailSync(runId) {
const targetId = Number(runId);
if (!(targetId > 0)) return null;
if (runWatch.detailSyncJob) {
runWatch.detailSyncRequestedRunId = targetId;
return runWatch.detailSyncJob;
}
const job = (async () => {
let target = targetId;
let attempt = 0;
while (target != null) {
runWatch.detailSyncRequestedRunId = null;
const generation = runWatch.generation;
const deltaCount = runWatch.detailDeltaCount;
try {
const run = await repo.getRun(target);
attempt = 0;
if (generation !== runWatch.generation) {
// A drop/re-subscribe superseded this read; re-read for the new watch
// rather than writing a result from the old one.
runWatch.detailSyncRequestedRunId = target;
continue;
}
if (state.runDetail?.id === target) {
if (runWatch.detailDeltaCount === deltaCount) {
state.runDetail = run;
renderRunState();
} else {
// A newer frame overtook the fetch; re-read rather than write the
// older run over it.
runWatch.detailSyncRequestedRunId = target;
}
}
// else: the operator left this run; its detail is no longer shown.
} catch {
if (generation !== runWatch.generation) {
runWatch.detailSyncRequestedRunId = target;
continue;
}
markStreamDegraded();
attempt += 1;
if (attempt > RUN_SYNC_RETRY_LIMIT) return;
await delay(RUN_SYNC_RETRY_BASE_MS * attempt);
if (generation !== runWatch.generation) {
runWatch.detailSyncRequestedRunId = target;
continue;
}
// A run opened meanwhile wins over retrying this one.
if (runWatch.detailSyncRequestedRunId == null) runWatch.detailSyncRequestedRunId = target;
}
target = runWatch.detailSyncRequestedRunId;
}
})();
runWatch.detailSyncJob = job;
job.finally(() => {
if (runWatch.detailSyncJob === job) runWatch.detailSyncJob = null;
});
return job;
}
/**
* Fold one pushed `run_event` frame into whatever local state it names: the runs
* list (and so the pipeline rows' last-run line and the attention bell) in
* place, and the open run detail. A frame for a run the list does not hold
* re-syncs the list once; a frame that changed the detail and carries a settled
* step, a waiting step/run or a terminal run also fetches the full detail once.
*/
function applyRunEvent(frame) {
const runId = Number(frame?.run_id);
if (!(runId > 0)) return;
let listChanged = false;
if (state.runsLoaded) {
const fold = foldRunEvent(state.runs, frame);
if (fold.needsResync) {
scheduleRunsResync();
} else if (fold.runs !== state.runs) {
state.runs = fold.runs;
listChanged = true;
renderRunState();
// A terminal transition also settles the usage aggregate (the active
// count), which the delta does not carry; one server read refreshes it. A
// duplicate terminal frame changes nothing above, so it triggers no read.
if (frame.step == null && isTerminalRunStatus(frame.status)) scheduleRunsResync();
}
}
const detail = state.runDetail;
if (detail && Number(detail.id) === runId) {
runWatch.detailDeltaCount += 1;
const folded = foldRunEventDetail(detail, frame);
const detailChanged = folded !== detail;
if (detailChanged) {
state.runDetail = folded;
renderRunState();
}
if (runDetailNeedsFullSync(frame) && (detailChanged || listChanged)) {
scheduleRunDetailSync(runId);
}
}
// A list-only change with the detail open is still a fold; if the run list was
// not in hand, the resync above covers the new row.
}
/**
* 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) {
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();
// The narrow layout hides the list on selection; move focus out of the row
// immediately, then again to the real heading once the reply paints.
focusDetailHeading();
try {
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();
focusDetailHeading();
} catch (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();
}
}
/** 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) {
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();
focusDetailHeading();
}
try {
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)) {
return;
}
state.runDetail = detail;
renderContent();
if (!silent) focusDetailHeading();
// The run detail is no longer polled: the watch's pushed `run_event` frames
// advance it live (R10), and a settled/terminal frame triggers one full
// `get_run` for the heavy fields the compact delta omits.
} catch (err) {
if (!runStillSelected(id)) {
return;
}
if (silent) {
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();
}
}
/**
* (Re)start the shared runs-list clock: it ticks once a second only while a
* shown run is executing, updating each running row's meta line in place (never
* a full re-render, so an open filter/sort menu is not torn down). The elapsed
* value is derived from the run's server start timestamp, so it survives a
* reconnect.
*/
function refreshListClock() {
stopListClock();
listNow = Date.now();
if (state.view === "runs" && state.runs.some((run) => run.executing)) {
listClock = setInterval(() => {
listNow = Date.now();
for (const node of document.querySelectorAll(".run-row-meta[data-run-id]")) {
const id = Number(node.getAttribute("data-run-id"));
const run = state.runs.find((candidate) => candidate.id === id);
if (run && run.executing) node.textContent = metaText(run, listNow);
}
}, 1000);
}
}
function stopListClock() {
if (listClock) {
clearInterval(listClock);
listClock = null;
}
}
/**
* (Re)start the run detail's own clock: it ticks once a second only while the
* shown run is executing, updating just the Duration row in place (never a full
* re-render, so an open stage pane and its scroll are not torn down). The value
* is derived from the server's start timestamp, so it survives a reconnect.
*/
function refreshDetailClock() {
stopDetailClock();
detailNow = Date.now();
if (state.view === "runs" && isExecuting(state.runDetail)) {
detailClock = setInterval(() => {
detailNow = Date.now();
const node = document.querySelector(".run-duration[data-run-id]");
if (node && state.runDetail) node.textContent = runDurationText(state.runDetail, detailNow) ?? "";
}, 1000);
}
}
function stopDetailClock() {
if (detailClock) {
clearInterval(detailClock);
detailClock = null;
}
}
// ---------------------------------------------------------------------------
// View modules
// ---------------------------------------------------------------------------
// The view modules receive the page shell through one runtime object rather than
// importing app.js, so the dependency direction stays app -> views (no cycle).
const runtime = {
state,
client,
repo,
runAlerts,
attentionLayer,
searchHost,
render,
renderContent,
renderHeader,
focusDetailHeading,
focusListHeading,
endpointConfigured,
setServerUrlDraft,
pushRoute,
applyRoute,
openConfiguredEndpoint,
onReconnectClicked,
selectPipeline,
selectRun,
setError,
loadCurrentView,
};
const views = {
attention: createAttentionView(runtime),
settings: createSettingsView(runtime),
pipelines: createPipelinesView(runtime),
templates: createTemplatesView(runtime),
runs: createRunsView(runtime),
dialogs: createDialogsView(runtime),
runDetail: createRunDetailView(runtime),
chat: createChatView(runtime),
search: createSearchView(runtime),
};
runtime.views = views;
const {
renderAttentionBell,
refreshAttentionBell,
renderAttentionSheet,
closeAttentionSheet,
onRunAlertFrame,
} = views.attention;
const { renderSettingsView, refreshServerUrlError } = views.settings;
const { renderPipelineList, renderPipelineDetail } = views.pipelines;
const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection, closeTemplateCreateDialog } =
views.templates;
const renderRunList = () => views.runs.renderRunList(listNow);
const renderRunDetail = () => views.runDetail.renderRunDetail(detailNow);
const {
renderChatList,
renderChatCreate,
renderChatConversation,
afterChatRender,
captureChatPosition,
refreshChatClock,
stopChatClock,
loadChatSessions,
loadChatDirectories,
startNewChat,
openChatSession,
subscribeChatSession,
clearChatSubscriptions,
settleChatThreads,
resyncOpenChat,
onChatEvent,
onChatPermission,
onChatFrame,
dismissChatClose,
dismissChatRename,
} = views.chat;
const {
openSearch,
closeSearch,
renderSearch,
onSearchInput,
sendSearchNow,
} = views.search;
const { openDecisionSheet, closeDecisionSheet, dismissConfirm, dismissActionError } = views.dialogs;
const { closeStagePane } = views.runDetail;
// Kept as named exports for the UI smoke's page-rendered markdown/tool samples.
export const renderToolCallRow = views.chat.renderToolCallRow;
export const renderToolDiff = views.chat.renderToolDiff;
export const renderMarkdown = views.chat.renderMarkdown;
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
client.addEventListener("state", (event) => {
const next = event.detail;
const wasConnected = state.connection.kind === "connected";
const previousKind = state.connection.kind;
state.connection = next;
if (next.kind === "connected" && !wasConnected) {
onConnected();
}
if (next.kind !== "connected" && previousKind === "connected") {
stopListClock();
stopDetailClock();
stopChatClock();
// The socket dropped: the server detaches every chat subscription with it
// (there is no chat_unsubscribe), and the frames feeding any running turn are
// gone, so no thread keeps claiming to run until a fresh frame proves it.
clearChatSubscriptions();
settleChatThreads();
// Drop the run-status baseline but keep this page session's notified keys:
// the reconnect reseeds from the fresh list before it resubscribes, so a
// transition hidden by the gap can never notify late.
runAlerts.reset();
}
if (next.kind !== "connected") {
// Nothing is watched while the socket is down; an in-flight read is
// invalidated and the badge falls back to Connecting (or Offline when idle).
streamDown();
}
// A reconnect (not a first connect): re-attach the open chat's stream and
// refresh its history wholesale, so a gap that swallowed the end of a turn is
// repaired rather than shown stale.
if (next.kind === "connected" && (previousKind === "connecting" || previousKind === "disconnected")) {
resyncOpenChat();
}
render();
});
// The client surfaces every unsolicited envelope as a DOM-free `frame` event
// (client.js). A `chat_event` frame is folded twice, on purpose: the live
// transcript (C5) folds the frame itself, and the composer's own bookkeeping
// clears the queued notice and releases the Stop control. A frame for any other
// type is ignored.
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message) return;
// The live run stream (R10). A pushed `run_event` only reaches a subscriber, so
// it confirms the watch even when the server never acks the subscribe. A reply
// carrying our subscribe id is the optional ack (live) or a refusal (offline).
if (message.type === Protocol.RUN_EVENT) {
const frame = message[Protocol.RUN_EVENT];
if (frame) {
confirmStreamLive();
applyRunEvent(frame);
// L5: the same frame feeds the notification ledger.
onRunAlertFrame(frame);
}
return;
}
if (message.id != null && message.id === runWatch.subscriptionId) {
if (message.type === Protocol.SUBSCRIBE) {
confirmStreamLive();
return;
}
if (message.type === Protocol.ERROR) {
clearRunWatch();
setRunStream(RunStream.Offline);
return;
}
}
if (message.type === Protocol.CHAT_PERMISSION) {
const permission = message[ChatKeys.PERMISSION];
if (permission) onChatPermission(permission);
return;
}
if (message.type !== Protocol.CHAT_EVENT) return;
const frame = message[ChatKeys.EVENT];
if (frame) onChatEvent(frame);
onChatFrame(message);
});
// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the
// omni-search field and the attention sheet are modal: Escape closes the topmost
// one (the artifact viewer or the diff viewer, when either is above, owns Escape
// first via its own listener). The attention sheet, when open, is the topmost
// overlay and owns Escape first. Registered once; every branch is a no-op when
// nothing is open.
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape") return;
if (state.attentionSheetOpen) {
event.preventDefault();
closeAttentionSheet();
return;
}
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
if (state.templateCreateOpen) {
event.preventDefault();
closeTemplateCreateDialog();
return;
}
if (state.actionError) {
event.preventDefault();
dismissActionError();
return;
}
if (state.chatRename) {
event.preventDefault();
dismissChatRename();
return;
}
if (state.chatClose) {
event.preventDefault();
dismissChatClose();
return;
}
if (state.confirmKind) {
event.preventDefault();
dismissConfirm();
return;
}
if (state.decisionOpen) {
event.preventDefault();
closeDecisionSheet();
return;
}
if (state.runStagePane) {
event.preventDefault();
closeStagePane();
return;
}
if (state.chatMenu) {
event.preventDefault();
state.chatMenu = null;
renderContent();
return;
}
if (state.searchOpen) {
event.preventDefault();
closeSearch();
}
});
// A click anywhere outside an open Chat actions menu closes it, so a menu never
// lingers behind another row's selection. The wrap element (button + panel)
// keeps its own clicks from closing it.
document.addEventListener("click", (event) => {
if (!state.chatMenu) return;
const target = event.target;
if (target instanceof Element && target.closest(".chat-menu-wrap")) return;
state.chatMenu = null;
renderContent();
});
// Return-to-foreground recovery (T4): the page becomes visible again, or the
// browser reports it is back online, and the client drives its socket back
// without waiting out the backoff. DOM-only, and idempotent.
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") onForegroundActive();
});
window.addEventListener("online", onForegroundActive);
// Prefill from a previous session only; the user still confirms with Connect.
// 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();
state.notifyAsked = loadNotifyAsked();
// 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);
// A previously configured endpoint re-opens on load: with connection moved into
// Settings, a reload/deep link must not require a detour through Settings before
// the pending route can load. With nothing stored, Settings is the only place
// that asks for a URL (the shell says "Not configured").
const bootServerUrl = readServerUrl(localStorage).trim();
// 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();
// One responsive chrome refresh: CSS owns the wide/narrow switch; this only
// repoints the section mounts' accessible state and the roving tabindex.
let shellResizeTimer = null;
window.addEventListener("resize", () => {
if (shellResizeTimer) clearTimeout(shellResizeTimer);
shellResizeTimer = setTimeout(() => {
shellResizeTimer = null;
renderHeader();
}, 120);
});
// A previously configured endpoint re-opens on load (see bootServerUrl).
if (bootServerUrl) openConfiguredEndpoint({ surfaceError: false });