2717 lines
101 KiB
JavaScript
2717 lines
101 KiB
JavaScript
// 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 { readGraphExpanded } from "./graphPrefs.js";
|
||
import { readArtifactView } from "./artifactViewPrefs.js";
|
||
import { readLayoutPrefs, writeLayoutPrefs } from "./layoutPrefs.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 { backChevronIcon, h } from "./dom.js";
|
||
import { createModalController } from "./modal.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";
|
||
import { createSchedulesView } from "./views/schedules.js";
|
||
import { installMobileViewport } from "./mobileViewport.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);
|
||
installMobileViewport();
|
||
|
||
// Register the app's shell service worker where the browser allows it (a secure
|
||
// context: https, localhost, or the desktop app). On a plain-LAN http origin the
|
||
// page still works; only installation/offline caching is unavailable there.
|
||
if (typeof navigator !== "undefined" && "serviceWorker" in navigator) {
|
||
const secure =
|
||
typeof location !== "undefined" &&
|
||
(location.protocol === "https:" ||
|
||
location.hostname === "localhost" ||
|
||
location.hostname === "127.0.0.1");
|
||
if (secure) {
|
||
window.addEventListener("load", () => {
|
||
navigator.serviceWorker.register("/sw.js").catch(() => undefined);
|
||
});
|
||
}
|
||
}
|
||
|
||
// 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);
|
||
|
||
/** The three detail section choices are sticky and survive a reload. */
|
||
const SECTION_STORAGE_KEYS = {
|
||
pipelines: "pipelines.web.pipelineTab.v1",
|
||
runs: "pipelines.web.runTab.v1",
|
||
templates: "pipelines.web.templateTab.v1",
|
||
};
|
||
|
||
function readSection(key, fallback) {
|
||
try {
|
||
return localStorage.getItem(SECTION_STORAGE_KEYS[key]) || fallback;
|
||
} catch {
|
||
return fallback;
|
||
}
|
||
}
|
||
|
||
function writeSection(key, value) {
|
||
try {
|
||
localStorage.setItem(SECTION_STORAGE_KEYS[key], value);
|
||
} catch {
|
||
// Storage may be unavailable; the in-memory choice still applies.
|
||
}
|
||
}
|
||
|
||
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: readSection("pipelines", "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,
|
||
// Expanded by default; a collapse is remembered (graphPrefs.js).
|
||
pipelineGraphExpanded: readGraphExpanded(),
|
||
// The Run pipeline dialog: pipeline/version, prompt, working directory,
|
||
// notification mode and its loading/error state.
|
||
runStart: null,
|
||
// Gallery or list for run artifacts; a per-operator choice (artifactViewPrefs.js).
|
||
artifactView: readArtifactView(),
|
||
// Starred chat sessions: filled from chat_sessions (server-shared).
|
||
chatStars: new Set(),
|
||
// The collapsed rail/list choices (layoutPrefs.js), restored per device.
|
||
...readLayoutPrefs(),
|
||
// Whether the CLOSED chats group is expanded (the chevron beside its name).
|
||
chatClosedOpen: false,
|
||
chatCollapsedDirs: new Set(),
|
||
chatModelPicker: null,
|
||
chatModels: [],
|
||
chatModelsFor: "",
|
||
chatModelsLoading: false,
|
||
chatModelsError: "",
|
||
chatModelQuery: "",
|
||
chatModelBusy: false,
|
||
// The last time each destination's data arrived (manual refresh or a socket
|
||
// push); the list's Refresh button shows it on hover.
|
||
lastUpdated: {},
|
||
// 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,
|
||
runGraphExpanded: readGraphExpanded(),
|
||
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: readSection("templates", "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: readSection("runs", "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,
|
||
// The keyboard-selected result (ArrowUp/Down) and the row Enter opens.
|
||
searchActiveIndex: 0,
|
||
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,
|
||
// The tool-call panel (C6): the turns whose panel is open and the individual
|
||
// rows the operator has expanded, keyed the same way as the old inline state 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,
|
||
chatBackends: ["opencode"],
|
||
};
|
||
|
||
// 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.filter((destination) => destination.key !== "settings").map((destination) =>
|
||
destinationTab(destination, "rail"),
|
||
),
|
||
);
|
||
|
||
const dockTabs = DESTINATIONS.filter((destination) => destination.key !== "settings");
|
||
const dockDestinations = h(
|
||
"div",
|
||
{
|
||
id: "dockDestinations",
|
||
class: "dock-tabs",
|
||
role: "tablist",
|
||
"aria-label": "Destinations",
|
||
},
|
||
...dockTabs.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");
|
||
|
||
function settingsControl(mount) {
|
||
return h(
|
||
"button",
|
||
{
|
||
id: mount === "rail" ? "railSettings" : "dockSettings",
|
||
class: mount === "rail" ? "shell-settings rail-settings" : "shell-settings dock-settings",
|
||
type: "button",
|
||
title: "Settings",
|
||
"aria-label": "Settings",
|
||
"data-settings-destination": "settings",
|
||
onclick: () => goToDestination("settings"),
|
||
},
|
||
icon("settings"),
|
||
);
|
||
}
|
||
|
||
const railSettings = settingsControl("rail");
|
||
const dockSettings = settingsControl("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("button", {
|
||
id: "railCollapse",
|
||
class: "shell-collapse rail-collapse",
|
||
type: "button",
|
||
title: "Collapse navigation",
|
||
"aria-label": "Collapse navigation",
|
||
"aria-expanded": "true",
|
||
}),
|
||
h(
|
||
"div",
|
||
{ class: "rail-brand" },
|
||
h("img", {
|
||
class: "rail-brand-icon",
|
||
src: "/favicon.svg",
|
||
alt: "",
|
||
width: "26",
|
||
height: "26",
|
||
"aria-hidden": "true",
|
||
}),
|
||
h("span", { text: "Pipelines" }),
|
||
),
|
||
railSearch,
|
||
h("div", { class: "rail-divider rail-divider-visible", role: "presentation" }),
|
||
railDestinations,
|
||
h("div", { class: "rail-divider", role: "presentation" }),
|
||
railSections,
|
||
h("div", { class: "rail-footer" }, h("div", { class: "rail-footer-row" }, railStatus, railSettings)),
|
||
);
|
||
|
||
// 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" },
|
||
h("div", { class: "dock-status-row" }, dockStatus, dockSettings),
|
||
// The destinations come first and Search sits on the right; every item takes
|
||
// an equal share of the bar on a phone.
|
||
// One equal share per destination; Search is one more share of the same row,
|
||
// so the whole bar divides evenly however many destinations exist.
|
||
h("div", { class: "dock-row", style: `--dock-count: ${dockTabs.length}` }, 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" });
|
||
// Dialogs are re-parented here, outside the inert app root. `inert` inherits and
|
||
// cannot be overridden by a descendant, so a panel left inside .app-root could
|
||
// never be interactive while the background is inert.
|
||
const modalLayer = h("div", { id: "modalLayer" });
|
||
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));
|
||
appRail.querySelector("#railCollapse")?.addEventListener("click", () => {
|
||
state.railCollapsed = !state.railCollapsed;
|
||
applyLayoutState();
|
||
if (typeof window.matchMedia === "function") {
|
||
const wideQuery = window.matchMedia("(min-width: 600px)");
|
||
const onWideChange = () => {
|
||
applyLayoutState();
|
||
renderContent();
|
||
};
|
||
if (typeof wideQuery.addEventListener === "function") wideQuery.addEventListener("change", onWideChange);
|
||
else if (typeof wideQuery.addListener === "function") wideQuery.addListener(onWideChange);
|
||
}
|
||
});
|
||
document.addEventListener("click", (event) => {
|
||
const button = event.target instanceof Element ? event.target.closest("#listCollapse") : null;
|
||
if (!button) return;
|
||
state.listCollapsed = !state.listCollapsed;
|
||
writeLayoutPrefs(state);
|
||
renderContent();
|
||
});
|
||
applyLayoutState();
|
||
document.body.append(attentionLayer);
|
||
document.body.append(modalLayer);
|
||
|
||
// One controller owns Escape, the Tab trap, the background's inert state and
|
||
// focus return for every role="dialog" surface.
|
||
const modal = createModalController({
|
||
document,
|
||
layer: () => modalLayer,
|
||
background: () => document.querySelector(".app-root"),
|
||
skipLinks: () => [...document.querySelectorAll(".skip-link")],
|
||
});
|
||
|
||
/** 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 tabs = [...document.querySelectorAll("[data-destination]")];
|
||
const keys = tabs.map((tab) => tab.getAttribute("data-destination"));
|
||
// Settings is a separate control beside the status, so while it is open no
|
||
// destination tab is selected; keep the first one in the roving order.
|
||
const activeIndex = keys.indexOf(activeKey);
|
||
const roving = activeIndex >= 0 ? activeIndex : 0;
|
||
for (const tab of tabs) {
|
||
const key = tab.getAttribute("data-destination");
|
||
const isActive = key === activeKey;
|
||
tab.setAttribute("aria-selected", isActive ? "true" : "false");
|
||
tab.setAttribute("tabindex", rovingTabindex(roving, keys.indexOf(key)));
|
||
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`);
|
||
}
|
||
for (const control of document.querySelectorAll("[data-settings-destination='settings']")) {
|
||
const active = activeKey === "settings";
|
||
control.classList.toggle("active", active);
|
||
if (active) control.setAttribute("aria-current", "page");
|
||
else control.removeAttribute("aria-current");
|
||
}
|
||
// The list's data may have arrived before its first paint (the run watch's
|
||
// snapshot); stamp it so the Refresh tooltip is never "Not refreshed yet"
|
||
// while the list is visibly populated.
|
||
const loaded =
|
||
state.view === "runs"
|
||
? state.runsLoaded
|
||
: state.view === "pipelines"
|
||
? state.pipelinesLoaded
|
||
: state.view === "chat"
|
||
? state.chatLoaded
|
||
: true;
|
||
if (loaded && !(Number(state.lastUpdated?.[state.view]) > 0)) touchView(state.view);
|
||
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;
|
||
writeSection(state.view, key);
|
||
renderContent();
|
||
focusSectionTab(key);
|
||
}
|
||
|
||
function focusSectionTab(key) {
|
||
const railTab = document.getElementById(`rail-tab-${key}`);
|
||
const stripTab = document.getElementById(`strip-tab-${key}`);
|
||
// Whichever mount is on screen: wide screens show the strip at the top of the
|
||
// detail, narrow ones the bottom strip, and the rail copy is display:none.
|
||
const visible = [railTab, stripTab].find((tab) => tab && tab.offsetParent !== null);
|
||
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, actions = [] } = {}) {
|
||
const tag = detailOpen ? "h2" : "h1";
|
||
// The destination rail/dock already names the screen. Keep the heading in the
|
||
// accessibility tree for landmarks and focus restoration, but do not print it
|
||
// twice above the list. A narrow header exists only when it carries an action
|
||
// (the Runs attention bell); otherwise the list starts with its own toolbar.
|
||
const heading = h(tag, { class: "pane-title sr-only", id: "listTitle", tabindex: "-1", text: title });
|
||
if (!isWideLayout() && actions.length === 0) return heading;
|
||
const head = h("div", { class: "pane-head pane-head-compact" }, heading);
|
||
head.append(h("div", { class: "pane-head-actions" }, ...actions, listCollapseButton()));
|
||
return head;
|
||
}
|
||
|
||
/** The icon that collapses the list pane to a narrow strip and back. */
|
||
function listCollapseButton() {
|
||
const collapsed = state.listCollapsed === true;
|
||
return h("button", {
|
||
id: "listCollapse",
|
||
class: "shell-collapse list-collapse",
|
||
type: "button",
|
||
title: collapsed ? "Expand list" : "Collapse list",
|
||
"aria-label": collapsed ? "Expand list" : "Collapse list",
|
||
"aria-expanded": collapsed ? "false" : "true",
|
||
text: collapsed ? "\u203a" : "\u2039",
|
||
});
|
||
}
|
||
|
||
function applyLayoutState() {
|
||
appRail.classList.toggle("collapsed", state.railCollapsed === true && isWideLayout());
|
||
const railButton = document.getElementById("railCollapse");
|
||
if (railButton) {
|
||
const label = state.railCollapsed ? "Expand navigation" : "Collapse navigation";
|
||
railButton.title = label;
|
||
railButton.setAttribute("aria-label", label);
|
||
railButton.setAttribute("aria-expanded", state.railCollapsed ? "false" : "true");
|
||
railButton.textContent = state.railCollapsed ? "\u203a" : "\u2039";
|
||
}
|
||
writeLayoutPrefs(state);
|
||
}
|
||
|
||
function backButton(view) {
|
||
return h(
|
||
"button",
|
||
{
|
||
class: "ghost back-button",
|
||
type: "button",
|
||
"aria-label": "Back to list",
|
||
title: "Back to list",
|
||
onclick: () => closeDetail(view),
|
||
},
|
||
backChevronIcon(),
|
||
);
|
||
}
|
||
|
||
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") {
|
||
const route = { kind: "chat" };
|
||
pushRoute(route);
|
||
applyRoute(route);
|
||
restoreListFocus(restore);
|
||
return;
|
||
}
|
||
if (view === "templates") {
|
||
const route = { kind: "templates" };
|
||
pushRoute(route);
|
||
applyRoute(route);
|
||
restoreListFocus(restore);
|
||
return;
|
||
}
|
||
const route = view === "runs" && state.runFilters.pipelineId != null
|
||
? { kind: "runs", pipelineId: state.runFilters.pipelineId }
|
||
: { 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({ preventScroll: true });
|
||
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) {
|
||
// One header for every detail screen: the same chevron control on the left
|
||
// and the screen's own h1 beside it, vertically centred. The title leaves the
|
||
// scroller so it cannot drift away from the control.
|
||
const header = h("div", { class: "detail-head" }, backButton(view));
|
||
const title = body.querySelector("#detailTitle");
|
||
if (title) {
|
||
title.remove();
|
||
header.append(title);
|
||
}
|
||
pane.append(header);
|
||
}
|
||
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();
|
||
}
|
||
|
||
const listScrollPositions = new Map();
|
||
|
||
function renderContent() {
|
||
const previousList = content.querySelector(".list-pane");
|
||
const previousScroll = previousList?.querySelector(".list-scroll");
|
||
if (previousScroll && previousList.getClientRects().length > 0) {
|
||
listScrollPositions.set(previousList.dataset.listView, previousScroll.scrollTop);
|
||
}
|
||
// 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);
|
||
modal.reconcile();
|
||
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", {
|
||
// Collapsing a pane is a wide-screen affordance; a phone always keeps the
|
||
// list and the bottom destination bar available.
|
||
class: `pane-layout${state.listCollapsed && isWideLayout() ? " list-collapsed" : ""}`,
|
||
"data-active-pane": activePane,
|
||
});
|
||
|
||
if (view === "pipelines") {
|
||
layout.append(
|
||
h(
|
||
"section",
|
||
{ class: "list-pane", "data-list-view": view, "aria-label": "Pipelines list" },
|
||
paneHeading("Pipelines", { detailOpen }),
|
||
renderPipelineList(),
|
||
),
|
||
detailPaneFor(view, renderPipelineDetail(), { detailOpen, tabs: model.tabs }),
|
||
);
|
||
} else if (view === "runs") {
|
||
layout.append(
|
||
h(
|
||
"section",
|
||
{ class: "list-pane", "data-list-view": view, "aria-label": "Runs list" },
|
||
paneHeading("Runs", { detailOpen }),
|
||
renderRunList(),
|
||
),
|
||
detailPaneFor(view, renderRunDetail(), { detailOpen, tabs: model.tabs }),
|
||
);
|
||
} else if (view === "templates") {
|
||
layout.append(
|
||
h(
|
||
"section",
|
||
{ class: "list-pane", "data-list-view": view, "aria-label": "Templates list" },
|
||
paneHeading("Templates", { detailOpen }),
|
||
renderTemplateGallery(),
|
||
),
|
||
detailPaneFor(view, renderTemplateDetail(), { detailOpen, tabs: model.tabs }),
|
||
);
|
||
} else {
|
||
layout.append(
|
||
h(
|
||
"section",
|
||
{ class: "list-pane", "data-list-view": view, "aria-label": "Chat list" },
|
||
paneHeading("Chat", { detailOpen }),
|
||
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" });
|
||
// The conversation and create panes each put their own compact Back control
|
||
// in the chat bar; the generic full-width pane-back row is for the other
|
||
// detail panes, which have no header of their own.
|
||
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();
|
||
// A list re-render is animated, never jump-cut: rows that moved keep their
|
||
// visual place with a FLIP, new rows fade in, and a destination/tab/selection
|
||
// change fades the pane in once (the same view's live updates do not replay it).
|
||
const reduceMotion =
|
||
typeof window.matchMedia === "function" &&
|
||
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||
const before = new Map();
|
||
if (!reduceMotion) {
|
||
for (const node of content.querySelectorAll("[data-animate-key]")) {
|
||
before.set(node.getAttribute("data-animate-key"), node.getBoundingClientRect());
|
||
}
|
||
}
|
||
content.replaceChildren(...nodes);
|
||
const restoredList = content.querySelector(".list-pane .list-scroll");
|
||
if (restoredList) restoredList.scrollTop = listScrollPositions.get(state.view) ?? 0;
|
||
if (!reduceMotion) {
|
||
for (const node of content.querySelectorAll("[data-animate-key]")) {
|
||
const key = node.getAttribute("data-animate-key");
|
||
const prior = before.get(key);
|
||
if (prior) {
|
||
const rect = node.getBoundingClientRect();
|
||
const dx = prior.left - rect.left;
|
||
const dy = prior.top - rect.top;
|
||
if (Math.abs(dx) > 0.5 || Math.abs(dy) > 0.5) {
|
||
node.animate(
|
||
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "translate(0, 0)" }],
|
||
{ duration: 180, easing: "ease-out" },
|
||
);
|
||
}
|
||
} else {
|
||
node.classList.add("row-enter");
|
||
node.addEventListener("animationend", () => node.classList.remove("row-enter"), {
|
||
once: true,
|
||
});
|
||
}
|
||
}
|
||
const key = [
|
||
state.view,
|
||
state.selectedPipelineId ?? "",
|
||
state.selectedRunId ?? "",
|
||
state.runTab ?? "",
|
||
state.pipelineTab ?? "",
|
||
state.chatActiveId ?? "",
|
||
].join("|");
|
||
if (state.lastRenderKey !== key) {
|
||
state.lastRenderKey = key;
|
||
content.classList.remove("view-enter");
|
||
void content.offsetWidth;
|
||
content.classList.add("view-enter");
|
||
}
|
||
}
|
||
if (state.view === "chat") {
|
||
afterChatRender();
|
||
modal.reconcile();
|
||
stopListClock();
|
||
stopDetailClock();
|
||
refreshChatClock();
|
||
return;
|
||
}
|
||
modal.reconcile();
|
||
stopChatClock();
|
||
if (state.view === "runs") {
|
||
refreshListClock();
|
||
refreshDetailClock();
|
||
} else {
|
||
stopListClock();
|
||
stopDetailClock();
|
||
}
|
||
}
|
||
|
||
/** Record that a view's data just arrived. */
|
||
function touchView(view = state.view) {
|
||
state.lastUpdated = { ...(state.lastUpdated ?? {}), [view]: Date.now() };
|
||
}
|
||
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 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.
|
||
*/
|
||
let schedulesEndpoint = null;
|
||
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);
|
||
if (schedulesEndpoint !== validated.wsUrl) {
|
||
views.schedules.clearScheduleCache();
|
||
modal.close("schedule-editor");
|
||
modal.close("schedule-delete");
|
||
schedulesEndpoint = validated.wsUrl;
|
||
}
|
||
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() {
|
||
views.schedules.clearScheduleCache();
|
||
// 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 "chatSession":
|
||
return "chat";
|
||
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") {
|
||
if (r.pipelineId != null) {
|
||
state.runFilters = { ...defaultRunFilters(), pipelineId: r.pipelineId };
|
||
} else {
|
||
state.runFilters = { ...state.runFilters, pipelineId: null };
|
||
}
|
||
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;
|
||
if (r.kind === "pipelineStage") state.pipelineTab = "graph";
|
||
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" || r.kind === "chatSession") {
|
||
state.view = "chat";
|
||
if (!state.chatLoaded) await loadCurrentView();
|
||
if (r.kind === "chat") {
|
||
state.chatActiveId = null;
|
||
renderContent();
|
||
return;
|
||
}
|
||
// A chat detail is a real history entry: opening one pushes /chat/:id, so
|
||
// Back (including Android's back gesture) returns to the chat list rather
|
||
// than the previous destination. An id the server no longer lists falls
|
||
// back to the list instead of leaving a dead pane.
|
||
const known =
|
||
state.chatThreads.has(r.id) || state.chatSessions.some((session) => session.id === r.id);
|
||
if (!connected() || !known) {
|
||
state.chatActiveId = null;
|
||
if (`${location.pathname}${location.search}` !== "/chat") {
|
||
replaceRoute({ kind: "chat" });
|
||
}
|
||
renderContent();
|
||
return;
|
||
}
|
||
state.chatCreate = null;
|
||
state.chatActiveId = r.id;
|
||
renderContent();
|
||
await openChatSession(r.id, { updateRoute: false });
|
||
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 } = {}) {
|
||
if (force && state.view === "pipelines") views.schedules.clearScheduleCache();
|
||
// 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;
|
||
}
|
||
touchView(state.view);
|
||
// 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)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/** Whether the current destination is showing a detail rather than its list. */
|
||
function detailIsOpen(view = state.view) {
|
||
switch (view) {
|
||
case "pipelines":
|
||
return state.selectedPipelineId != null;
|
||
case "runs":
|
||
return state.selectedRunId != null;
|
||
case "chat":
|
||
return state.chatActiveId != null || state.chatCreate != null;
|
||
case "templates":
|
||
return state.selectedTemplateKey != null;
|
||
default:
|
||
return false;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Returning to the page refreshes the visible list once, in place. The manual
|
||
* Refresh controls are gone; live streams cover work in progress and a list that
|
||
* changed elsewhere is picked up on focus instead of waiting for a reload.
|
||
* Menus, dialogs and text fields are left alone so a return never closes what the
|
||
* operator was using.
|
||
*/
|
||
let foregroundRefreshTimer = null;
|
||
|
||
function refreshVisibleListOnForeground() {
|
||
if (typeof document === "undefined" || document.visibilityState !== "visible") return;
|
||
if (state.connection.kind !== "connected" || state.loading) return;
|
||
if (state.view === "settings" || detailIsOpen()) return;
|
||
if (state.searchOpen || state.runStart || state.chatCreate) return;
|
||
if (state.chatMenu != null || state.openMenu || state.pipelineMenu) return;
|
||
const active = document.activeElement;
|
||
if (active instanceof Element && active.matches("input, textarea, select")) return;
|
||
if (foregroundRefreshTimer) return;
|
||
foregroundRefreshTimer = setTimeout(async () => {
|
||
foregroundRefreshTimer = null;
|
||
if (state.connection.kind !== "connected" || state.loading || detailIsOpen()) return;
|
||
const before = document.querySelector(".list-pane .list-scroll");
|
||
const top = before?.scrollTop ?? 0;
|
||
await loadCurrentView(true);
|
||
const after = document.querySelector(".list-pane .list-scroll");
|
||
if (after && top > 0) after.scrollTop = top;
|
||
}, 300);
|
||
}
|
||
|
||
/** Render whatever a run-state change touched, without re-reading anything. */
|
||
function renderRunState() {
|
||
if (state.view === "runs" || state.view === "pipelines") renderContent();
|
||
views.dialogs.refreshStageAudit?.();
|
||
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;
|
||
if (state.runsLoaded && !state.runs.some((run) => run.id === runId) && Number(frame.schedule_id) > 0 &&
|
||
state.view === "pipelines" && state.pipelineDetail?.id === Number(frame.pipeline_id)) {
|
||
// A newly dispatched timer advanced NextDue. Refresh once on insertion,
|
||
// not on every stage delta, while retaining the no-polling run lifecycle.
|
||
void views.schedules.loadPipelineSchedules(Number(frame.pipeline_id), { force: true });
|
||
}
|
||
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;
|
||
touchView("runs");
|
||
if (state.view === "pipelines") touchView("pipelines");
|
||
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) {
|
||
if (frame.session_export_updated === true) scheduleRunDetailSync(runId);
|
||
runWatch.detailDeltaCount += 1;
|
||
const folded = foldRunEventDetail(detail, frame);
|
||
const detailChanged = folded !== detail;
|
||
if (detailChanged) {
|
||
state.runDetail = folded;
|
||
touchView("runs");
|
||
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;
|
||
// The section stays put when the operator opens another run (sticky, persisted).
|
||
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;
|
||
// The section stays put when the operator opens another pipeline.
|
||
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,
|
||
modal,
|
||
searchHost,
|
||
render,
|
||
renderContent,
|
||
renderHeader,
|
||
touchView,
|
||
focusDetailHeading,
|
||
focusListHeading,
|
||
endpointConfigured,
|
||
setServerUrlDraft,
|
||
pushRoute,
|
||
applyRoute,
|
||
closeDetail,
|
||
openConfiguredEndpoint,
|
||
onReconnectClicked,
|
||
selectPipeline,
|
||
selectRun,
|
||
refreshRunDetail: scheduleRunDetailSync,
|
||
scheduleChanged: async (pipelineId) => {
|
||
const endpoint = state.url;
|
||
const pipelines = await repo.listPipelines();
|
||
if (endpoint !== state.url) return;
|
||
state.pipelines = pipelines;
|
||
state.pipelinesLoaded = true;
|
||
touchView("pipelines");
|
||
if (state.pipelineDetail?.id === pipelineId) {
|
||
const version = state.pipelineDetail.version;
|
||
const detail = await repo.getPipeline(pipelineId, version);
|
||
if (endpoint === state.url && state.pipelineDetail?.id === pipelineId && state.pipelineDetail.version === version) {
|
||
state.pipelineDetail = detail;
|
||
}
|
||
}
|
||
renderContent();
|
||
},
|
||
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),
|
||
schedules: createSchedulesView(runtime),
|
||
};
|
||
runtime.views = views;
|
||
|
||
const {
|
||
renderAttentionBell,
|
||
refreshAttentionBell,
|
||
renderAttentionSheet,
|
||
onRunAlertFrame,
|
||
} = views.attention;
|
||
// The Runs view is created before this destructuring; its toolbar calls this
|
||
// through the runtime object at render time, so attach it once the function is
|
||
// available.
|
||
runtime.renderAttentionBell = renderAttentionBell;
|
||
const { renderSettingsView, refreshServerUrlError } = views.settings;
|
||
const { renderPipelineList, renderPipelineDetail } = views.pipelines;
|
||
const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection } =
|
||
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,
|
||
} = views.chat;
|
||
const {
|
||
openSearch,
|
||
closeSearch,
|
||
renderSearch,
|
||
onSearchInput,
|
||
sendSearchNow,
|
||
} = views.search;
|
||
const { openDecisionSheet } = views.dialogs;
|
||
|
||
// 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.
|
||
/**
|
||
* A question raised by an agent chat is as urgent as a failing run: if the page
|
||
* is not showing that conversation, raise the browser notification the operator
|
||
* already enabled for run alerts. Clicking it opens the chat with the question.
|
||
*/
|
||
function notifyChatQuestion(frame) {
|
||
const form = frame?.form;
|
||
if (!form?.id) return;
|
||
if (typeof globalThis.Notification !== "function") return;
|
||
if (globalThis.isSecureContext !== true || globalThis.Notification.permission !== "granted") return;
|
||
if (state.view === "chat" && state.chatActiveId === frame.session_id) return;
|
||
const session = state.chatSessions.find((row) => row.id === frame.session_id);
|
||
const title = String(session?.title ?? "Chat").trim() || "Chat";
|
||
try {
|
||
const notification = new Notification(`${title} needs your answer`, {
|
||
body: String(form.title ?? "The agent asked a question."),
|
||
tag: `chat-question:${form.id}`,
|
||
});
|
||
notification.onclick = () => {
|
||
window.focus();
|
||
state.view = "chat";
|
||
render();
|
||
openChatSession(frame.session_id);
|
||
};
|
||
} catch {
|
||
// The in-page question card remains available.
|
||
}
|
||
}
|
||
|
||
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) {
|
||
if (
|
||
frame.kind === "form" &&
|
||
frame.form?.kind === "question" &&
|
||
frame.form.resolved !== true &&
|
||
frame.form.cancelled !== true
|
||
) {
|
||
notifyChatQuestion(frame);
|
||
}
|
||
onChatEvent(frame);
|
||
}
|
||
onChatFrame(message);
|
||
});
|
||
|
||
// The shared modal controller owns Escape for every role="dialog" (attention
|
||
// sheet, stage pane, viewers, decision/confirm/Action-failed, chat Rename/Close,
|
||
// template create). Only the non-modal surfaces below are handled here: the Chat
|
||
// actions menu and the Search disclosure, which are not dialogs.
|
||
document.addEventListener("keydown", (event) => {
|
||
if (event.key !== "Escape") 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") return;
|
||
onForegroundActive();
|
||
refreshVisibleListOnForeground();
|
||
});
|
||
window.addEventListener("focus", refreshVisibleListOnForeground);
|
||
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). When
|
||
// nothing is stored, the page's own origin is the supported default proxy: use
|
||
// it instead of leaving a freshly signed-in device on a "Not configured" screen
|
||
// and making the operator find the same URL in Settings.
|
||
if (bootServerUrl) {
|
||
openConfiguredEndpoint({ surfaceError: false });
|
||
} else {
|
||
const sameOrigin = defaultServerUrl();
|
||
if (validateServerUrl(sameOrigin).valid) {
|
||
state.url = sameOrigin;
|
||
openConfiguredEndpoint({ surfaceError: false });
|
||
}
|
||
}
|