// Spike web UI: the page shell. Boot, shared state, the one reused client and // repository, connection/banner wiring, navigation + URL routes, render dispatch // and the top bar. 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, bannerState, foregroundAction, protocolMismatch, serverBuildLabel, stateBadge, } from "./connection.js"; import { foldRunEvent, foldRunEventDetail, isTerminalRunStatus, runDetailNeedsFullSync, } from "./runEvents.js"; import { readServerUrl, readWorkspace, writeServerUrl } from "./settings.js"; import { layoutGraph } from "./graph.js"; import { DEFAULT_ROUTE, parseRoute, serializeRoute } from "./routes.js"; import { EMPTY_PIPELINE_FILTERS } from "./pipelines.js"; import { DEFAULT_RUN_SORT, metaText, formatDuration, defaultRunFilters, } from "./runs.js"; import { runDurationText, runTimeline, clampVisitIndex } 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 { CHAT_TAB_TITLE } from "./chat.js"; import { h } from "./dom.js"; import { describeError, isExecuting } from "./format.js"; import { createAttentionView, loadAttentionDismissed, loadNotifyAsked, } from "./views/attention.js"; import { createSettingsView } from "./views/settings.js"; import { createPipelinesView } from "./views/pipelines.js"; import { createTemplatesView } from "./views/templates.js"; import { createRunsView } from "./views/runs.js"; import { createDialogsView } from "./views/dialogs.js"; import { createRunDetailView } from "./views/runDetail.js"; import { createChatView, readChatScrollStore, readChatDraftStore, readChatOverridesStore, readChatSeenStore, readEphemeralChatIds, } from "./views/chat.js"; import { createSearchView } from "./views/search.js"; function defaultServerUrl() { if (typeof location === "undefined" || !location.host) return ""; const scheme = location.protocol === "https:" ? "wss" : "ws"; return `${scheme}://${location.host}/connect`; } const client = new PipelinesClient(); const repo = new PipelinesRepository(client); // Read the persisted settings once: the server URL falls back to the page's own // proxy endpoint when unset, and the workspace starts blank when unset. Both the // configured value and the draft start from storage. const initialWorkspace = readWorkspace(localStorage); const state = { view: "pipelines", url: readServerUrl(localStorage) || defaultServerUrl(), // The server URL's own validation message (Android's `urlError`), shown as the // Settings field's supporting text and cleared as soon as the field is edited. urlError: "", // The workspace the operator configured (L1), the analogue of SettingsRepository's // `workspace` preference. `workspaceDraft` is the field's live value; Save copies // it into `workspace` and localStorage. Both start from the persisted value. workspace: initialWorkspace, workspaceDraft: initialWorkspace, connection: client.state, // The live run-stream state (R10), independent of any screen: Offline until a // watch is established, Connecting while subscribing/re-subscribing after a // drop, Live once an ack, the first pushed frame or a successful watch read // proves pushes are arriving. The runs list and the run detail render it as the // LiveBadge.kt words. runStream: RunStream.Offline, // The last `pong` reply is remembered so the banner can name a stale server // build and warn about a protocol mismatch (T5) without re-pinging. serverBuild: null, serverProtocol: null, // The `pong` reply's server time (L1), shown in the Settings connection card. serverTime: null, pipelines: [], runs: [], usage: null, pipelineDetail: null, runDetail: null, selectedPipelineId: null, selectedRunId: null, // The version the selected pipeline detail was requested at (0 = latest), and // the stage whose definition pane is open. Both are part of the URL route. pipelineRequestedVersion: 0, pipelineGraphSelection: null, // The URL route model (L6): the route currently rendered, the one pending until // the first successful connection opens it, whether that first connection has // happened, and a re-entrancy guard for popstate-driven application. route: { ...DEFAULT_ROUTE }, pendingRoute: null, routeFirstConnect: false, routeApplying: false, popPending: false, // Pipelines view: client-side filter/sort/detail-tab state. The run history is // fetched alongside the pipelines so the list can show each pipeline's last // run; runsLoaded tells a genuinely empty history apart from one not in hand. pipelineFilters: { ...EMPTY_PIPELINE_FILTERS }, pipelineSort: "server_order", pipelineMenu: null, pipelineTab: "summary", // The mounted workflow graph (P6) and whether its panel is expanded. The // handle is dropped on every re-render so its listeners can never leak. pipelineGraph: null, pipelineGraphExpanded: false, // The mounted run-mode graph (R5) on the run detail's Graph tab. Dropped on // every re-render and on a run change, so its wheel/pointer/resize listeners // and its elapsed timer can never leak. runGraph: null, versionsExpanded: false, pipelinesLoaded: false, runsLoaded: false, templates: [], templateLoading: false, // key -> graph|null: the parsed definition, cached once per template key. A // failed/absent validate stores null so the card/detail say "unavailable". templateGraphs: new Map(), selectedTemplateKey: null, templateTab: "summary", // The create-from-template dialog (P5): whether it is open, the name being // typed, whether a validate+submit is in flight, the server's refusal text and // the created pipeline's name (null until a success, which is also what makes // Cancel read Close and the field lock). The dialog validates the template's // source first, then submits it create-only; nothing runs. templateCreateOpen: false, templateCreateName: "", templateCreateSending: false, templateCreateError: "", templateCreateCreated: null, loading: false, error: "", runFilters: defaultRunFilters(), runSort: DEFAULT_RUN_SORT, openMenu: null, // Run detail: the selected tab (Summary by default) and the per-run // expand/collapse choices for the input/output field sections and the summary // artifacts section. The stage pane is the timeline's per-visit panel; its // section expansion is reseeded each time a pane is opened. runTab: "summary", runSections: new Set(), runStagePane: null, runStageSections: new Set(), // The attention / "Needs you" surface (R15). `attentionDismissed` is the set // of `{runId}:{kind}` identities the operator has explicitly dealt with, loaded // once at boot from localStorage. `attentionSheetOpen` drives the sheet and // `attentionSnapshot` holds the entries captured when it opened, so Clear all // only ever removes identities the operator actually saw. attentionDismissed: new Set(), attentionSheetOpen: false, attentionSnapshot: null, // Notifications (L5): whether the operator has already been asked, loaded once // at boot from localStorage. The browser owns the permission itself; this flag // only changes the honest wording in Settings and is never a claim of consent. notifyAsked: false, // Omni-search (S1/S2): the field/panel state, kept beside the view it never // changes, plus the pure debounce/stale-token sequencer. Opening or closing the // search leaves state.view, the selection and the loaded data untouched. searchOpen: false, searchQuery: "", searchKind: DEFAULT_SEARCH_KIND, searchSort: DEFAULT_SEARCH_SORT, searchResults: [], searchLoading: false, searchError: "", searchLoaded: false, searchFocusPending: false, searchSequencer: new SearchSequencer(), // Run-level operator actions (R11–R14): the decision the open sheet renders // (retained across a refused send so the server's own reason can be shown even // after a refresh), the sheet's draft/sending/error, the action awaiting a // confirm dialog, the in-progress rename title (null when not editing) and the // one shared Action-failed dialog. runDecision: null, decisionOpen: false, decisionDraft: new DecisionDraft(), decisionSending: false, decisionError: "", confirmKind: null, renameValue: null, renameBusy: false, actionError: "", // Chat (C1/C3/C4/C7/C14): the server's operator-session list and its load // state, the operator's narrowing, one open thread per session id and the // active one. The transcript is untrusted model output, so every server string // is set with textContent and the markdown renderer builds DOM nodes, never // innerHTML. chatSessions: [], // The verification chats this page itself created (C2's automation flag). The // server deliberately never lists them; the page keeps its own in-memory row so // the creator can keep working with the chat it just opened. The set is // memory-only, so a reload cannot turn one into a permanent list entry. // Verification chats this tab created (never listed by the server). Kept in // sessionStorage so a reload of this tab still shows the chat it made, while a // different tab or a later visit never sees it. chatEphemeralIds: new Set(readEphemeralChatIds()), chatLoading: false, chatLoaded: false, chatError: "", chatQuery: "", chatThreads: new Map(), chatActiveId: null, chatPlaced: null, chatFollowing: true, chatReasoning: new Set(), // The tool-call panel (C6): the turns whose panel is open and the individual // rows the operator has expanded, both keyed the same way as chatReasoning so // a re-render keeps them. chatToolPanels: new Set(), chatToolRows: new Set(), chatScroll: readChatScrollStore(), // The scroll restore across a prepended older page, the position captured // from the live transcript just before a re-render (so a dialog, a refresh or // the loading frame of a paging fetch never loses the operator's place), and // the debounced save. chatAnchor: null, chatPending: null, chatScrollTimer: null, // True only while the operator's own gesture (wheel/pointer/touch) is the // reason the transcript moved, so a programmatic placement or follow can never // be mistaken for the operator leaving the bottom. chatUserIntent: false, // The session awaiting the Close chat? confirm, and the shared Action-failed // report for a refused close/reopen. chatClose: null, chatBusy: false, // C13: this device's local titles/hidden ids and the seen watermarks, both // persisted as one JSON value each. `chatMenu` is the row whose Chat actions // menu is open, `chatRename` the session whose Rename chat dialog is open, and // `chatSnackbar` the one in-flight hide report (`{id, sessionId}`) with the // timer that auto-dismisses it. A new hide replaces the previous report. chatOverrides: readChatOverridesStore(), chatSeen: readChatSeenStore(), chatMenu: null, chatRename: null, chatSnackbar: null, chatSnackbarSeq: 0, chatSnackbarTimer: null, // C5: the session ids this connection currently has subscribed to their shared // live stream. The server detaches a subscription when the connection closes // (there is no chat_unsubscribe), so this is cleared on every socket drop and // re-established for the open chat on reconnect. A refused subscription simply // never joins the set, so the badge reads "not live" honestly. chatSubscriptions: new Set(), // C2: the create flow. `chatCreate` is the ChatCreateState analogue (null until // the New chat entry point is used); the directory reply is cached so cancelling // and reopening does not re-ask, and a failed load keeps its own reason. chatDirectories: [], chatDirectoriesLoading: false, chatDirectoriesLoaded: false, chatDirectoriesError: "", chatCreate: null, }; // The app-wide run-event watch (R10), owned by the connection rather than any // screen. `workspace` is the blank string while a watch is established (the // server-wide "any" scope) and null when nothing is watched; `subscriptionId` is // the send-only subscribe frame's id so an ack or refusal can be attributed. // `generation` is bumped on every (re)subscribe and every drop, so an in-flight // read from a superseded watch can neither write its result nor clear the badge. const runWatch = { workspace: null, subscriptionId: null, generation: 0, runsResyncJob: null, runsResyncQueued: false, detailSyncJob: null, detailSyncRequestedRunId: null, detailDeltaCount: 0, }; // The coalesced resync retry bound, mirroring AppViewModel: at most three // retries (four attempts) at 500 ms x attempt, then the badge drops to // "reconnecting" until a later push or read confirms the stream again. const RUN_SYNC_RETRY_LIMIT = 3; const RUN_SYNC_RETRY_BASE_MS = 500; // The run-notification ledger (L5). It is seeded from the authoritative run list // and from the subscribe snapshot, then observes pushed `run_event` frames; it // never feeds the runs list (that is R10's fold above). const runAlerts = createAlertLedger(); // One shared live clock for the runs list: it ticks only while a shown run is // executing, and each running row reads its elapsed from it rather than starting // a timer of its own. Elapsed is derived from the server's start timestamp, so // it stays correct after a reconnect; a finished history never ticks. let listClock = null; let listNow = Date.now(); // The run detail's own live clock: it ticks only while the shown run is // executing, updating just the Duration row in place (never a full re-render, so // an open stage pane is not torn down), exactly as the runs list does. let detailClock = null; let detailNow = Date.now(); /** Await one delay; used only by the bounded resync retry backoff. */ function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } // --------------------------------------------------------------------------- // Rendering // --------------------------------------------------------------------------- const header = h("header", { class: "topbar" }); // The full-width omni-search panel sits directly under the top bar (and so under // the search control that lives in it), above the connection banner so it can // never be mistaken for a status strip. const searchHost = h("div", { id: "searchHost", class: "search-host" }); // The persistent connection banner sits in normal document flow directly under // the header (never fixed/overlaying), so it can never cover the content. const connBanner = h("div", { id: "connBanner", class: "conn-banner", hidden: true }); const content = h("main", { id: "content" }); // 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" }); document.body.append(header, searchHost, connBanner, content, attentionLayer); /** Whether the URL field currently holds a usable endpoint for Reconnect. */ function endpointConfigured() { return validateServerUrl(state.url).valid; } /** * The one server-URL draft (Android's `serverUrlDraft`). Both the header field and * the Settings `Server URL` field edit this same value and are mirrored in place * without a re-render, so the two can never show different endpoints while typing * (and neither loses focus). Editing also clears the field's own error, exactly as * AppViewModel.updateServerUrlDraft does. */ function setServerUrlDraft(value, sourceId) { state.url = value; clearServerUrlError(); for (const id of ["url", "settingsServerUrl"]) { if (id === sourceId) continue; const other = document.getElementById(id); if (other && other.value !== value) other.value = value; } // The Settings field mirrors this value even when the edit came from the header, // so its own supporting text, error tint and aria-invalid must be refreshed from // the same draft state too: a corrected URL can never leave the field announced // as invalid (or keep the stale "That is not a valid URL." message) just because // the correction happened in the header field. if (document.getElementById("settingsServerUrl")) views.settings.refreshServerUrlError(); } /** * Clear the server-URL validation error, wherever it was surfaced: the Settings * field's own error always, and — when the invalid Connect came from another view * — 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(); } } } function renderHeader() { const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() }); const controls = [ ...searchHeaderControls(), h("input", { id: "url", type: "text", placeholder: "ws://HOST:PORT/connect", value: state.url, spellcheck: "false", oninput: (e) => { setServerUrlDraft(e.target.value, "url"); }, }), ]; // The manual reconnect control (T3) sits beside the URL field and is offered // whenever the connection state asks for one. if (info.action) { controls.push( h("button", { id: "reconnectBtn", class: "ghost", text: info.action, onclick: onReconnectClicked }), ); } controls.push( h("button", { id: "connectBtn", text: state.connection.kind === "connected" ? "Disconnect" : "Connect", onclick: onConnectClicked, }), h("span", { class: "state", id: "stateBadge" }, connectionLabel()), ); header.replaceChildren( h( "div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" }), renderAttentionBell(), ), h("div", { class: "connbar" }, ...controls), ); // Autofocus the field only for the render that opened it, so a later // connection-state re-render never steals the operator's focus. if (state.searchOpen && state.searchFocusPending) { document.getElementById("searchInput")?.focus(); state.searchFocusPending = false; } } /** * The top bar's search control: the Search button while closed, and the query * field with its Close control while open. The field's value is always read back * from `state.searchQuery`, so a re-render can never desync the two. */ function searchHeaderControls() { if (!state.searchOpen) { return [ h("button", { id: "searchToggle", class: "ghost search-toggle", type: "button", title: "Search", text: "Search", onclick: openSearch, }), ]; } return [ h("input", { id: "searchInput", class: "search-input", type: "text", placeholder: "Search pipelines, runs and artifacts", value: state.searchQuery, spellcheck: "false", autocomplete: "off", "aria-label": "Search", oninput: (event) => onSearchInput(event.target.value), onkeydown: (event) => { if (event.key === "Enter") { event.preventDefault(); sendSearchNow(); } }, }), h("button", { id: "searchClose", class: "ghost search-close", type: "button", text: "Close search", onclick: closeSearch, }), ]; } /** * The persistent connection banner. Its copy/tone come from the pure * `bannerState`, and it also carries the last server build and a protocol * mismatch warning (T5). Every server string is set with textContent. */ function renderBanner() { const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() }); connBanner.className = `conn-banner conn-${info.tone}`; connBanner.hidden = false; const nodes = [ h("span", { class: "conn-banner-dot", "aria-hidden": "true" }), h("span", { class: "conn-banner-text", text: info.text }), ]; const build = serverBuildLabel(state.serverBuild); if (build) nodes.push(h("span", { class: "conn-build", text: build })); const warning = protocolMismatch(PROTOCOL_VERSION, state.serverProtocol); if (warning) nodes.push(h("span", { class: "conn-warning", text: warning })); connBanner.replaceChildren(...nodes); } function connectionLabel() { const info = stateBadge(state.connection); return h("span", { class: `dot ${info.tone}`, text: info.text }); } /** * The run-event watch for this connected epoch (R10) is established by * `startRunWatch`; it also seeds L5's notification ledger (the authoritative * list plus the subscribe snapshot) so a reconnect gap never notifies. */ function render() { renderHeader(); renderBanner(); renderSearch(); renderContent(); renderAttentionSheet(); } function renderContent() { // The graph owns wheel/pointer/resize listeners; drop the previous mount // before rebuilding the DOM so a re-render, tab switch or view switch never // leaves an observer or listener behind. if (state.pipelineGraph) { state.pipelineGraph.unmount(); state.pipelineGraph = null; } if (state.runGraph) { state.runGraph.unmount(); state.runGraph = null; } const nodes = []; if (state.error) { nodes.push(h("div", { class: "banner error" }, h("strong", { text: "Error: " }), state.error)); } nodes.push( h( "nav", { class: "tabs" }, // A destination reached by a deep link has not loaded this list yet: say // "Pipelines" rather than a false count of 0. tabButton("pipelines", state.pipelinesLoaded ? `Pipelines (${state.pipelines.length})` : "Pipelines"), tabButton("runs", `Runs (${state.runs.length})`), tabButton("templates", "Templates"), tabButton("chat", CHAT_TAB_TITLE), tabButton("settings", "Settings"), h("span", { class: "spacer" }), h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }), ), ); // Settings is a single-pane destination (not the list/detail split): the // app's own settings page is one scrolled column. if (state.view === "settings") { nodes.push(renderSettingsView()); } else { const split = h("div", { class: "split" }); if (state.view === "pipelines") { split.append(renderPipelineList(), renderPipelineDetail()); } else if (state.view === "runs") { split.append(renderRunList(), renderRunDetail()); } else if (state.view === "chat") { // While the create flow is open it owns the detail pane; the session list // stays visible beside it, exactly as the app's two-pane chat stack does. split.append(renderChatList(), state.chatCreate ? renderChatCreate() : renderChatConversation()); } else { split.append(renderTemplateGallery(), renderTemplateDetail()); } nodes.push(split); } // Capture the live transcript's position before it is replaced, so the very // next render can put the operator back exactly where they were (a dialog, a // refresh or a paging frame must not move them). captureChatPosition(); content.replaceChildren(...nodes); if (state.view === "chat") { afterChatRender(); stopListClock(); stopDetailClock(); refreshChatClock(); return; } stopChatClock(); if (state.view === "runs") { refreshListClock(); refreshDetailClock(); } else { stopListClock(); stopDetailClock(); } } function tabButton(view, label) { return h("button", { class: `tab${state.view === view ? " active" : ""}`, text: label, onclick: () => { // A top-level tab is a real destination: it updates the URL and lets one // route application set the view, selection and any list load. Pushing // first means a load failure can still replace the URL honestly. const route = { kind: view }; pushRoute(route); applyRoute(route); }, }); } // --------------------------------------------------------------------------- // Actions // --------------------------------------------------------------------------- function setError(err) { state.error = err instanceof Error ? err.message : String(err); state.loading = false; renderContent(); } /** * Validate the URL field, remember it and open the socket. Shared by Connect, * the manual Reconnect control and the foreground recovery so all three take the * same validate → persist → repo.connect path. `repo.connect` resets the * attempt/backoff inside client.js, cancelling a pending retry delay. * * An invalid draft is reported as the Settings field's own error (Android's * `urlError`) and cleared on the next edit; it is never left as a page-level * banner. `surfaceError` is false for the background (foreground-recovery) * caller so a stale, invalid URL field cannot spray an error into the UI on every * visibilitychange/online event. */ function openConfiguredEndpoint({ surfaceError = true } = {}) { const validated = validateServerUrl(state.url); if (!validated.valid) { if (surfaceError) { state.urlError = validated.message; // On another view the field is not rendered, so the page-level error is the // only way to say why nothing happened; on Settings it belongs under the // field. if (state.view === "settings") { refreshServerUrlError(); } else { state.error = validated.message; renderContent(); } } return; } state.error = ""; state.urlError = ""; writeServerUrl(localStorage, state.url); repo.connect(validated); } function onConnectClicked() { if (state.connection.kind === "connected") { repo.disconnect(); return; } openConfiguredEndpoint(); // The `state` listener kicks off the initial load once connected. } /** * The manual reconnect control (T3): re-open the same validated endpoint now. * `repo.connect` (client.connect) resets the attempt/backoff, so a pending * retry delay is cancelled and the socket is reopened immediately. */ function onReconnectClicked() { openConfiguredEndpoint(); } /** * Return-to-foreground recovery (T4), the page's counterpart of * ForegroundReconnector: called when the tab becomes visible again or the * browser comes back online. Idle is the client's own deliberate-disconnect * state and is left alone; Connecting and Disconnected are driven back to the * socket at once, cancelling the pending backoff inside client.connect. A * Connected socket is trusted because the browser's own online/visibility event * is the liveness signal available to the page (it has no in-page positive ping * probe like ForegroundReconnector.confirm()); that deviation is recorded in * web/PARITY.md. Idempotent: repeated events just re-open the same endpoint. */ function onForegroundActive() { if (foregroundAction(state.connection, true) !== ForegroundAction.Reconnect) return; openConfiguredEndpoint({ surfaceError: false }); } async function onConnected() { // Establish the run-event watch immediately once the socket is up (R10): the // unsubscribe/subscribe pair is sent before anything else is read, and its // authoritative `list_runs` resync is the one the view then reuses, so a // connection never stacks two initial history reads. The watch is // send-only/best-effort; a failure leaves the badge "reconnecting" and the // ordinary view load proceeds. const watched = startRunWatch(); let reply; try { reply = await repo.ping(); } catch (err) { setError(err); return; } // Remember the server's build/protocol so the banner can name a stale server // and warn about a protocol mismatch (T5); the ping is the only source. state.serverProtocol = reply?.protocol ?? null; state.serverBuild = reply?.build ?? null; // The pong carries the server's own time (internal/protocol/message.go `Time`), // shown in the Settings connection card. state.serverTime = reply?.time ?? null; // Update the banner at once; the content render that shows the build/time in // the Settings card is the one `loadCurrentView` already performs (Settings is // local, so that path is a single render and nothing is fetched twice). renderBanner(); // A URL opened before the socket was up is the pending destination: the first // successful connection loads its list and then its detail/stage. Later // reconnects keep the ordinary current-view refresh and never replay a link. if (!state.routeFirstConnect) { state.routeFirstConnect = true; const route = state.pendingRoute ?? state.route ?? DEFAULT_ROUTE; state.pendingRoute = null; // The watch is connection-scoped, not route-scoped: it was started above (its // subscribe is already sent) and its own resync seeds the run list, so opening // the pending route must not wait for it here. watched.catch(() => {}); await applyRoute(route); return; } // Seed from the authoritative list first, then watch: the subscribe snapshot // and its ack are treated as seeds, so a reconnect gap never notifies. const runsFresh = await watched; await loadCurrentView(false, { runsFresh }); // A reconnect after a network drop must also re-hydrate an open detail: the // route (and its URL) can survive a drop, but a detail that was never loaded — // or was cleared while disconnected — has to be fetched again, otherwise the // URL and the rendered view disagree. Only the URL-bearing detail routes do // this; the list destinations were just refreshed above. const route = state.route; if ( route && (route.kind === "run" || route.kind === "runStage" || route.kind === "pipeline" || route.kind === "pipelineStage") ) { await applyRoute(route); } } // --------------------------------------------------------------------------- // URL routes (L6) // --------------------------------------------------------------------------- /** The view a route renders in: details belong to their list's destination. */ function viewForRoute(route) { switch (route?.kind) { case "pipeline": case "pipelineStage": return "pipelines"; case "run": case "runStage": return "runs"; case "template": return "templates"; case "runs": case "chat": case "settings": case "templates": return route.kind; default: return "pipelines"; } } /** Record a user move in history. Only a real URL change pushes an entry. */ function pushRoute(route) { const url = serializeRoute(route); const current = `${location.pathname}${location.search}`; if (url !== current) { try { history.pushState(null, "", url); } catch { // A non-HTTP location (file://) may refuse history; local state still moves. } } state.route = route; // Only an untouched boot deep link is replayed after connecting. A move the // operator made while still disconnected (a tab, a selection, Back/Forward) is // now the destination the URL shows, so the stale boot link must not win. state.pendingRoute = null; } /** Correct the current entry in place (a missing entity, a consumed action). */ function replaceRoute(route) { const url = serializeRoute(route); const current = `${location.pathname}${location.search}`; if (url !== current) { try { history.replaceState(null, "", url); } catch { // See pushRoute. } } state.route = route; state.pendingRoute = null; } /** * Apply a route to the local view and, when connected, load exactly what it * needs: the destination list first on a boot deep link, then the requested * detail/stage. Same-id data already in hand is not refetched, so Back from a * stage route only closes the pane. Total: every failure ends in an honest list * fallback rather than a throw. */ async function applyRoute(route) { const r = route && typeof route === "object" ? route : { ...DEFAULT_ROUTE }; state.routeApplying = true; const connected = () => state.connection.kind === "connected"; try { state.route = r; // Applying a route is itself a navigation decision (popstate, a push, or the // boot link): the pending boot link is never allowed to override it later. state.pendingRoute = null; state.error = ""; state.loading = false; state.view = viewForRoute(r); // R10 removed the 1 Hz run poll: a run detail is advanced by pushed // `run_event` frames and the shared clocks, so a destination change has no // poll to stop. if (r.kind === "pipelines") { // A default destination reached from an unknown or malformed path (a boot // deep link or a Back entry) corrects the address bar so the URL and the // rendered list agree; on the canonical /pipelines this is a no-op. if (`${location.pathname}${location.search}` !== "/pipelines") { replaceRoute({ kind: "pipelines" }); } state.selectedPipelineId = null; resetPipelineDetailState(); renderContent(); // Mirror the old tab handler: an unfetched destination while disconnected // still says `Connect to the server first.` rather than showing a silent // empty list. Once connected this is the list load the route needs. if (!state.pipelines.length) await loadCurrentView(); return; } if (r.kind === "runs") { state.selectedRunId = null; state.runDetail = null; state.runStagePane = null; state.runStageSections = new Set(); state.decisionOpen = false; state.runDecision = null; renderContent(); if (!state.runs.length) await loadCurrentView(); return; } if (r.kind === "pipeline" || r.kind === "pipelineStage") { const version = Number.isSafeInteger(r.version) ? r.version : 0; const same = state.selectedPipelineId === r.id && state.pipelineDetail != null && state.pipelineRequestedVersion === version; state.view = "pipelines"; if (same) { if (r.kind === "pipelineStage") { if (!pipelineHasStage(state.pipelineDetail, r.stageKey)) { state.pipelineGraphSelection = null; state.pipelineTab = "graph"; replaceRoute({ kind: "pipeline", id: r.id, version }); renderContent(); return; } state.pipelineTab = "graph"; state.pipelineGraphSelection = r.stageKey; } else { // The detail route itself does not name a section; keep the tab and // only close the stage pane. state.pipelineGraphSelection = null; } renderContent(); return; } state.selectedPipelineId = r.id; state.pipelineRequestedVersion = version; state.pipelineDetail = null; state.pipelineTab = r.kind === "pipelineStage" ? "graph" : "summary"; state.pipelineGraphSelection = r.kind === "pipelineStage" ? r.stageKey : null; renderContent(); if (!connected()) return; if (!state.pipelinesLoaded) await loadCurrentView(); await selectPipeline({ id: r.id, version }, { updateRoute: false }); if (r.kind === "pipelineStage" && state.view === "pipelines" && state.pipelineDetail) { if (!pipelineHasStage(state.pipelineDetail, r.stageKey)) { // A path naming a stage the loaded graph does not declare is accepted by // the (data-blind) parser but cannot open a pane: mirror the missing-entity // fallbacks and replace the URL with the pipeline itself. state.pipelineGraphSelection = null; state.pipelineTab = "graph"; replaceRoute({ kind: "pipeline", id: r.id, version }); renderContent(); return; } state.pipelineTab = "graph"; state.pipelineGraphSelection = r.stageKey; renderContent(); } return; } if (r.kind === "run" || r.kind === "runStage") { state.view = "runs"; const same = state.selectedRunId === r.id && state.runDetail != null; if (!same) { state.selectedRunId = r.id; resetRunDetailState(); renderContent(); if (!connected()) return; if (!state.runsLoaded) await loadCurrentView(); await selectRun(r.id, { updateRoute: false }); } if (!connected() || !state.runDetail || state.runDetail.id !== r.id) return; if (r.kind === "runStage") { // No ?visit means the stage's most recent visit, exactly as the graph's // own node click opens it; the URL stays without a visit. A valid but // out-of-range index is clamped to the stage's last visit and the entry // corrected, so the address bar and the pane agree (renderStagePane // already clamps, which is why the two must not diverge). const visits = runTimeline(state.runDetail.steps ?? []).visitsByStage.get(r.stageKey) ?? []; // A key that is neither visited nor a node of the loaded run graph cannot // open a pane. Mirror the pipeline-stage fallback: show the run itself and // correct the URL rather than leaving an empty pane under a stage path. if (!visits.length && !layoutGraph(state.runDetail.graph).nodes.some((node) => node.key === r.stageKey)) { state.runStagePane = null; state.runStageSections = new Set(); replaceRoute({ kind: "run", id: r.id }); renderContent(); return; } const wanted = r.visit == null ? Math.max(0, visits.length - 1) : r.visit; const visit = clampVisitIndex(wanted, visits.length); state.runStagePane = { stageKey: r.stageKey, visitIndex: visit }; state.runStageSections = new Set(); renderContent(); if (r.visit != null && visit !== r.visit) { replaceRoute({ kind: "runStage", id: r.id, stageKey: r.stageKey, visit }); } } else { if (state.runStagePane) { state.runStagePane = null; state.runStageSections = new Set(); renderContent(); } consumeRunAction(r); } return; } if (r.kind === "templates") { // Entering the gallery leaves any template detail (and a create dialog // opened for it) behind, exactly as the Settings card did before routing. resetTemplateSelection(); renderContent(); if (!state.templates.length) await loadCurrentView(); return; } if (r.kind === "template") { // A route that names a different template reseeds the detail: a create // dialog and its typed name belong to the template they were opened on. // A same-route re-apply keeps them, so a push or replace is not a reset. if (state.selectedTemplateKey !== r.key) resetTemplateCreateState(); state.selectedTemplateKey = r.key; renderContent(); if (!state.templates.length) await loadCurrentView(); return; } if (r.kind === "chat") { renderContent(); if (!state.chatLoaded) await loadCurrentView(); return; } // Settings is local; the fallback covers any route kind a caller invents. state.view = "settings"; state.error = ""; renderContent(); } finally { state.routeApplying = false; // A Back/Forward that arrived while a load was in flight still wins: apply // the location the browser actually shows now, once this pass is done. if (state.popPending) { state.popPending = false; applyRoute(parseRoute(location.pathname, location.search)); } } } /** * A run URL's one-shot `?action=decide` (the notification analogue): after the * run loads, open the existing decision sheet only when the run is genuinely * waiting, then replace the entry with the action-free /runs/:id so a refresh * does not reopen it. Never invents a decision. */ function consumeRunAction(route) { if (!route?.action) return; const action = route.action; replaceRoute({ kind: "run", id: route.id }); if (action !== "decide") return; const decision = pendingDecision(state.runDetail); if (decision) openDecisionSheet(decision); } async function loadCurrentView(force = false, { runsFresh = false } = {}) { // Settings is local: it has no server-backed list to (re)load, so switching to // or refreshing it must never raise the "connect first" error. if (state.view === "settings") { renderContent(); return; } if (state.connection.kind !== "connected") { state.error = "Connect to the server first."; renderContent(); return; } if (state.view === "templates") { await loadTemplates(force); return; } if (state.view === "chat") { await loadChatSessions(force); return; } state.loading = true; state.error = ""; renderContent(); try { if (state.view === "pipelines") { state.pipelines = await repo.listPipelines(); state.pipelinesLoaded = true; // The last-run line joins list_runs onto the pipelines, so the history is // fetched alongside them; runsLoaded distinguishes a genuinely empty // history from one that has not arrived yet. On connect that history has // just been read by the run watch's own resync, so it is not read twice. if (!runsFresh) { const { runs, usage } = await repo.listRuns(); state.runs = runs; runAlerts.seed(runs); if (usage) state.usage = usage; state.runsLoaded = true; } } else if (!runsFresh) { const { runs, usage } = await repo.listRuns(); state.runs = runs; runAlerts.seed(runs); state.usage = usage; state.runsLoaded = true; } // The nav badge reads the pipeline count, and the Pipelines destination is // one click away: load that list once when it has not been seen, whether the // runs came from the watch's resync or a direct read. if (!state.pipelinesLoaded) { try { state.pipelines = await repo.listPipelines(); state.pipelinesLoaded = true; } catch { // The Pipelines destination will report its own load failure. } } state.loading = false; renderContent(); // The run list the attention surface derives from has just (re)loaded, so // bring the bell's badge up to date. refreshAttentionBell(); // Keep the current selection fresh after a refresh. if (force && state.view === "runs" && state.selectedRunId) { await selectRun(state.selectedRunId, { silent: true }); } } catch (err) { setError(err); } } // --------------------------------------------------------------------------- // The live run stream (R10) // --------------------------------------------------------------------------- /** Render whatever a run-state change touched, without re-reading anything. */ function renderRunState() { if (state.view === "runs" || state.view === "pipelines") renderContent(); refreshAttentionBell(); } /** Record the explicit stream state and repaint the badge when it changed. */ function setRunStream(next) { if (state.runStream === next) return; state.runStream = next; renderRunState(); } /** * Drop the watch bookkeeping and invalidate any in-flight read. Called on every * socket drop and before a new subscribe, so a superseded read can neither write * its result over newer state nor confirm a stream that is gone. The stream's own * state is set by the caller (streamDown / startRunWatch). */ function clearRunWatch() { runWatch.workspace = null; runWatch.subscriptionId = null; runWatch.generation += 1; runWatch.runsResyncQueued = false; } /** Nothing is watched: reflect the connection's own state in the live badge. */ function streamDown() { clearRunWatch(); state.runStream = state.connection.kind === "connecting" || state.connection.kind === "disconnected" ? RunStream.Connecting : RunStream.Offline; } /** A subscription ack, a push, or a successful watch read proves the stream is live. */ function confirmStreamLive() { if (runWatch.workspace === null) return; setRunStream(RunStream.Live); } /** A push-driven read failed: stop claiming live until something confirms it again. */ function markStreamDegraded() { if (runWatch.workspace !== null) setRunStream(RunStream.Connecting); } /** * Establish the one watch over every workspace the client displays (the blank * scope, which the server treats as "any"): the runs list is server-wide, so the * client asks for the runs it shows rather than the one workspace the operator * configured. It best-effort drops the previous watch first (the server caps * subscriptions per connection), marks the watch before sending so a push that * races the send is still attributed to it, then takes one authoritative resync * of the watched state. Resolves true when that resync succeeded, so the caller * knows the runs list is already fresh. */ async function startRunWatch() { const generation = ++runWatch.generation; runWatch.workspace = null; runWatch.subscriptionId = null; state.runStream = RunStream.Connecting; try { repo.unsubscribeRuns(); } catch { // The drop failed; the new subscribe is still attempted, but the badge stays // "reconnecting" until an ack, push or successful read confirms the new watch. state.runStream = RunStream.Connecting; } if (generation !== runWatch.generation || state.connection.kind !== "connected") return false; runWatch.workspace = ""; // L5: seed from the list already in hand, and treat the subscribe snapshot as // seeds too (it can arrive before any ack). The authoritative resync below // then seeds again, so a reconnect gap never notifies late. runAlerts.seed(state.runs); runAlerts.beginSeed(); try { runWatch.subscriptionId = repo.subscribeRuns("", []); } catch { runAlerts.endSeed(); clearRunWatch(); setRunStream(RunStream.Offline); return false; } let resynced = false; try { resynced = await scheduleRunsResync(); } finally { runAlerts.endSeed(); } if (generation !== runWatch.generation) return false; if (state.runDetail?.id != null) scheduleRunDetailSync(state.runDetail.id); return resynced; } /** * Re-reads the runs list once for a burst of frames the list could not fold (a * created run whose summary is not in the compact delta, or a terminal * transition that changes the usage aggregate) and once after every * (re)subscribe. Coalesced — at most one in flight with one queued follow-up — * and it loops while a frame arrived, so no push is ever dropped. A failed read * stops claiming live and is retried with a bounded backoff before giving up. * Resolves true when the last read succeeded. */ function scheduleRunsResync() { if (runWatch.runsResyncJob) { runWatch.runsResyncQueued = true; return runWatch.runsResyncJob; } const job = (async () => { let attempt = 0; let ok = true; for (;;) { runWatch.runsResyncQueued = false; const generation = runWatch.generation; try { const { runs, usage } = await repo.listRuns(); if (generation !== runWatch.generation) { // The watch was re-established (or dropped) while this read was in // flight; its result is superseded, so re-read under the new watch // instead of writing stale state or clearing the badge. runWatch.runsResyncQueued = true; continue; } state.runs = runs; runAlerts.seed(runs); if (usage) state.usage = usage; state.runsLoaded = true; attempt = 0; ok = true; confirmStreamLive(); renderRunState(); } catch { if (generation !== runWatch.generation) { runWatch.runsResyncQueued = true; continue; } markStreamDegraded(); attempt += 1; if (attempt > RUN_SYNC_RETRY_LIMIT) { ok = false; break; } await delay(RUN_SYNC_RETRY_BASE_MS * attempt); if (generation !== runWatch.generation) { runWatch.runsResyncQueued = true; continue; } runWatch.runsResyncQueued = true; ok = false; } if (!runWatch.runsResyncQueued) break; } return ok; })(); runWatch.runsResyncJob = job; job.finally(() => { if (runWatch.runsResyncJob === job) runWatch.runsResyncJob = null; }); return job; } /** * Fetches the full run detail once for a burst of settled-step/terminal pushes, * so the artifacts and output the compact delta omits appear without a timer. A * response is dropped and retried when a newer frame landed while the fetch was * in flight, so the fetch can never regress the fold. The queued request is keyed * by run id, so opening another run mid-fetch fetches that run instead of * discarding the request; a run the operator has left is never written over. */ function scheduleRunDetailSync(runId) { const targetId = Number(runId); if (!(targetId > 0)) return null; if (runWatch.detailSyncJob) { runWatch.detailSyncRequestedRunId = targetId; return runWatch.detailSyncJob; } const job = (async () => { let target = targetId; let attempt = 0; while (target != null) { runWatch.detailSyncRequestedRunId = null; const generation = runWatch.generation; const deltaCount = runWatch.detailDeltaCount; try { const run = await repo.getRun(target); attempt = 0; if (generation !== runWatch.generation) { // A drop/re-subscribe superseded this read; re-read for the new watch // rather than writing a result from the old one. runWatch.detailSyncRequestedRunId = target; continue; } if (state.runDetail?.id === target) { if (runWatch.detailDeltaCount === deltaCount) { state.runDetail = run; renderRunState(); } else { // A newer frame overtook the fetch; re-read rather than write the // older run over it. runWatch.detailSyncRequestedRunId = target; } } // else: the operator left this run; its detail is no longer shown. } catch { if (generation !== runWatch.generation) { runWatch.detailSyncRequestedRunId = target; continue; } markStreamDegraded(); attempt += 1; if (attempt > RUN_SYNC_RETRY_LIMIT) return; await delay(RUN_SYNC_RETRY_BASE_MS * attempt); if (generation !== runWatch.generation) { runWatch.detailSyncRequestedRunId = target; continue; } // A run opened meanwhile wins over retrying this one. if (runWatch.detailSyncRequestedRunId == null) runWatch.detailSyncRequestedRunId = target; } target = runWatch.detailSyncRequestedRunId; } })(); runWatch.detailSyncJob = job; job.finally(() => { if (runWatch.detailSyncJob === job) runWatch.detailSyncJob = null; }); return job; } /** * Fold one pushed `run_event` frame into whatever local state it names: the runs * list (and so the pipeline rows' last-run line and the attention bell) in * place, and the open run detail. A frame for a run the list does not hold * re-syncs the list once; a frame that changed the detail and carries a settled * step, a waiting step/run or a terminal run also fetches the full detail once. */ function applyRunEvent(frame) { const runId = Number(frame?.run_id); if (!(runId > 0)) return; let listChanged = false; if (state.runsLoaded) { const fold = foldRunEvent(state.runs, frame); if (fold.needsResync) { scheduleRunsResync(); } else if (fold.runs !== state.runs) { state.runs = fold.runs; listChanged = true; renderRunState(); // A terminal transition also settles the usage aggregate (the active // count), which the delta does not carry; one server read refreshes it. A // duplicate terminal frame changes nothing above, so it triggers no read. if (frame.step == null && isTerminalRunStatus(frame.status)) scheduleRunsResync(); } } const detail = state.runDetail; if (detail && Number(detail.id) === runId) { runWatch.detailDeltaCount += 1; const folded = foldRunEventDetail(detail, frame); const detailChanged = folded !== detail; if (detailChanged) { state.runDetail = folded; renderRunState(); } if (runDetailNeedsFullSync(frame) && (detailChanged || listChanged)) { scheduleRunDetailSync(runId); } } // A list-only change with the detail open is still a fold; if the run list was // not in hand, the resync above covers the new row. } /** * The run/pipeline detail reset a different selection needs: no stale pane, * dialog or tab from the entity the operator navigated away from. Shared by the * in-page selection and the URL route so both open the same fresh detail. */ function resetRunDetailState() { state.runGraph?.unmount(); state.runGraph = null; state.runDetail = null; state.runTab = "summary"; state.runSections = new Set(); state.runStagePane = null; state.runStageSections = new Set(); state.runDecision = null; state.decisionOpen = false; state.decisionDraft = new DecisionDraft(); state.decisionSending = false; state.decisionError = ""; state.confirmKind = null; state.renameValue = null; state.actionError = ""; } /** * A server refusal (its own `type:"error"` reply) means the entity genuinely does * not exist. A transport failure — a timeout, a socket drop, a client-side * NotConnectedError — is not a missing entity, so its deep link is kept (and will * be hydrated again on reconnect) rather than discarded. */ function isServerRefusal(err) { return err instanceof ProtocolError; } /** * A run the server does not have falls back honestly: the selection is cleared, * the runs list is shown (and loaded if this was a hard deep link), the server's * own refusal stays in the page banner, and the URL is replaced with /runs. It * never throws and never leaves an empty run pane carrying a stale identity. */ async function missingRunFallback(err) { resetRunDetailState(); state.selectedRunId = null; state.view = "runs"; if (state.connection.kind === "connected" && !state.runsLoaded) { await loadCurrentView(); } state.error = describeError(err); replaceRoute({ kind: "runs" }); renderContent(); } /** * The pipeline-side reset a different selection (or a refusal) needs. The * selection ids are the caller's, so only the detail it describes is cleared. */ function resetPipelineDetailState() { state.pipelineDetail = null; state.pipelineTab = "summary"; state.pipelineGraphSelection = null; state.versionsExpanded = false; } /** * Whether the loaded graph can select a stage key. The route parser cannot know * the keys without data, so the wiring checks and falls back honestly. The * mounted graph selects every laid-out node — named stages and the two terminals * (`#success`/`#failure`) — and the URL it writes for any of them must re-open * the same pane, so the check uses the same layout rather than stages alone. */ function pipelineHasStage(detail, key) { return layoutGraph(detail?.graph).nodes.some((node) => node.key === key); } /** The pipeline counterpart of missingRunFallback: list, banner, /pipelines. */ async function missingPipelineFallback(err) { resetPipelineDetailState(); state.selectedPipelineId = null; state.view = "pipelines"; if (state.connection.kind === "connected" && !state.pipelinesLoaded) { await loadCurrentView(); } state.error = describeError(err); replaceRoute({ kind: "pipelines" }); renderContent(); } /** The pipeline selection this reply was requested for is still the shown one. */ function pipelineStillSelected(id, version) { return ( state.view === "pipelines" && state.selectedPipelineId === id && state.pipelineRequestedVersion === version ); } async function selectPipeline(summary, { updateRoute = true } = {}) { const id = summary.id; const version = Number.isSafeInteger(summary.version) && summary.version > 0 ? summary.version : 0; if (updateRoute) pushRoute({ kind: "pipeline", id, version }); state.view = "pipelines"; state.selectedPipelineId = id; state.pipelineRequestedVersion = version; resetPipelineDetailState(); // A selection describes only itself: a previous refusal banner must not sit // above the entity the operator has just opened. state.error = ""; renderContent(); 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(); } 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(); } 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(); // The run detail is no longer polled: the watch's pushed `run_event` frames // advance it live (R10), and a settled/terminal frame triggers one full // `get_run` for the heavy fields the compact delta omits. } catch (err) { if (!runStillSelected(id)) { return; } if (silent) { return; } if (isServerRefusal(err)) { await missingRunFallback(err); return; } // A transient failure keeps the deep link; the reconnect re-hydrates it. state.error = describeError(err); renderContent(); } } /** * (Re)start the shared runs-list clock: it ticks once a second only while a * shown run is executing, updating each running row's meta line in place (never * a full re-render, so an open filter/sort menu is not torn down). The elapsed * value is derived from the run's server start timestamp, so it survives a * reconnect. */ function refreshListClock() { stopListClock(); listNow = Date.now(); if (state.view === "runs" && state.runs.some((run) => run.executing)) { listClock = setInterval(() => { listNow = Date.now(); for (const node of document.querySelectorAll(".run-row-meta[data-run-id]")) { const id = Number(node.getAttribute("data-run-id")); const run = state.runs.find((candidate) => candidate.id === id); if (run && run.executing) node.textContent = metaText(run, listNow); } }, 1000); } } function stopListClock() { if (listClock) { clearInterval(listClock); listClock = null; } } /** * (Re)start the run detail's own clock: it ticks once a second only while the * shown run is executing, updating just the Duration row in place (never a full * re-render, so an open stage pane and its scroll are not torn down). The value * is derived from the server's start timestamp, so it survives a reconnect. */ function refreshDetailClock() { stopDetailClock(); detailNow = Date.now(); if (state.view === "runs" && isExecuting(state.runDetail)) { detailClock = setInterval(() => { detailNow = Date.now(); const node = document.querySelector(".run-duration[data-run-id]"); if (node && state.runDetail) node.textContent = runDurationText(state.runDetail, detailNow) ?? ""; }, 1000); } } function stopDetailClock() { if (detailClock) { clearInterval(detailClock); detailClock = null; } } // --------------------------------------------------------------------------- // View modules // --------------------------------------------------------------------------- // The view modules receive the page shell through one runtime object rather than // importing app.js, so the dependency direction stays app -> views (no cycle). const runtime = { state, client, repo, runAlerts, attentionLayer, searchHost, render, renderContent, renderHeader, renderBanner, endpointConfigured, setServerUrlDraft, pushRoute, applyRoute, openConfiguredEndpoint, onReconnectClicked, selectPipeline, selectRun, setError, loadCurrentView, }; const views = { attention: createAttentionView(runtime), settings: createSettingsView(runtime), pipelines: createPipelinesView(runtime), templates: createTemplatesView(runtime), runs: createRunsView(runtime), dialogs: createDialogsView(runtime), runDetail: createRunDetailView(runtime), chat: createChatView(runtime), search: createSearchView(runtime), }; runtime.views = views; const { renderAttentionBell, refreshAttentionBell, renderAttentionSheet, closeAttentionSheet, onRunAlertFrame, } = views.attention; const { renderSettingsView, refreshServerUrlError } = views.settings; const { renderPipelineList, renderPipelineDetail } = views.pipelines; const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection, closeTemplateCreateDialog } = views.templates; const renderRunList = () => views.runs.renderRunList(listNow); const renderRunDetail = () => views.runDetail.renderRunDetail(detailNow); const { renderChatList, renderChatCreate, renderChatConversation, afterChatRender, captureChatPosition, refreshChatClock, stopChatClock, loadChatSessions, loadChatDirectories, startNewChat, openChatSession, subscribeChatSession, clearChatSubscriptions, settleChatThreads, resyncOpenChat, onChatEvent, onChatPermission, onChatFrame, dismissChatClose, dismissChatRename, } = views.chat; const { openSearch, closeSearch, renderSearch, onSearchInput, sendSearchNow, } = views.search; const { openDecisionSheet, closeDecisionSheet, dismissConfirm, dismissActionError } = views.dialogs; const { closeStagePane } = views.runDetail; // Kept as named exports for the UI smoke's page-rendered markdown/tool samples. export const renderToolCallRow = views.chat.renderToolCallRow; export const renderToolDiff = views.chat.renderToolDiff; export const renderMarkdown = views.chat.renderMarkdown; // --------------------------------------------------------------------------- // Boot // --------------------------------------------------------------------------- client.addEventListener("state", (event) => { const next = event.detail; const wasConnected = state.connection.kind === "connected"; const previousKind = state.connection.kind; state.connection = next; if (next.kind === "connected" && !wasConnected) { onConnected(); } if (next.kind !== "connected" && previousKind === "connected") { stopListClock(); stopDetailClock(); stopChatClock(); // The socket dropped: the server detaches every chat subscription with it // (there is no chat_unsubscribe), and the frames feeding any running turn are // gone, so no thread keeps claiming to run until a fresh frame proves it. clearChatSubscriptions(); settleChatThreads(); // Drop the run-status baseline but keep this page session's notified keys: // the reconnect reseeds from the fresh list before it resubscribes, so a // transition hidden by the gap can never notify late. runAlerts.reset(); } if (next.kind !== "connected") { // Nothing is watched while the socket is down; an in-flight read is // invalidated and the badge falls back to Connecting (or Offline when idle). streamDown(); } // A reconnect (not a first connect): re-attach the open chat's stream and // refresh its history wholesale, so a gap that swallowed the end of a turn is // repaired rather than shown stale. if (next.kind === "connected" && (previousKind === "connecting" || previousKind === "disconnected")) { resyncOpenChat(); } render(); }); // The client surfaces every unsolicited envelope as a DOM-free `frame` event // (client.js). A `chat_event` frame is folded twice, on purpose: the live // transcript (C5) folds the frame itself, and the composer's own bookkeeping // clears the queued notice and releases the Stop control. A frame for any other // type is ignored. client.addEventListener("frame", (event) => { const message = event.detail; if (!message) return; // The live run stream (R10). A pushed `run_event` only reaches a subscriber, so // it confirms the watch even when the server never acks the subscribe. A reply // carrying our subscribe id is the optional ack (live) or a refusal (offline). if (message.type === Protocol.RUN_EVENT) { const frame = message[Protocol.RUN_EVENT]; if (frame) { confirmStreamLive(); applyRunEvent(frame); // L5: the same frame feeds the notification ledger. onRunAlertFrame(frame); } return; } if (message.id != null && message.id === runWatch.subscriptionId) { if (message.type === Protocol.SUBSCRIBE) { confirmStreamLive(); return; } if (message.type === Protocol.ERROR) { clearRunWatch(); setRunStream(RunStream.Offline); return; } } if (message.type === Protocol.CHAT_PERMISSION) { const permission = message[ChatKeys.PERMISSION]; if (permission) onChatPermission(permission); return; } if (message.type !== Protocol.CHAT_EVENT) return; const frame = message[ChatKeys.EVENT]; if (frame) onChatEvent(frame); onChatFrame(message); }); // The stage pane, the decision sheet, the confirm/Action-failed dialogs, the // omni-search field and the attention sheet are modal: Escape closes the topmost // one (the artifact viewer or the diff viewer, when either is above, owns Escape // first via its own listener). The attention sheet, when open, is the topmost // overlay and owns Escape first. Registered once; every branch is a no-op when // nothing is open. document.addEventListener("keydown", (event) => { if (event.key !== "Escape") return; if (state.attentionSheetOpen) { event.preventDefault(); closeAttentionSheet(); return; } if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return; if (state.templateCreateOpen) { event.preventDefault(); closeTemplateCreateDialog(); return; } if (state.actionError) { event.preventDefault(); dismissActionError(); return; } if (state.chatRename) { event.preventDefault(); dismissChatRename(); return; } if (state.chatClose) { event.preventDefault(); dismissChatClose(); return; } if (state.confirmKind) { event.preventDefault(); dismissConfirm(); return; } if (state.decisionOpen) { event.preventDefault(); closeDecisionSheet(); return; } if (state.runStagePane) { event.preventDefault(); closeStagePane(); return; } if (state.chatMenu) { event.preventDefault(); state.chatMenu = null; renderContent(); return; } if (state.searchOpen) { event.preventDefault(); closeSearch(); } }); // A click anywhere outside an open Chat actions menu closes it, so a menu never // lingers behind another row's selection. The wrap element (button + panel) // keeps its own clicks from closing it. document.addEventListener("click", (event) => { if (!state.chatMenu) return; const target = event.target; if (target instanceof Element && target.closest(".chat-menu-wrap")) return; state.chatMenu = null; renderContent(); }); // Return-to-foreground recovery (T4): the page becomes visible again, or the // browser reports it is back online, and the client drives its socket back // without waiting out the backoff. DOM-only, and idempotent. document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") onForegroundActive(); }); window.addEventListener("online", onForegroundActive); // Prefill from a previous session only; the user still confirms with Connect. // The attention surface's dismissed identities are loaded once here, before the // first render, so the bell's badge is correct from the very first paint. state.attentionDismissed = loadAttentionDismissed(); state.notifyAsked = loadNotifyAsked(); // One route parse at boot. A deep link is kept pending — the first successful // connection loads its list and then its detail/stage — while the page paints the // right destination's shell immediately. const bootRoute = parseRoute(location.pathname, location.search); // An unknown or malformed boot path parses to the Pipelines list; correct the // address bar so the URL and the rendered view agree (the pending deep link, if // any, is untouched: a real deep link is not the default route). const bootUrl = `${location.pathname}${location.search}`; if (bootRoute.kind === "pipelines" && bootUrl !== "/pipelines") { try { history.replaceState(null, "", "/pipelines"); } catch { // A non-HTTP location (file://) may refuse history; the view still renders. } } state.route = bootRoute; state.pendingRoute = bootRoute; state.view = viewForRoute(bootRoute); // 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();