// Spike web UI: pipeline list + run detail over the live WebSocket protocol. // Deliberately small and DOM-only (no framework, no build step). Every value // that came from the server is set with textContent, never innerHTML. import { PipelinesClient } from "./client.js"; import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js"; import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js"; import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js"; import { ForegroundAction, RunStream, bannerState, foregroundAction, liveBadgeState, protocolMismatch, serverBuildLabel, stateBadge, } from "./connection.js"; import { foldRunEvent, foldRunEventDetail, isTerminalRunStatus, runDetailNeedsFullSync, } from "./runEvents.js"; import { SERVER_URL_HELPER, SERVER_URL_PLACEHOLDER, TEMPLATES_CARD_LABEL, TEMPLATES_CARD_SECONDARY, TRUST_BODY, TRUST_TITLE, WORKSPACE_HELPER, WORKSPACE_PLACEHOLDER, canSaveWorkspace, connectionActionKind, connectionActions, connectionCard, readServerUrl, readWorkspace, savedWorkspaceLine, workspaceErrorText, writeServerUrl, writeWorkspace, } from "./settings.js"; import { ArtifactKind, artifactCaptureNotes, artifactGroups, artifactKind, artifactKindLabel, artifactsHeader, artifactsSummary, artifactViewerPositionLabel, displayVisit, humanBytes, pagedArtifacts, pagedIndex, presentedArtifacts, resolvedArtifactUrl, sessionExportArtifact, viewerIndexByUrl, } from "./artifacts.js"; import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, RUN_GRAPH_NOTE, mount as mountGraph, } from "./graph.js"; import { PIPELINE_SORTS, PIPELINE_DETAIL_TABS, RUN_PRESENCES, RUN_STATUS_FILTERS, EMPTY_PIPELINE_FILTERS, filterPipelines, graphNote, latestRunByPipeline, pipelineFilterCount, pipelineListEmptyState, pipelineSubtitle, pipelineUpdatedLine, runBadge, runBadgeMetaLine, sortPipelines, summaryFields, versionRow, } from "./pipelines.js"; import { RUN_STATES, RUN_TIME_RANGES, RUN_SORTS, DEFAULT_RUN_SORT, runStateOf, runIdentity, versionLabel, progressText, metaText, formatDuration, localDayKey, filterRuns, groupRunsByDay, runComparator, pipelineFilterOptions, runListEntries, defaultRunFilters, runFiltersActiveCount, } from "./runs.js"; import { CREATE_ACTION_LABEL, CREATE_NAME_LABEL, CREATE_NOTE, createConfirmLabel, createDismissLabel, createFormTitle, createFormValid, createSuccessMessage, createdPipelineName, effectiveStageType, templateCard, templateDetailName, templateGalleryName, templateGraphNote, templateStageCountLabel, templateStageSummary, TEMPLATE_UNPARSED_SOURCE_NOTE, } from "./templates.js"; import { RENDERED_RUN_TABS, EMPTY_INPUT_MESSAGE, EMPTY_OUTPUT_MESSAGE, EMPTY_TIMELINE_MESSAGE, NO_STAGE_DETAILS_MESSAGE, fieldSections, summaryRows, runIdentityLine, runLabelFor, runDurationText, runTimeline, runGraphState, nodeLabel, headlineFields, runStepFields, stageSectionSpecs, clampVisitIndex, referencedVerdictArtifacts, verdictReasonSegments, outcomeColorToken, stateGlyph, } from "./runDetail.js"; import { BINARY_DIFF_MESSAGE, NO_LINE_CHANGES_MESSAGE, TRUNCATED_PATCH_NOTE, ChangeKind, changeKindLabel, changeKindTitle, changePositionLabel, changeRowMeta, changeStat, changesListSummary, diffLineClass, diffLineSymbol, entryHasPatch, gutterText, gutterWidth, noChangeDetail, parseUnifiedPatch, patchUnavailableReason, runChanges, runChangesHeader, runChangesNote, } from "./changes.js"; import { ATTENTION_STORAGE_KEY, AttentionKind, attentionBadgeLabel, attentionDismissAll, attentionDismiss, attentionDismissalSnapshot, attentionEntries, attentionRowDescription, decodeAttentionDismissals, encodeAttentionDismissals, } from "./attention.js"; import { DEFAULT_SEARCH_KIND, DEFAULT_SEARCH_SORT, SEARCH_DEBOUNCE_MS, SEARCH_KINDS, SEARCH_SORTS, SearchSequencer, filterSearchResults, resolveRunTarget, searchControlsSummary, searchFailureText, searchPanelBody, searchPanelProgress, searchQuerySendable, searchResultKindLabel, searchRow, searchTarget, sortSearchResults, } from "./search.js"; import { ACTION_FAILED_OK, ACTION_FAILED_TITLE, CANCEL_CONFIRM, CANCEL_DIALOG_MESSAGE, DECISION_ACTION, DECISION_CANCEL, DECISION_CARD_TITLE, DECISION_CONFIRM, DECISION_SENDING, DISMISS_KEEP, DecisionDraft, FEEDBACK_LABEL, RENAME_ACTION, RENAME_CANCEL, RENAME_FIELD_LABEL, RENAME_SAVE, RESTART_CONFIRM, RESTART_DIALOG_MESSAGE, RETRY_CONFIRM, RETRY_DIALOG_MESSAGE, canCancel, canRetry, cancelDialogTitle, decisionCardMeta, decisionSheetMeta, decisionSheetTitle, optionTargetText, pendingDecision, restartDialogTitle, retryDialogTitle, retryRequestKey, } from "./actions.js"; import { BACKGROUND_TASKS_TITLE, CHAT_ATTACH_LABEL, CHAT_COMMAND_DISMISS_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMPOSER_PLACEHOLDER, CHAT_EMPTY, CHAT_FOLLOW_THRESHOLD_PX, CHAT_LOADING, CHAT_NEW_ACTION, CHAT_NO_MATCH_ACTION, CHAT_QUEUED_NOTICE, CHAT_SEARCH_LABEL, CHAT_SEND_LABEL, CHAT_STOP_LABEL, CHAT_TAB_TITLE, CLOSED_CHIP_LABEL, CLOSED_SECTION_LABEL, CLOSE_CHAT_ACTION, CLOSE_CHAT_CONFIRM, CLOSE_CHAT_DISMISS, CLOSE_CHAT_TITLE, COMPOSER_SEND, COMPOSER_STOP, CONVERSATION_EMPTY, CONVERSATION_LOADING, LOAD_OLDER_ACTION, REOPEN_ACTION, SELECT_CHAT_HINT, APPROVAL_CONTROL_ALWAYS, APPROVAL_CONTROL_ONCE, APPROVAL_CONTROL_REJECT, DECISION_ALWAYS, DECISION_ONCE, DECISION_REJECT, RISK_REVIEW_LABEL, WAITING_FOR_APPROVAL_LABEL, SHELL_DETAILS_LABEL, SHELL_OUTPUT_EMPTY, SHELL_OUTPUT_ERROR, SHELL_OUTPUT_LABELS, SHELL_OUTPUT_LOADING, SHELL_OUTPUT_READY, SHELL_OUTPUT_UNAVAILABLE, SHELL_ROW_LABEL, applyChatEvent, applyChatPermission, appendChatNotice, approvalCard, attachmentDisplayName, attachmentError, attachmentFiles, backgroundTasksRunningLabel, chatBottomDistancePx, chatCommandEffect, chatCommandHelp, chatCommandSuggestions, chatFirstScroll, chatFollowsAt, chatHeaderMeta, chatNoMatchMessage, chatNoticeLabel, chatOpensAtNewest, chatShowJumpToLatest, chatStreamState, closeChatConfirmation, composerAction, composerCanSend, composerSendEnabled, composerSubmit, directoryLabel, dismissChatNotice as dismissChatNoticeModel, filterSessions, groupSessionsByDirectory, historyResync, makeChatNotice, mergeHistoryPage, mergeShellFrame, newChatThread, parseChatInput, queuedAfterFrame, reasoningLabel, resumedThread, runningAfterFrame, runningBackgroundShells, runningToolElapsedMillis, sessionActivity, sessionActivityBadge, sessionChipLabel, sessionMeta, sessionStatusLabel, sessionTitle, sessionWorkLabel, settledThread, shellCommandSummary, shellOutputState, shellsLoaded, takeChatNoticeOffer as takeChatNoticeOfferModel, formatToolDuration, threadElapsedMillis, threadPhase, threadRunningTools, threadToolElapsedMillis, TURN_PHASE_WAITING, toolCallCount, toolCallRow, toolCallsAnnouncement, toolCallsLabel, toolDetail, toolFailed, toolLabel, toolLongRunning, toolRunning, toolsRunning, transcriptRows, turnElapsedMillis, turnPhaseLabel, } from "./chat.js"; import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js"; /** * The per-session chat scroll positions (C14). Persisted in localStorage, the * browser analogue of the Android `ChatThread.scroll`: a position the operator * deliberately left — including the very top — is restored, while an absent one * opens the conversation at its newest message. */ const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1"; /** * The per-chat composer drafts (C8). Mirrored into localStorage, the browser * analogue of the Android store's per-device draft: a draft survives a reload, * keyed by session id (attachments are memory-only — a File handle cannot be * serialised). The in-memory `thread.draft` is the source of truth while the page * is open; this is only the persistence beside it. */ const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1"; /** Shown where tiles exist but the configured server URL cannot resolve them. */ const ARTIFACT_SERVER_HINT = "Set the server URL in Settings to open or copy artifact links."; /** * The page is normally served by serve.mjs, which also proxies /connect to the * Pipelines server. Defaulting to this page's own origin therefore points at * that proxy and keeps the page and the WebSocket same-origin — the server * rejects a cross-origin upgrade with 403. Nothing is hardcoded: the value is * derived from wherever the page was loaded, and the user can override it. */ 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, // 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, // 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: [], 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, // 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(), }; // 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; // 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(); // The chat running indicator's own live clock (C5): it ticks once a second only // while the open conversation has a turn in flight, updating just the indicator // in place (never a full re-render), so the transcript's scroll is not disturbed. let chatClock = null; let chatNow = Date.now(); // --------------------------------------------------------------------------- // DOM helpers // --------------------------------------------------------------------------- function h(tag, props = {}, ...children) { const node = document.createElement(tag); for (const [key, value] of Object.entries(props)) { if (value == null || value === false) continue; if (key === "class") node.className = value; else if (key === "text") node.textContent = value; else if (key.startsWith("on") && typeof value === "function") { node.addEventListener(key.slice(2).toLowerCase(), value); } else node.setAttribute(key, value === true ? "" : String(value)); } for (const child of children.flat()) { if (child == null || child === false) continue; node.append(child instanceof Node ? child : document.createTextNode(String(child))); } return node; } function isExecuting(run) { return Boolean(run && run.executing); } /** 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); // The pending debounce timer and the edit it belongs to. Both are dropped the // moment the query is sent, cleared or superseded. let searchTimer = null; let searchEdit = null; /** 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")) 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 attention bell action, shown in the top bar on every view (R15). Its * accessible name comes from `attentionBadgeLabel`; the visible badge is drawn * only when something genuinely needs the operator, and the count comes from the * same pure model the sheet reads. */ function renderAttentionBell() { const count = attentionCount(); const label = attentionBadgeLabel(count); const button = h("button", { id: "attentionBell", class: "attention-bell", type: "button", "aria-label": label, title: label, onclick: openAttentionSheet, }); button.append(h("span", { class: "attention-bell-glyph", "aria-hidden": "true", text: "\uD83D\uDD14" })); if (count > 0) { button.append( h("span", { class: "attention-badge", "aria-hidden": "true", "data-count": String(count), text: String(count), }), ); } return button; } /** The number of entries the attention surface currently holds. */ function attentionCount() { return attentionEntries(state.runs, state.attentionDismissed).length; } /** * Update the bell in place after the run list (which the surface derives from) * loads, without rebuilding the header and disturbing the URL field. */ function refreshAttentionBell() { const button = document.querySelector("#attentionBell"); if (!button) return; const count = attentionCount(); const label = attentionBadgeLabel(count); button.setAttribute("aria-label", label); button.title = label; let badge = button.querySelector(".attention-badge"); if (count > 0) { if (!badge) { badge = h("span", { class: "attention-badge", "aria-hidden": "true" }); button.append(badge); } badge.dataset.count = String(count); badge.textContent = String(count); } else if (badge) { badge.remove(); } } /** * 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 }); } // --- Attention / "Needs you" surface (R15) --------------------------------- /** * The attention sheet: the ordered list from the pure `attentionEntries` model, * opened from the bell in the top bar. It is a single managed dialog — Escape, * a backdrop click and the Close button all close it — with the exact app * wording: title `Needs you`, rows of status icon + the run label + the * `{pipeline} · {detail}` line + a trailing `Dismiss`, and the empty state * `Nothing needs you right now.` with no Clear all. * * `state.attentionSnapshot` is captured only when the sheet opens and kept until * it closes, so Clear all acts on what the operator actually saw and an entry * that arrives while it is open is shown but not cleared. */ function renderAttentionSheet() { if (!state.attentionSheetOpen) { attentionLayer.replaceChildren(); return; } const entries = attentionEntries(state.runs, state.attentionDismissed); const overlay = h("div", { class: "attention-sheet", role: "dialog", "aria-modal": "true", "aria-label": "Needs you", }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeAttentionSheet(); }); const head = h( "div", { class: "attention-sheet-head" }, h("h2", { class: "attention-sheet-title", text: "Needs you" }), h("button", { class: "attention-sheet-close", type: "button", text: "Close", onclick: () => closeAttentionSheet(), }), ); const body = h("div", { class: "attention-sheet-body" }); if (entries.length === 0) { body.append(h("p", { class: "attention-empty", text: "Nothing needs you right now." })); } else { body.append( h("button", { class: "attention-clear", type: "button", text: "Clear all", onclick: clearAttentionSheet, }), ); for (const entry of entries) body.append(renderAttentionRow(entry)); } const sheet = h("div", { class: "attention-sheet-panel", tabindex: "-1" }, head, body); overlay.append(sheet); attentionLayer.replaceChildren(overlay); } /** One attention row: status icon, the two text lines, and a trailing Dismiss. */ function renderAttentionRow(entry) { const glyphState = entry.kind === AttentionKind.Decision ? "waiting" : "failed"; const open = h( "button", { class: "attention-row-open", type: "button", "data-run-id": String(entry.runId), "data-kind": entry.kind.name.toLowerCase(), onclick: () => activateAttentionEntry(entry), }, h("span", { class: `attention-icon chip-${glyphState}`, "aria-hidden": "true", text: stateGlyph(glyphState), }), h( "span", { class: "attention-text" }, h("span", { class: "attention-label", text: entry.label }), h("span", { class: "attention-desc", text: attentionRowDescription(entry) }), ), ); const dismiss = h("button", { class: "attention-dismiss", type: "button", "aria-label": "Dismiss", title: "Dismiss", onclick: (event) => { // The trailing control must never activate the row it sits in. event.stopPropagation(); dismissAttentionEntries([entry]); }, }); dismiss.append(h("span", { "aria-hidden": "true", text: "\u2715" })); return h("div", { class: "attention-row", "data-key": entry.key }, open, dismiss); } /** Open the sheet, capturing the dismissal snapshot it will act on. */ function openAttentionSheet() { state.attentionSheetOpen = true; state.attentionSnapshot = attentionDismissalSnapshot( attentionEntries(state.runs, state.attentionDismissed), ); render(); document.querySelector(".attention-sheet-close")?.focus(); } /** Close the sheet, dropping the snapshot; focus returns to the bell. */ function closeAttentionSheet({ restoreFocus = true } = {}) { if (!state.attentionSheetOpen) return; state.attentionSheetOpen = false; state.attentionSnapshot = null; render(); if (restoreFocus) document.querySelector("#attentionBell")?.focus(); } /** Dismiss one or more entries for good, persisting the identity set. */ function dismissAttentionEntries(entries) { if (!entries?.length) return; let next = new Set(state.attentionDismissed); for (const entry of entries) next = attentionDismiss(next, entry.key); persistAttentionDismissed(next); render(); } /** Clear all applies only the identities captured when the sheet opened. */ function clearAttentionSheet() { const snapshot = state.attentionSnapshot ?? []; const next = attentionDismissAll(state.attentionDismissed, snapshot); persistAttentionDismissed(next); render(); } /** * Activating a row closes the sheet and opens the run. A Failed row is dismissed * first (opening it is the operator dealing with it); a Decision row is not — * only answering the decision clears it. */ function activateAttentionEntry(entry) { if (entry.kind === AttentionKind.Failed) { persistAttentionDismissed(attentionDismiss(state.attentionDismissed, entry.key)); } state.attentionSheetOpen = false; state.attentionSnapshot = null; state.view = "runs"; render(); selectRun(entry.runId); } /** Store the dismissed identities as one JSON array under one localStorage key. */ function persistAttentionDismissed(next) { state.attentionDismissed = next; try { localStorage.setItem(ATTENTION_STORAGE_KEY, encodeAttentionDismissals(next)); } catch { // Storage disabled or full: the in-memory set still applies for this session. } } /** The dismissed identities from storage at boot; anything unreadable is empty. */ function loadAttentionDismissed() { try { return decodeAttentionDismissals(localStorage.getItem(ATTENTION_STORAGE_KEY)); } catch { return new Set(); } } 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" }, tabButton("pipelines", `Pipelines (${state.pipelines.length})`), 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") { split.append(renderChatList(), 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: () => { state.view = view; state.error = ""; renderContent(); if (view === "runs" && !state.runs.length) loadCurrentView(); if (view === "pipelines" && !state.pipelines.length) loadCurrentView(); if (view === "templates" && !state.templates.length) loadCurrentView(); if (view === "chat" && !state.chatLoaded) loadCurrentView(); }, }); } // --- Settings (L1) --------------------------------------------------------- /** * The Settings destination: the app's three sections (Connection, Workspace, * Templates) in one pane. It is wiring only — every string, the workspace * validation and the connection card's lines come from the pure `settings.js`, * and the connection controls drive the page's existing single client through * the same handlers the header uses (no second socket or path). Every * server-derived string is set with textContent. */ function renderSettingsView() { const pane = h("div", { class: "settings" }); pane.append(renderSettingsConnection(), renderSettingsWorkspace(), renderSettingsTemplates()); return pane; } function renderSettingsConnection() { const section = h("section", { class: "settings-section" }); section.append(h("h2", { class: "settings-title", text: "Connection" })); section.append( h( "label", { class: "settings-field", for: "settingsServerUrl" }, h("span", { class: "settings-field-label", text: "Server URL" }), h("input", { id: "settingsServerUrl", type: "text", placeholder: SERVER_URL_PLACEHOLDER, value: state.url, spellcheck: "false", autocomplete: "off", "aria-describedby": "settingsUrlHelper", "aria-invalid": state.urlError ? "true" : null, oninput: (event) => { setServerUrlDraft(event.target.value, "settingsServerUrl"); }, }), ), ); // Android's `urlError ?: helper` supporting text. The error clears on the next // edit (AppViewModel.updateServerUrlDraft) and is announced as the field's own // invalid state rather than as a page-level banner. section.append( h( "p", { id: "settingsUrlHelper", class: `settings-helper${state.urlError ? " settings-helper-error" : ""}`, role: state.urlError ? "alert" : null, }, serverUrlSupportingText(), ), ); const actions = connectionActions(state.connection); section.append( h( "div", { class: "settings-actions" }, h("button", { id: "settingsPrimary", class: "primary", type: "button", text: actions.primary, onclick: () => runConnectionAction(actions.primary), }), h("button", { id: "settingsSecondary", class: "ghost", type: "button", text: actions.secondary, onclick: () => runConnectionAction(actions.secondary), }), ), ); const tone = bannerState(state.connection, { hasEndpoint: endpointConfigured() }).tone; const card = h("div", { class: `settings-status status-${tone}` }); const lines = connectionCard(state.connection, { version: state.serverBuild?.version, commit: state.serverBuild?.commit, serverTime: state.serverTime, }); lines.forEach((line, index) => { // Android's Connecting card leads its one line with a CircularProgressIndicator; // the shared spinner is drawn only for that state, inline with the text, so the // other three stay plain text. if (index === 0 && state.connection.kind === "connecting") { const row = h("div", { class: "settings-status-head" }); row.append(h("span", { class: "spinner settings-status-spinner", "aria-hidden": "true" })); row.append(h("p", { class: "settings-status-line", text: line })); card.append(row); return; } card.append(h("p", { class: "settings-status-line", text: line })); }); section.append(card, renderTrustWarning()); return section; } /** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */ function renderTrustWarning() { return h( "div", { class: "settings-warning" }, h("p", { class: "settings-warning-title", text: TRUST_TITLE }), h("p", { class: "settings-warning-body", text: TRUST_BODY }), ); } /** * Route a Settings connection control through the page's existing single client, * mirroring AppViewModel: Disconnect closes the shared socket, Connect is * connect-only (validate + persist + open — never the header's toggle), and * Reconnect re-opens the same validated endpoint now. Nothing here opens a second * connection. */ function runConnectionAction(label) { const kind = connectionActionKind(label); if (kind === "disconnect") { repo.disconnect(); return; } if (kind === "reconnect") { onReconnectClicked(); return; } // The `Connect` label must never fall through to the header's toggle: while // connected that would tear the live socket down (Android's connect() is // connect-only). openConfiguredEndpoint(); } /** Android's `urlError ?: helper` supporting text for the Server URL field. */ function serverUrlSupportingText() { return state.urlError || SERVER_URL_HELPER; } /** * Update the Server URL field's own error state in place (supporting text, * aria-invalid and the error tint) so an invalid Connect never needs a full * re-render and the field being typed in is never rebuilt. */ function refreshServerUrlError() { const field = document.getElementById("settingsServerUrl"); const helper = document.getElementById("settingsUrlHelper"); if (field) { if (state.urlError) field.setAttribute("aria-invalid", "true"); else field.removeAttribute("aria-invalid"); } if (helper) { helper.textContent = serverUrlSupportingText(); helper.classList.toggle("settings-helper-error", Boolean(state.urlError)); if (state.urlError) helper.setAttribute("role", "alert"); else helper.removeAttribute("role"); } } function renderSettingsWorkspace() { const section = h("section", { class: "settings-section" }); section.append(h("h2", { class: "settings-title", text: "Workspace" })); section.append( h( "label", { class: "settings-field", for: "settingsWorkspace" }, h("span", { class: "settings-field-label", text: "Workspace path (on the server)" }), h("input", { id: "settingsWorkspace", type: "text", placeholder: WORKSPACE_PLACEHOLDER, value: state.workspaceDraft, spellcheck: "false", autocomplete: "off", "aria-describedby": "workspaceHelper", "aria-invalid": workspaceErrorText(state.workspaceDraft) ? "true" : null, oninput: (event) => { state.workspaceDraft = event.target.value; refreshWorkspaceControls(); }, }), ), ); section.append( h( "p", { id: "workspaceHelper", class: `settings-helper${workspaceErrorText(state.workspaceDraft) ? " settings-helper-error" : ""}`, }, workspaceSupportingText(), ), ); section.append( h("button", { id: "saveWorkspace", class: "primary settings-save", type: "button", text: "Save workspace", disabled: !canSaveWorkspace(state.workspaceDraft), onclick: saveWorkspace, }), ); section.append(h("p", { id: "savedWorkspace", class: "settings-saved", text: savedWorkspaceLine(state.workspace) })); return section; } /** Android's `workspaceError ?: helper` supporting text for the workspace field. */ function workspaceSupportingText() { return workspaceErrorText(state.workspaceDraft) || WORKSPACE_HELPER; } /** * Update the workspace field's dependent controls in place (the helper/error line * and the Save button's enabled state) so typing never re-renders — and so never * blurs — the field being typed in. */ function refreshWorkspaceControls() { const helper = document.getElementById("workspaceHelper"); const invalid = Boolean(workspaceErrorText(state.workspaceDraft)); if (helper) { helper.textContent = workspaceSupportingText(); helper.classList.toggle("settings-helper-error", invalid); } const field = document.getElementById("settingsWorkspace"); if (field) { if (invalid) field.setAttribute("aria-invalid", "true"); else field.removeAttribute("aria-invalid"); } const save = document.getElementById("saveWorkspace"); if (save) save.disabled = !canSaveWorkspace(state.workspaceDraft); } /** Persist the workspace (trimmed) and update the `Saved workspace:` line. */ function saveWorkspace() { if (!canSaveWorkspace(state.workspaceDraft)) return; state.workspace = writeWorkspace(localStorage, state.workspaceDraft); state.workspaceDraft = state.workspace; // Show the trimmed value that was actually stored, in the field as well as the // saved line (both updated in place so the keyboard focus is not disturbed). const field = document.getElementById("settingsWorkspace"); if (field) field.value = state.workspace; const saved = document.getElementById("savedWorkspace"); if (saved) saved.textContent = savedWorkspaceLine(state.workspace); } /** * Reset the template detail/create state that belongs to a selection. Shared by * selecting a template and opening the gallery from Settings, so the two lists of * fields can never drift. */ function resetTemplateCreateState() { state.templateTab = "summary"; // A different template reseeds the create dialog, so a name typed for one // template can never be submitted against another. state.templateCreateOpen = false; state.templateCreateName = ""; state.templateCreateSending = false; state.templateCreateError = ""; state.templateCreateCreated = null; } /** Clear the selection and everything that belongs to it. */ function resetTemplateSelection() { state.selectedTemplateKey = null; resetTemplateCreateState(); } /** * Open the existing Templates gallery (L1's one card): switch the view, clear any * selection/detail left from a previous visit and render. The gallery itself is * unchanged — this is the same destination the Templates tab opens. */ function openTemplatesFromSettings() { state.view = "templates"; state.error = ""; resetTemplateSelection(); renderContent(); if (!state.templates.length) loadCurrentView(); } function renderSettingsTemplates() { const section = h("section", { class: "settings-section" }); section.append(h("h2", { class: "settings-title", text: "Templates" })); const card = h( "button", { id: "browseTemplates", class: "card settings-card", type: "button", onclick: openTemplatesFromSettings, }, // SettingsScreen.kt's row idiom: a leading glyph, the label and secondary // line, then a forward chevron. h("span", { class: "settings-card-glyph", "aria-hidden": "true", text: "\u25a4" }), h( "span", { class: "settings-card-text" }, h("span", { class: "card-name", text: TEMPLATES_CARD_LABEL }), h("span", { class: "card-desc", text: TEMPLATES_CARD_SECONDARY }), ), h("span", { class: "settings-card-chevron", "aria-hidden": "true", text: "\u203a" }), ); section.append(card); return section; } function renderPipelineList() { const list = h("div", { class: "list" }); list.append(renderPipelineControls()); const rows = h("div", { id: "pipelineRows" }); fillPipelineRows(rows); list.append(rows); return list; } /** * The list's filter + sort toolbar and (when open) the matching menu panel. The * rows themselves live in the separate `#pipelineRows` container so a keystroke * in the name filter can refresh just the rows without rebuilding (and so * blurring) the input the operator is typing in. */ function renderPipelineControls() { const filters = state.pipelineFilters; const count = pipelineFilterCount(filters); const panel = state.pipelineMenu; const controls = h( "div", { class: "list-controls" }, h( "div", { class: "list-toolbar" }, h( "button", { id: "filterToggle", class: `control${panel === "filter" ? " active" : ""}`, onclick: () => { state.pipelineMenu = panel === "filter" ? null : "filter"; renderContent(); }, }, h("span", { text: "Filter" }), h("span", { id: "filterCount", class: "count", text: count ? ` (${count})` : "" }), ), h("button", { id: "sortToggle", class: `control${panel === "sort" ? " active" : ""}`, text: `Sort: ${pipelineSortLabel(state.pipelineSort)}`, onclick: () => { state.pipelineMenu = panel === "sort" ? null : "sort"; renderContent(); }, }), h("button", { id: "clearFilters", class: "ghost clear", text: "Clear filters", hidden: count === 0, onclick: clearPipelineFilters, }), ), ); if (panel === "filter") controls.append(renderFilterPanel()); if (panel === "sort") controls.append(renderSortPanel()); return controls; } function renderFilterPanel() { const filters = state.pipelineFilters; const panel = h("div", { class: "menu-panel filter-panel" }); panel.append(h("div", { class: "filter-section", text: "Name" })); panel.append( h( "label", { class: "filter-field" }, h("span", { class: "filter-field-label", text: "Pipeline name contains" }), h("input", { id: "pipelineNameFilter", type: "text", value: filters.name, spellcheck: "false", oninput: (e) => { state.pipelineFilters = { ...state.pipelineFilters, name: e.target.value }; // Targeted refresh: the input keeps focus and its value while the // list narrows behind it. refreshPipelineRows(); }, }), ), ); panel.append(h("div", { class: "filter-section", text: "Runs" })); for (const presence of RUN_PRESENCES) { panel.append( h( "label", { class: "filter-item" }, h("input", { type: "radio", name: "runPresence", checked: filters.presence === presence.key, onchange: () => { state.pipelineFilters = { ...state.pipelineFilters, presence: presence.key }; renderContent(); }, }), h("span", { text: presence.label }), ), ); } panel.append(h("div", { class: "filter-section", text: "Last run status" })); for (const status of RUN_STATUS_FILTERS) { panel.append( h( "label", { class: "filter-item" }, h("input", { id: `status-${status}`, type: "checkbox", checked: filters.lastRunStatuses.includes(status), onchange: (e) => { const next = e.target.checked ? [...state.pipelineFilters.lastRunStatuses, status] : state.pipelineFilters.lastRunStatuses.filter((s) => s !== status); state.pipelineFilters = { ...state.pipelineFilters, lastRunStatuses: next }; renderContent(); }, }), h("span", { text: status }), ), ); } panel.append( h("div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearPipelineFilters })), ); return panel; } function renderSortPanel() { const panel = h("div", { class: "menu-panel sort-panel" }); for (const option of PIPELINE_SORTS) { panel.append( h("button", { class: `sort-option${state.pipelineSort === option.key ? " active" : ""}`, text: option.label, onclick: () => { state.pipelineSort = option.key; state.pipelineMenu = null; renderContent(); }, }), ); } panel.append( h( "div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Reset", onclick: () => { state.pipelineSort = "server_order"; state.pipelineMenu = null; renderContent(); }, }), ), ); return panel; } /** Re-renders the rows and the toolbar's active-filter badge after a filter change. */ function refreshPipelineRows() { const rows = document.getElementById("pipelineRows"); if (rows) fillPipelineRows(rows); const count = pipelineFilterCount(state.pipelineFilters); const badge = document.getElementById("filterCount"); if (badge) badge.textContent = count ? ` (${count})` : ""; const clear = document.getElementById("clearFilters"); if (clear) clear.hidden = count === 0; } /** Sorts, filters and renders the pipeline rows (or the matching empty state) into `rowsEl`. */ function fillPipelineRows(rowsEl) { const latestRuns = latestRunByPipeline(state.runs); const runsKnown = state.runsLoaded; const now = Date.now(); const nodes = []; if (state.loading && !state.pipelines.length) { nodes.push(h("div", { class: "muted pad", text: "Loading pipelines…" })); } else if (!state.pipelinesLoaded) { nodes.push(h("div", { class: "muted pad", text: "Connect to the server to load pipelines." })); } else { const sorted = sortPipelines(state.pipelines, state.pipelineSort, latestRuns); const items = filterPipelines(sorted, state.pipelineFilters, latestRuns, runsKnown); if (items.length) { for (const pipeline of items) nodes.push(renderPipelineRow(pipeline, latestRuns, runsKnown, now)); } else { const empty = pipelineListEmptyState(state.pipelines, items, state.pipelineFilters); const box = h("div", { class: "empty pad" }, h("div", { class: "muted", text: empty.message })); if (empty.clearAction) { box.append(h("button", { class: "ghost", text: empty.clearAction, onclick: clearPipelineFilters })); } nodes.push(box); } } rowsEl.replaceChildren(...nodes); } function renderPipelineRow(pipeline, latestRuns, runsKnown, now) { const children = [ h("span", { class: "row-title", text: pipeline.name || `pipeline ${pipeline.id}` }), h("span", { class: "row-meta", text: pipelineSubtitle(pipeline) }), ]; const updated = pipelineUpdatedLine(pipeline); if (updated) children.push(h("span", { class: "row-meta", text: updated })); if (runsKnown) { const run = latestRuns.get(pipeline.id); if (!run) { children.push(h("span", { class: "row-meta muted", text: "no runs recorded" })); } else { const badge = runBadge(run, now); children.push( h( "span", { class: "row-run" }, h("span", { class: `chip chip-${badge.state}`, text: badge.state }), h("span", { class: "row-meta", text: runBadgeMetaLine(badge) }), ), ); } } return h( "button", { class: `row${state.selectedPipelineId === pipeline.id ? " selected" : ""}`, onclick: () => selectPipeline(pipeline) }, ...children, ); } function renderPipelineDetail() { const d = state.pipelineDetail; const pane = h("div", { class: "detail" }); if (!d) { pane.append(h("div", { class: "muted pad", text: "Select a pipeline." })); return pane; } pane.append(h("h2", { text: d.name || `pipeline ${d.id}` })); pane.append( h( "div", { class: "detail-tabs" }, ...PIPELINE_DETAIL_TABS.map((tab) => h("button", { class: `detail-tab${state.pipelineTab === tab.key ? " active" : ""}`, text: tab.label, onclick: () => { state.pipelineTab = tab.key; renderContent(); }, }), ), ), ); if (state.pipelineTab === "graph") { pane.append(h("p", { class: "graph-note muted", text: graphNote() })); const stages = d.graph?.stages ?? []; if (!stages.length) { pane.append(h("div", { class: "muted pad", text: PIPELINE_GRAPH_EMPTY })); return pane; } const host = h("div", { class: "graph-host" }); pane.append(host); state.pipelineGraph = mountGraph(host, d.graph, { expanded: state.pipelineGraphExpanded, onExpandedChange: (value) => { state.pipelineGraphExpanded = value; }, }); return pane; } if (state.pipelineTab === "source") { pane.append(h("pre", { class: "source-code" }, h("code", { text: d.source || "" }))); return pane; } pane.append(h("div", { class: "detail-subtitle muted", text: pipelineSubtitle({ ...d, stages: d.graph?.stages?.length ?? d.stages }) })); const rows = h("div", { class: "kv" }); for (const field of summaryFields(d)) { rows.append( h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: field.key }), h("span", { class: `kv-val${field.monospace ? " monospace" : ""}`, text: field.value }), ), ); } pane.append(rows); pane.append( h( "button", { class: "section-toggle", onclick: () => { state.versionsExpanded = !state.versionsExpanded; renderContent(); }, }, h("span", { class: "chevron", text: state.versionsExpanded ? "\u25be" : "\u25b8" }), h("span", { text: "Versions" }), ), ); if (state.versionsExpanded) { const versions = d.versions ?? []; const body = h("div", { class: "section-body versions-list" }); if (!versions.length) { body.append(h("div", { class: "muted", text: "No versions recorded." })); } else { for (const version of versions) { const row = versionRow(version); body.append( h( "div", { class: "version-row" }, h("span", { class: "version-title", text: row.versionLabel }), h("span", { class: "muted", text: row.stagesText }), row.createdText ? h("span", { class: "muted", text: row.createdText }) : null, ), ); } } pane.append(body); } return pane; } // --- Templates ------------------------------------------------------------- /** The cached parsed graph for a template key, or null when it did not parse. */ function templateGraphFor(key) { return state.templateGraphs.has(key) ? state.templateGraphs.get(key) : null; } function renderTemplateGallery() { const pane = h("div", { class: "list gallery" }); pane.append( h( "div", { class: "pane-head" }, h("h2", { text: "Templates" }), h("button", { class: "ghost", text: "Refresh templates", onclick: () => loadTemplates(true) }), ), ); if (state.templateLoading && !state.templates.length) { pane.append(h("div", { class: "muted pad", text: "Loading templates…" })); return pane; } if (!state.templates.length) { pane.append(h("div", { class: "muted pad", text: "No templates are available on this server." })); return pane; } const cards = h("div", { class: "cards" }); for (const entry of state.templates) { const card = templateCard(entry, templateGraphFor(entry.key)); cards.append( h( "button", { class: `card${state.selectedTemplateKey === entry.key ? " selected" : ""}`, onclick: () => selectTemplate(entry.key), }, h("span", { class: "card-name", text: templateGalleryName(card.name) }), h("span", { class: "card-desc", text: card.description }), h("span", { class: "card-meta", text: templateStageCountLabel(card.stageCount) }), ), ); } pane.append(cards); return pane; } function renderTemplateDetail() { const pane = h("div", { class: "detail" }); const entry = state.templates.find((t) => t.key === state.selectedTemplateKey); if (!entry) { pane.append(h("div", { class: "muted pad", text: "Select a template." })); return pane; } const graph = templateGraphFor(entry.key); pane.append(renderTemplateDetailActions()); pane.append( h( "div", { class: "tabstrip" }, templateTabButton("summary", "Summary"), templateTabButton("graph", "Graph"), templateTabButton("source", "Source"), ), ); if (state.templateTab === "graph") pane.append(renderTemplateGraphTab(graph)); else if (state.templateTab === "source") pane.append(renderTemplateSourceTab(entry, graph)); else pane.append(renderTemplateSummaryTab(entry, graph)); if (state.templateCreateOpen) pane.append(renderTemplateCreateDialog(entry)); return pane; } /** * The template detail's action row: the one "Create pipeline from this * template" action (P5), matching the app's top-bar add action. It opens the * dialog; it never submits on its own. */ function renderTemplateDetailActions() { return h( "div", { class: "detail-actions" }, h("button", { class: "ghost template-create-open", type: "button", text: CREATE_ACTION_LABEL, onclick: () => openTemplateCreateDialog(), }), ); } /** Open the create dialog with a fresh, empty name; nothing is sent until Create. */ function openTemplateCreateDialog() { state.templateCreateOpen = true; state.templateCreateName = ""; state.templateCreateSending = false; state.templateCreateError = ""; state.templateCreateCreated = null; renderContent(); document.querySelector(".template-create-name")?.focus(); } /** Dismiss the create dialog (never while a validate+submit is in flight). */ function closeTemplateCreateDialog() { if (state.templateCreateSending) return; state.templateCreateOpen = false; state.templateCreateName = ""; state.templateCreateError = ""; state.templateCreateCreated = null; renderContent(); } /** * The create dialog (P5): the title, the one required name field, the note, the * server's refusal text or the success line, and Create/Cancel (Cancel reads * Close after a success). Create is disabled while the name is blank or while * sending; the field locks while sending and after a success. Every server * string is set with textContent. */ function renderTemplateCreateDialog(entry) { const title = createFormTitle(entry); const overlay = h("div", { class: "template-create-dialog", role: "dialog", "aria-modal": "true", "aria-label": title, }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeTemplateCreateDialog(); }); const panel = h("div", { class: "template-create-panel" }); panel.append(h("h2", { class: "template-create-title", text: title })); const field = h("label", { class: "template-create-field" }); field.append(h("span", { class: "template-create-label", text: CREATE_NAME_LABEL })); field.append( h("input", { class: "template-create-name", type: "text", value: state.templateCreateName, spellcheck: "false", autocomplete: "off", disabled: state.templateCreateSending || state.templateCreateCreated != null, oninput: (event) => { // Update in place (no re-render) so the field keeps focus and its caret; // only the confirm button's enabled state depends on the name. state.templateCreateName = event.target.value; const confirm = overlay.querySelector(".template-create-confirm"); if (confirm) { confirm.disabled = !createFormValid(state.templateCreateName, { sending: state.templateCreateSending, created: state.templateCreateCreated, }); } }, }), ); panel.append(field); panel.append(h("p", { class: "template-create-note muted", text: CREATE_NOTE })); if (state.templateCreateError) { panel.append(h("div", { class: "template-create-error bad", text: state.templateCreateError })); } if (state.templateCreateCreated != null) { panel.append( h("div", { class: "template-create-success", text: createSuccessMessage(state.templateCreateCreated), }), ); } const actions = h("div", { class: "template-create-actions" }); actions.append( h("button", { class: "ghost template-create-cancel", type: "button", text: createDismissLabel(state.templateCreateCreated), disabled: state.templateCreateSending, onclick: closeTemplateCreateDialog, }), ); actions.append( h("button", { class: "template-create-confirm", type: "button", text: createConfirmLabel(state.templateCreateSending), disabled: !createFormValid(state.templateCreateName, { sending: state.templateCreateSending, created: state.templateCreateCreated, }), onclick: () => createFromTemplate(entry), }), ); panel.append(actions); overlay.append(panel); return overlay; } /** * The P5 submit flow, exactly the app's: validate the template's source first * and, when the server refuses to parse it, show its own error in the dialog and * send nothing; otherwise submit the source create-only with the chosen name. On * success remember the created name, refresh the pipeline list so the new row is * visible and leave the dialog open (Cancel now reads Close); on failure show * the server's error without closing. */ async function createFromTemplate(entry) { if ( !createFormValid(state.templateCreateName, { sending: state.templateCreateSending, created: state.templateCreateCreated, }) ) { return; } const name = state.templateCreateName; state.templateCreateSending = true; state.templateCreateError = ""; renderContent(); try { await repo.validate(entry.source); } catch (error) { state.templateCreateSending = false; state.templateCreateError = describeError(error); renderContent(); return; } try { const detail = await repo.submit(name, entry.source); state.templateCreateSending = false; state.templateCreateCreated = createdPipelineName(detail, name); await refreshPipelines(); } catch (error) { state.templateCreateSending = false; state.templateCreateError = describeError(error); } renderContent(); } /** * Refresh just the pipeline summaries after a create so the new row appears when * the operator returns to the Pipelines list. A failed refresh keeps the created * name and is surfaced through the banner rather than discarded. */ async function refreshPipelines() { try { state.pipelines = await repo.listPipelines(); state.pipelinesLoaded = true; } catch (error) { state.error = describeError(error); } } function templateTabButton(tab, label) { return h("button", { class: `minitab${state.templateTab === tab ? " active" : ""}`, text: label, onclick: () => { state.templateTab = tab; renderContent(); }, }); } function renderTemplateSummaryTab(entry, graph) { const wrap = h("div", { class: "tabbody" }); wrap.append(h("h2", { text: templateDetailName(entry) })); if ((entry.description ?? "").trim()) { wrap.append(h("p", { class: "body", text: entry.description })); } wrap.append(h("div", { class: "kv" }, kvMono("Key", entry.key))); wrap.append( h("div", { class: "meta-line", text: templateStageCountLabel(graph?.stages?.length ?? null) }), ); if (entry.scheduled) wrap.append(h("div", { class: "meta-line", text: "Includes a schedule" })); const summary = templateStageSummary(graph); if (summary.note) { wrap.append(h("div", { class: "muted pad", text: summary.note })); return wrap; } wrap.append(h("h3", { text: "Stages" })); const ul = h("ul", { class: "stages" }); for (const stage of summary.stages) { ul.append( h( "li", {}, h("code", { text: stage.key }), h("span", { class: "chip", text: effectiveStageType(stage.type) }), ), ); } wrap.append(ul); return wrap; } function renderTemplateGraphTab(graph) { const wrap = h("div", { class: "tabbody" }); wrap.append(h("p", { class: "muted", text: templateGraphNote(graph) })); return wrap; } function renderTemplateSourceTab(entry, graph) { const wrap = h("div", { class: "tabbody" }); if (graph == null) { wrap.append(h("p", { class: "muted", text: TEMPLATE_UNPARSED_SOURCE_NOTE })); } wrap.append( h( "div", { class: "codeblock" }, h("div", { class: "codeblock-label", text: "Definition source" }), h("pre", { class: "codeblock-body", text: entry.source ?? "" }), ), ); return wrap; } function pipelineSortLabel(key) { return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label; } function clearPipelineFilters() { state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS }; renderContent(); } function renderRunList() { const pane = h("div", { class: "list runs" }); pane.append(renderRunToolbar()); const scroll = h("div", { class: "run-scroll" }); if (state.loading && !state.runs.length) { scroll.append(h("div", { class: "muted pad", text: "Loading…" })); pane.append(scroll); return pane; } const filters = state.runFilters; const today = localDayKey(new Date()); const filtered = filterRuns(state.runs, filters, today); const groups = groupRunsByDay(filtered, today, undefined, runComparator(state.runSort)); const entries = runListEntries( state.usage, state.runs.length === 0, filtered.length === 0 && state.runs.length > 0, groups, "", ); for (const entry of entries) { switch (entry.kind) { case "usage": scroll.append(renderUsage(entry.usage)); break; case "empty": scroll.append(renderEmptyState(entry)); break; case "day": scroll.append(h("div", { class: "day-header", text: entry.label })); break; case "run": scroll.append(renderRunRow(entry.run)); break; case "error": scroll.append(h("div", { class: "run-list-error", text: entry.message })); break; } } pane.append(scroll); return pane; } function renderUsage(usage) { const metrics = h("div", { class: "metrics" }); metrics.append(metric("Total", String(usage.total ?? 0), "total")); if ((usage.average_seconds ?? 0) > 0) { metrics.append(metric("Average", formatDuration(usage.average_seconds), "average")); } metrics.append(metric("Succeeded", String(usage.succeeded ?? 0), "succeeded")); metrics.append(metric("Failed", String(usage.failed ?? 0), "failed")); metrics.append(metric("Canceled", String(usage.canceled ?? 0), "canceled")); metrics.append(metric("Interrupted", String(usage.interrupted ?? 0), "interrupted")); metrics.append(metric("Active", String(usage.active ?? 0), "active")); return metrics; } function metric(label, value, cls) { return h( "div", { class: `metric metric-${cls}` }, h("span", { class: "metric-value", text: value }), h("span", { class: "metric-label", text: label }), ); } function renderEmptyState(entry) { const wrap = h("div", { class: "empty-state" }, h("span", { text: entry.message })); if (entry.actionLabel) { wrap.append(h("button", { class: "ghost", text: entry.actionLabel, onclick: clearRunFilters })); } return wrap; } /** * One run row, in the app's exact hierarchy: status chip (+ spinner while * executing); primary line = stored title else pipeline name, carrying the * version chip when there is no title; the pipeline name + version chip on a * second line only when a title exists; the progress line; the meta line; and * the diagnostic line, in the error colour only on a failure. Every * server-provided string is set with textContent. */ function renderRunRow(run) { const status = runStateOf(run.status); const identity = runIdentity(run.title, run.name); const row = h("button", { class: `row run-row${state.selectedRunId === run.id ? " selected" : ""}`, onclick: () => selectRun(run.id), }); const head = h("span", { class: "run-row-head" }); head.append(h("span", { class: `chip chip-${status}`, text: status })); if (run.executing) head.append(h("span", { class: "spinner", "aria-hidden": "true" })); head.append(h("span", { class: "run-row-title", text: identity.label })); if (identity.pipeline == null) head.append(versionChip(run.version)); row.append(head); if (identity.pipeline != null) { row.append( h( "span", { class: "run-row-pipeline" }, h("span", { class: "run-row-pipeline-name", text: identity.pipeline }), versionChip(run.version), ), ); } row.append(h("span", { class: "run-row-progress", text: progressText(run) })); row.append( h("span", { class: "run-row-meta", "data-run-id": String(run.id), text: metaText(run, listNow), }), ); if (String(run.diagnostic ?? "").trim()) { row.append( h("span", { class: `run-row-diag${status === "failed" ? " error" : ""}`, text: run.diagnostic, }), ); } return row; } function versionChip(version) { return h("span", { class: "version-chip", text: versionLabel(version) }); } function renderRunToolbar() { const activeCount = runFiltersActiveCount(state.runFilters); const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter"; const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label; const toolbar = h("div", { class: "run-toolbar" }); toolbar.append( h( "div", { class: "menu-anchor" }, h("button", { id: "runFilterBtn", class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`, title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs", text: filterLabel, "data-active-count": String(activeCount), onclick: () => toggleMenu("filter"), }), state.openMenu === "filter" ? renderFilterMenu() : null, ), h( "div", { class: "menu-anchor" }, h("button", { id: "runSortBtn", class: "ghost sort-btn", title: "Sort runs", text: `Sort: ${sortLabel}`, onclick: () => toggleMenu("sort"), }), state.openMenu === "sort" ? renderSortMenu() : null, ), h("span", { class: "spacer" }), renderLiveBadge(liveBadgeState(state.runStream)), ); return toolbar; } /** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */ function renderLiveBadge(info) { return h( "span", { class: `live-badge live-${info.tone}`, title: info.title ?? "Live run stream" }, h("span", { class: "live-dot", "aria-hidden": "true" }), h("span", { class: "live-word", text: info.label }), ); } function renderFilterMenu() { const filters = state.runFilters; const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" }); menu.append(h("div", { class: "menu-section", text: "Status" })); for (const status of RUN_STATES) { menu.append( filterCheck(status, filters.statuses.has(status), () => toggleStatusFilter(status), { "data-status": status, }), ); } menu.append(h("div", { class: "menu-divider" })); menu.append(h("div", { class: "menu-section", text: "Pipeline" })); menu.append( filterCheck("Any pipeline", filters.pipelineId == null, () => setPipelineFilter(null), { "data-pipeline": "any", }), ); for (const option of pipelineFilterOptions(state.runs)) { menu.append( filterCheck(option.name, filters.pipelineId === option.id, () => setPipelineFilter(option.id), { "data-pipeline": String(option.id), }), ); } menu.append(h("div", { class: "menu-divider" })); menu.append(h("div", { class: "menu-section", text: "Time range" })); for (const range of RUN_TIME_RANGES) { menu.append( filterCheck(range.label, filters.timeRange === range.value, () => setTimeRangeFilter(range.value), { "data-time": range.value, }), ); } menu.append( h( "div", { class: "menu-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearRunFilters }), h("button", { class: "ghost", text: "Done", onclick: closeMenu }), ), ); return menu; } function filterCheck(label, checked, onclick, data = {}) { return h( "label", { class: "filter-check" }, h("input", { type: "checkbox", checked: checked ? "checked" : null, onchange: onclick, ...data, }), h("span", { text: label }), ); } function renderSortMenu() { const menu = h("div", { class: "menu sort-menu", id: "runSortMenu" }); for (const option of RUN_SORTS) { menu.append( h("button", { class: `menu-item${state.runSort === option.value ? " selected" : ""}`, text: option.label, onclick: () => { state.runSort = option.value; closeMenu(); }, }), ); } menu.append(h("div", { class: "menu-divider" })); menu.append( h("button", { class: "menu-item", text: "Reset", onclick: () => { state.runSort = DEFAULT_RUN_SORT; closeMenu(); }, }), ); return menu; } function toggleStatusFilter(status) { const next = new Set(state.runFilters.statuses); if (next.has(status)) next.delete(status); else next.add(status); state.runFilters = { ...state.runFilters, statuses: next }; renderContent(); } function setPipelineFilter(pipelineId) { state.runFilters = { ...state.runFilters, pipelineId }; closeMenu(); } function setTimeRangeFilter(timeRange) { state.runFilters = { ...state.runFilters, timeRange }; closeMenu(); } function clearRunFilters() { state.runFilters = defaultRunFilters(); closeMenu(); } function toggleMenu(name) { state.openMenu = state.openMenu === name ? null : name; renderContent(); } function closeMenu() { state.openMenu = null; renderContent(); } /** * The run detail: a tab strip (Summary / Graph / Input / Output / Timeline) over * the selected tab's body, wired from the pure helpers in runDetail.js. Summary * is the default and carries the run's identity, key/value rows and diagnostic; * the Graph tab mounts the shared workflow graph in run mode; Input/Output are * one collapsed section per recorded field; the Timeline is one compact row per * visit that opens the stage pane. Every server string is set with textContent, * never innerHTML. */ function renderRunDetail() { const d = state.runDetail; const pane = h("div", { class: "detail run-detail" }); if (!d) { pane.append(h("div", { class: "muted pad", text: "Select a run." })); return pane; } // A run parked on a person surfaces its decision above the tabs, exactly where // the Android run detail does, so opening the run is enough — no tab hunt. const decision = pendingDecision(d); if (decision) pane.append(renderDecisionCard(decision)); const actions = renderRunActions(d); if (actions) pane.append(actions); pane.append( h( "div", { class: "detail-tabs" }, ...RENDERED_RUN_TABS.map((tab) => h("button", { class: `detail-tab${state.runTab === tab.key ? " active" : ""}`, text: tab.label, onclick: () => { state.runTab = tab.key; renderContent(); }, }), ), ), ); if (state.runTab === "graph") { pane.append(renderRunGraphTab(d)); } else if (state.runTab === "input") { pane.append(renderRunFieldTab(d.input, "input", EMPTY_INPUT_MESSAGE)); } else if (state.runTab === "output") { pane.append(renderRunFieldTab(d.output, "output", EMPTY_OUTPUT_MESSAGE)); } else if (state.runTab === "steps") { pane.append(renderRunTimelineTab(d)); } else { pane.append(renderRunSummaryTab(d)); } if (state.runStagePane) pane.append(renderStagePane(d)); if (state.decisionOpen && state.runDecision) pane.append(renderDecisionSheet(state.runDecision)); const confirm = renderConfirmDialog(d); if (confirm) pane.append(confirm); if (state.actionError) pane.append(renderActionFailedDialog()); return pane; } /** * The Graph tab (R5): the run's own guidance note plus the shared workflow graph * mounted in run mode, or the app's exact missing-graph sentence when the server * sent no stages. The active stage pulses with its elapsed time while the run * executes; clicking a stage opens the existing visit pane at that stage's most * recent visit. The mount handle is tracked in `state.runGraph` so a re-render * (or a tab/run change) always unmounts the previous wheel/pointer/resize * listeners and the elapsed timer. */ function renderRunGraphTab(d) { const wrap = h("div", { class: "run-tab-body" }); const stages = d.graph?.stages ?? []; if (!stages.length) { wrap.append(h("div", { class: "run-empty muted", text: RUN_GRAPH_MISSING })); return wrap; } wrap.append(h("p", { class: "graph-note muted", text: RUN_GRAPH_NOTE })); const host = h("div", { class: "graph-host" }); wrap.append(host); state.runGraph = mountGraph(host, d.graph, { runState: runGraphState(d), onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)), }); return wrap; } /** * The visit index the graph opens for a stage: its most recent recorded visit * (`visits.size - 1`, never negative), exactly as RunGraphTab computes it. */ function latestVisitIndex(d, key) { const visits = runTimeline(d.steps ?? []).visitsByStage.get(key) ?? []; return Math.max(0, visits.length - 1); } /** The Summary tab: identity, chip row, key/value rows, diagnostic and gallery. */ function renderRunSummaryTab(d) { const wrap = h("div", { class: "run-tab-body" }); wrap.append(renderRunTitleRow(d)); const status = runStateOf(d.status); const chips = h("div", { class: "run-chip-row" }); chips.append(h("span", { class: `chip chip-${status}`, text: d.status || status })); if (String(d.outcome ?? "").trim()) chips.append(h("span", { class: "muted", text: `outcome ${d.outcome}` })); if (d.executing) chips.append(h("span", { class: "muted", text: "executing" })); chips.append(renderLiveBadge(liveBadgeState(state.runStream))); wrap.append(chips); wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) })); const rows = h("div", { class: "kv" }); for (const row of summaryRows(d, detailNow)) { if (row.kind === "wait") rows.append(h("div", { class: "run-wait", text: row.value })); else if (row.kind === "duration") rows.append(renderDurationRow(d, row)); else if (row.kind === "block") rows.append(renderCodeBlock(row.key, row.value)); else rows.append(renderKvRow(row)); } wrap.append(rows); // The run-level artifacts gallery (parity R8), collapsed by default like the // Android summary. Its header alone says what was captured until expanded. wrap.append( renderCollapsible("summary-artifacts", artifactsHeader(d.steps ?? [], isExecuting(d)), () => renderArtifactGallery(d.steps ?? []), ), ); // The run-level Changes (parity R4), collapsed by default like the Android // summary: the observed workspace diff. Its header alone states the file count // and aggregate stat until expanded, and every file row opens the diff viewer. const changes = runChanges(d.steps ?? []); wrap.append( renderCollapsible("summary-changes", runChangesHeader(changes), () => renderChangesBody(changes)), ); return wrap; } /** The Duration row, tagged so the detail clock can update it in place. */ function renderDurationRow(d, row) { return h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: row.key }), h("span", { class: "kv-val run-duration", "data-run-id": String(d.id), text: row.value }), ); } /** One key/value row from a summary row model. */ function renderKvRow(row) { return h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: row.key }), h("span", { class: `kv-val${row.monospace ? " monospace" : ""}`, text: row.value }), ); } /** A themed monospace block with a label header. */ function renderCodeBlock(label, text) { return h( "div", { class: "codeblock" }, h("div", { class: "codeblock-label", text: label }), h("pre", { class: "codeblock-body", text }), ); } /** One stage-pane field as either the code card (blocks) or a key/value row. */ function renderStageField(field) { if (field.block) return renderCodeBlock(field.label, field.value); return h( "div", { class: "kv-row" }, h("span", { class: "kv-key", text: field.label }), h("span", { class: `kv-val${field.mono ? " monospace" : ""}`, text: field.value }), ); } /** One collapsible input/output field section (expanded body is a code block). */ function renderRunFieldTab(map, keyPrefix, emptyMessage) { const wrap = h("div", { class: "run-tab-body" }); const sections = fieldSections(map, keyPrefix); if (!sections.length) { wrap.append(h("div", { class: "run-empty muted", text: emptyMessage })); return wrap; } for (const section of sections) { const key = `${keyPrefix}-${section.key}`; wrap.append( renderCollapsible(key, section.title, () => h("pre", { class: "field-block" }, h("code", { text: section.value })), ), ); } return wrap; } /** * One collapsible section of the run detail's field/summary body. Expanded state * is keyed in `state.runSections`, so the operator's choices survive a re-render. */ function renderCollapsible(key, title, bodyFn) { const expanded = state.runSections.has(key); const wrap = h("div", { class: "collapsible" }); wrap.append( h( "button", { class: "section-toggle", type: "button", "aria-expanded": expanded ? "true" : "false", onclick: () => { state.runSections = new Set(state.runSections); if (state.runSections.has(key)) state.runSections.delete(key); else state.runSections.add(key); renderContent(); }, }, h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), h("span", { class: "section-title", text: title }), ), ); if (expanded) wrap.append(h("div", { class: "section-body" }, bodyFn())); return wrap; } // --- Changes (parity R4) --------------------------------------------------- /** * The Changes section body: the file-list summary line, the honest capture note * (when the capture was not complete) and then either the no-change detail or * one clickable row per changed file in first-seen order. Every server string is * set as text, never as markup. */ function renderChangesBody(changes) { const body = h("div", { class: "changes" }); body.append(h("div", { class: "changes-summary", text: changesListSummary(changes) })); const note = runChangesNote(changes); if (note.trim() !== "") body.append(h("div", { class: "changes-note muted", text: note })); if (changes.files.length === 0) { body.append(h("div", { class: "changes-empty muted", text: noChangeDetail(changes) })); return body; } const list = h("div", { class: "changes-list" }); changes.files.forEach((entry, index) => list.append(renderChangeRow(entry, index, changes.files))); body.append(list); return body; } /** The tone class for a file's kind: added green, deleted red, else neutral. */ function changeKindTone(kind) { if (kind === ChangeKind.Added) return "ok"; if (kind === ChangeKind.Deleted) return "bad"; return "muted"; } /** * One changed-file row: the kind word in its hue, the path in monospace, the * `+N -M` stat and the `changed by …` meta line. Clicking (or Enter/Space) opens * the diff viewer on this file, whose position there confirms which row it is. */ function renderChangeRow(entry, index, files) { const open = () => openChangeViewer(files, index); const row = h("div", { class: "change-row", role: "button", tabindex: "0", "data-change-index": String(index), "aria-label": `Open ${entry.path}`, }); row.addEventListener("click", open); row.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); open(); } }); row.append(h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindLabel(entry.kind) })); const main = h("div", { class: "change-main" }); main.append(h("div", { class: "change-path monospace", text: entry.path })); main.append(h("div", { class: "change-meta muted", text: changeRowMeta(entry) })); row.append(main); const stat = h("div", { class: "change-stat" }); if (entry.added > 0) stat.append(h("span", { class: "stat-add", text: `+${entry.added}` })); if (entry.removed > 0) stat.append(h("span", { class: "stat-del", text: `-${entry.removed}` })); row.append(stat); return row; } let changeViewerOverlay = null; let changeViewerKeydown = null; let changeViewerIndex = null; /** Close the diff viewer, returning focus to the row that opened it. */ function closeChangeViewer() { if (changeViewerKeydown) { document.removeEventListener("keydown", changeViewerKeydown); changeViewerKeydown = null; } const index = changeViewerIndex; changeViewerOverlay?.remove(); changeViewerOverlay = null; changeViewerIndex = null; if (index != null) { document.querySelector(`.change-row[data-change-index="${index}"]`)?.focus(); } } /** * The full-screen diff viewer for one changed file. It pages through the run's * changed files exactly as the artifact viewer pages through a gallery's media * (one shared index, previous/next affordances, Escape/the close button/backdrop * dismissing), and shows both forms the brief requires, switchable from one * control row: the **Rendered** reading (each hunk's `@@` header, the shared * diff line language and the old/new gutter numbers) and the **Raw patch** (the * server's unified patch verbatim in monospace). A file the server could not * give a patch for (binary, truncated, or a capture that recorded none) shows the * honest reason in place of a diff rather than a fabricated one. */ function openChangeViewer(files, startIndex) { closeChangeViewer(); if (!files?.length) return; let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1); let form = "rendered"; const overlay = h("div", { class: "change-viewer", role: "dialog", "aria-modal": "true", "aria-label": "Diff viewer", }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeChangeViewer(); }); const renderViewer = () => { const entry = files[index]; changeViewerIndex = index; const stat = changeStat(entry.added, entry.removed); const hasPatch = entryHasPatch(entry); const titles = h("div", { class: "change-viewer-titles" }); const titleRow = h("div", { class: "change-viewer-title-row" }); titleRow.append( h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindTitle(entry.kind) }), ); if (stat !== "") titleRow.append(h("span", { class: "change-viewer-stat monospace", text: stat })); titles.append(titleRow); titles.append(h("div", { class: "change-viewer-path monospace", text: entry.path })); titles.append( h("div", { class: "change-viewer-position muted", text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`, }), ); const head = h( "div", { class: "change-viewer-head" }, titles, h("button", { class: "change-viewer-copy", type: "button", text: "Copy raw patch", disabled: !hasPatch, onclick: () => copyText(entry.patch ?? ""), }), h("button", { class: "change-viewer-close", type: "button", text: "Close diff", onclick: closeChangeViewer, }), ); const controls = h( "div", { class: "change-viewer-controls" }, h("button", { class: `change-form${form === "rendered" ? " active" : ""}`, type: "button", "data-form": "rendered", text: "Rendered", disabled: form === "rendered", onclick: () => { form = "rendered"; renderViewer(); }, }), h("button", { class: `change-form${form === "raw" ? " active" : ""}`, type: "button", "data-form": "raw", text: "Raw patch", disabled: !hasPatch, onclick: () => { form = "raw"; renderViewer(); }, }), h("div", { class: "change-viewer-spacer" }), h("button", { class: "change-page", type: "button", "data-page": "prev", text: "Previous file", disabled: index === 0, onclick: () => { index = Math.max(index - 1, 0); form = "rendered"; renderViewer(); }, }), h("button", { class: "change-page", type: "button", "data-page": "next", text: "Next file", disabled: index === files.length - 1, onclick: () => { index = Math.min(index + 1, files.length - 1); form = "rendered"; renderViewer(); }, }), ); const body = h("div", { class: "change-viewer-body" }); if (entry.binary || !hasPatch) { body.append( h("div", { class: "change-honest muted", text: entry.binary ? BINARY_DIFF_MESSAGE : patchUnavailableReason(entry), }), ); } else if (form === "raw") { body.append(h("pre", { class: "change-raw monospace", text: entry.patch ?? "" })); } else { body.append(renderRenderedDiff(entry)); } overlay.replaceChildren(head, controls, body); }; renderViewer(); document.body.append(overlay); changeViewerOverlay = overlay; changeViewerKeydown = (event) => { if (event.key === "Escape") closeChangeViewer(); }; document.addEventListener("keydown", changeViewerKeydown); } /** The rendered reading: the stat line, an optional truncation note, each hunk. */ function renderRenderedDiff(entry) { const wrap = h("div", { class: "change-diff" }); const parsed = parseUnifiedPatch(entry.patch); const statLine = h("div", { class: "change-diff-stat" }); if (parsed.added > 0) statLine.append(h("span", { class: "stat-add", text: `+${parsed.added}` })); if (parsed.removed > 0) statLine.append(h("span", { class: "stat-del", text: `-${parsed.removed}` })); if (parsed.added === 0 && parsed.removed === 0) { statLine.append(h("span", { class: "muted", text: NO_LINE_CHANGES_MESSAGE })); } wrap.append(statLine); if (entry.truncated) wrap.append(h("div", { class: "change-diff-note muted", text: TRUNCATED_PATCH_NOTE })); for (const hunk of parsed.hunks) wrap.append(renderHunk(hunk)); return wrap; } /** * One `@@` hunk: its header on a raised surface, then its lines in a * horizontally scrollable container, each with its old/new gutter numbers (blank * on the absent side and on a `\ No newline` marker) and the shared * `{symbol} {text}` coloured by kind. */ function renderHunk(hunk) { const width = gutterWidth(hunk); const wrap = h("div", { class: "change-hunk" }); wrap.append(h("div", { class: "change-hunk-head", text: hunk.header })); const lines = h("div", { class: "change-hunk-lines" }); for (const line of hunk.lines) { const gutter = line.noNewlineMarker ? " ".repeat(width * 2 + 1) : `${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}`; lines.append( h( "div", { class: "change-line" }, h("span", { class: "change-gutter", text: gutter }), h("span", { class: `change-text ${diffLineClass(line.kind)}`, text: `${diffLineSymbol(line.kind)} ${line.text}` }), ), ); } wrap.append(lines); return wrap; } /** Copy arbitrary text (the raw patch) to the clipboard, best effort. */ async function copyText(text) { if (!text || !canCopyLink()) return; try { await navigator.clipboard.writeText(text); } catch { // Clipboard permission may be denied; the patch is still readable. } } /** The Timeline tab: one compact row per visit, in step order. */ function renderRunTimelineTab(d) { const wrap = h("div", { class: "run-tab-body" }); const timeline = runTimeline(d.steps ?? []); if (!timeline.entries.length) { wrap.append(h("div", { class: "run-empty muted", text: EMPTY_TIMELINE_MESSAGE })); return wrap; } const list = h("div", { class: "timeline" }); for (const entry of timeline.entries) list.append(renderTimelineRow(entry)); wrap.append(list); return wrap; } /** * One timeline row: a stage-outcome glyph, the `{stage} · visit {n}` line with * the outcome chip, a paperclip when the visit recorded artifacts, the duration, * and the one-line description. Clicking (or Enter/Space) opens the stage pane. */ function renderTimelineRow(entry) { const state_ = runStateOf(entry.outcomeLabel); const chipLabel = entry.outcomeLabel || state_.label; const tone = outcomeClass(entry.step.outcome, entry.step.status); const open = () => openStagePane(entry.stageKey, entry.visitIndex); const row = h("div", { class: "timeline-row", role: "button", tabindex: "0", "data-stage-key": entry.stageKey, "data-visit-index": String(entry.visitIndex), }); row.addEventListener("click", open); row.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); open(); } }); row.append(h("span", { class: `timeline-glyph ${tone}`, text: stateGlyph(state_) })); const head = h("div", { class: "timeline-head" }); head.append(h("span", { class: "timeline-title", text: `${entry.stageKey} · visit ${entry.visit}` })); head.append(h("span", { class: `outcome-chip ${tone}`, text: chipLabel })); if (entry.hasArtifacts) { head.append( h("span", { class: "timeline-paperclip", title: "Recorded artifacts", "aria-label": "has recorded artifacts", text: "\u{1F4CE}" }), ); } if (entry.duration) head.append(h("span", { class: "timeline-duration muted", text: entry.duration })); const body = h("div", { class: "timeline-main" }, head); if (entry.description) body.append(h("span", { class: "timeline-desc muted", text: entry.description })); row.append(body); return row; } /** A CSS class naming a stage-outcome colour (status palette, else flow). */ function outcomeClass(outcome, status) { const [kind, value] = outcomeColorToken(outcome, status).split(" "); return `outcome-${kind}-${value}`; } // --- Stage pane ------------------------------------------------------------ /** * The stage pane: a closable dialog for one visit, opened from a timeline row. * It leads with the verdict block (when the server recorded one), then the * always-visible headline rows, then the visit's collapsible sections in the * Android order (Artifacts, Session, Output, Input, This run, Stage definition). * Escape, the Back button and a backdrop click close it. */ function renderStagePane(d) { const stageKey = state.runStagePane.stageKey; const timeline = runTimeline(d.steps ?? []); const runSteps = timeline.visitsByStage.get(stageKey) ?? []; const visitIndex = clampVisitIndex(state.runStagePane.visitIndex, runSteps.length); const step = runSteps[visitIndex] ?? null; const graph = d.graph ?? { stages: [] }; const specs = stageSectionSpecs(stageKey, graph, runSteps, visitIndex, true); const fields = step ? runStepFields(step) : []; const headline = headlineFields(fields); const overlay = h("div", { class: "stage-pane", role: "dialog", "aria-modal": "true", "aria-label": nodeLabel(stageKey), }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeStagePane(); }); const bar = h( "div", { class: "stage-pane-bar" }, h("button", { class: "stage-pane-back", type: "button", "aria-label": "Back", text: "\u2190 Back", onclick: closeStagePane, }), h( "div", { class: "stage-pane-titles" }, h("span", { class: "stage-pane-title", text: nodeLabel(stageKey) }), h("span", { class: "stage-pane-run muted", text: runLabelFor(d) }), ), ); const body = h("div", { class: "stage-pane-body" }); if (step) { const verdict = renderVerdictBlock(step); if (verdict) body.append(verdict); } for (const field of headline) body.append(renderStageField(field)); if (headline.length === 0 && specs.length === 0) { body.append(h("div", { class: "run-empty muted", text: NO_STAGE_DETAILS_MESSAGE })); } for (const spec of specs) body.append(renderStageSection(spec, step)); overlay.append(h("div", { class: "stage-pane-sheet" }, bar, body)); return overlay; } /** One stage-pane section, using the pane's own expansion state. */ function renderStageSection(spec, step) { const expanded = state.runStageSections.has(spec.key); const wrap = h("div", { class: "collapsible stage-section" }); wrap.append( h( "button", { class: "section-toggle", type: "button", "aria-expanded": expanded ? "true" : "false", onclick: () => { state.runStageSections = new Set(state.runStageSections); if (state.runStageSections.has(spec.key)) state.runStageSections.delete(spec.key); else state.runStageSections.add(spec.key); renderContent(); }, }, h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), h("span", { class: "section-title", text: spec.title }), ), ); if (!expanded) return wrap; const body = h("div", { class: "section-body" }); if (spec.artifacts && step) body.append(renderVisitArtifacts(step)); else if (spec.session && step) body.append(renderSessionExport(step)); else for (const field of spec.fields) body.append(renderStageField(field)); wrap.append(body); return wrap; } /** * The verdict block: heading "Verdict", the option as an outcome-coloured chip, * the reason as body text with inline artifact links, and the referenced * artifacts as compact chips. Nothing renders when the server recorded no * option and no reason. */ function renderVerdictBlock(step) { const verdict = step.verdict; if (!verdict) return null; const option = String(verdict.option ?? ""); const reason = String(verdict.reason ?? ""); if (option.trim() === "" && reason.trim() === "") return null; const wrap = h("div", { class: "verdict" }); const head = h("div", { class: "verdict-head" }, h("span", { class: "verdict-title", text: "Verdict" })); if (option.trim() !== "") { head.append(h("span", { class: `outcome-chip ${outcomeClass(step.outcome, step.status)}`, text: option })); } wrap.append(head); const references = referencedVerdictArtifacts(verdict, presentedArtifacts(step)); if (reason.trim() !== "") { const body = h("p", { class: "verdict-reason" }); for (const segment of verdictReasonSegments(reason, references)) { if (!segment.artifact) body.append(document.createTextNode(segment.text)); else body.append(renderVerdictLink(segment.text, segment.artifact, step)); } wrap.append(body); } if (references.length) { const refs = h("div", { class: "verdict-refs" }); for (const artifact of references) refs.append(renderVerdictRef(artifact, step)); wrap.append(refs); } return wrap; } /** One inline artifact reference in a verdict reason (media opens the viewer). */ function renderVerdictLink(text, artifact, step) { const resolved = resolvedArtifactUrl(artifact, state.url); if (!resolved) return h("span", { class: "verdict-link disabled", text }); const link = h("a", { class: "verdict-link", href: resolved, target: "_blank", rel: "noreferrer", text }); link.addEventListener("click", (event) => { event.preventDefault(); openArtifactFromVerdict(artifact, step, resolved); }); return link; } /** One compact chip naming a referenced artifact. */ function renderVerdictRef(artifact, step) { const resolved = resolvedArtifactUrl(artifact, state.url); const chip = h("button", { class: "verdict-ref", type: "button", text: artifact.name || "(unnamed artifact)", }); chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved)); return chip; } /** Open a referenced artifact: media in the viewer, everything else externally. */ function openArtifactFromVerdict(artifact, step, resolved) { if (!resolved) return; const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts: presentedArtifacts(step) }; const viewable = pagedArtifacts([group]); const viewerIndexOf = viewerIndexByUrl([group]); const at = viewerIndexOf.get(artifact.url); const kind = artifactKind(artifact.content_type, artifact.name); const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video; if (media && at != null) openArtifactViewer(viewable, at); else window.open(resolved, "_blank", "noopener,noreferrer"); } /** Open the stage pane for one visit of a stage and move focus into it. */ function openStagePane(stageKey, visitIndex) { state.runStagePane = { stageKey, visitIndex }; state.runStageSections = new Set(); renderContent(); document.querySelector(".stage-pane-back")?.focus(); } /** Close the stage pane, returning focus to the timeline row that opened it. */ function closeStagePane() { const closing = state.runStagePane; if (!closing) return; state.runStagePane = null; state.runStageSections = new Set(); renderContent(); const row = [...document.querySelectorAll(".timeline-row")].find( (node) => node.dataset.stageKey === closing.stageKey && node.dataset.visitIndex === String(closing.visitIndex), ); // A pane opened from the Timeline returns to its row; one opened from the Graph // returns to the stage node that opened it (there is no timeline row then). const focusTarget = row ?? [...document.querySelectorAll(".graph-node")].find( (candidate) => candidate.dataset.key === closing.stageKey, ); focusTarget?.focus(); } // --- Run-level operator actions (R11–R14) ---------------------------------- /** The one-line error text of a refused action (the server's own message). */ function describeError(error) { return error?.message || String(error); } /** * The decision card (R11): a prominent "Waiting for your decision" banner with * the stage/run identity and a deliberate Decide action. Only rendered when the * loaded run is genuinely waiting on a person. */ function renderDecisionCard(decision) { const card = h("div", { class: "decision-card" }); card.append(h("span", { class: "decision-card-icon", "aria-hidden": "true", text: "\u270B" })); const text = h("div", { class: "decision-card-text" }); text.append(h("div", { class: "decision-card-title", text: DECISION_CARD_TITLE })); text.append(h("div", { class: "decision-card-meta muted", text: decisionCardMeta(decision) })); card.append(text); card.append( h("button", { class: "decision-open", type: "button", text: DECISION_ACTION, onclick: () => openDecisionSheet(decision), }), ); return card; } /** Cancel/Retry actions, shown exactly per the app's eligibility rules. */ function renderRunActions(d) { const buttons = []; if (canCancel(d)) { buttons.push( h("button", { class: "run-action cancel-run", type: "button", text: "Cancel run", onclick: () => openConfirm({ kind: "cancel", runId: d.id }), }), ); } if (canRetry(d)) { buttons.push( h("button", { class: "run-action retry-run", type: "button", text: "Retry", onclick: () => openConfirm({ kind: "retry", runId: d.id }), }), ); } if (!buttons.length) return null; return h("div", { class: "run-actions" }, ...buttons); } /** Open the decision sheet with a fresh draft; nothing is sent until Confirm. */ function openDecisionSheet(decision) { state.runDecision = decision; state.decisionOpen = true; state.decisionDraft = new DecisionDraft(); state.decisionError = ""; renderContent(); document.querySelector(".decision-sheet .decision-option")?.focus(); } /** Dismiss the decision sheet (never while a decision is in flight). */ function closeDecisionSheet() { if (state.decisionSending) return; const wasOpen = state.decisionOpen; state.decisionOpen = false; state.runDecision = null; state.decisionError = ""; state.decisionDraft = new DecisionDraft(); if (!wasOpen) return; renderContent(); document.querySelector(".decision-card .decision-open")?.focus(); } /** * The decision sheet (R11): the waiting stage, the author's recorded * instructions, one selectable row per option (with its resolved target when * declared), the optional feedback field and the deliberate confirm. Selecting a * row never sends; a refusal keeps the sheet open with the server's exact reason. */ function renderDecisionSheet(decision) { const overlay = h("div", { class: "decision-sheet", role: "dialog", "aria-modal": "true", "aria-label": decisionSheetTitle(decision.stageKey), }); overlay.addEventListener("click", (event) => { if (event.target === overlay) closeDecisionSheet(); }); const sheet = h("div", { class: "decision-sheet-panel" }); sheet.append(h("h2", { class: "decision-sheet-title", text: decisionSheetTitle(decision.stageKey) })); sheet.append(h("div", { class: "decision-sheet-meta muted", text: decisionSheetMeta(decision) })); if (String(decision.instructions ?? "").trim() !== "") { sheet.append(h("p", { class: "decision-instructions", text: decision.instructions })); } const options = h("div", { class: "decision-options", role: "radiogroup", "aria-label": "Options" }); for (const option of decision.options) { const selected = state.decisionDraft.selected === option.key; const row = h("button", { class: `decision-option${selected ? " selected" : ""}`, type: "button", role: "radio", "aria-checked": selected ? "true" : "false", "data-option": option.key, onclick: () => { state.decisionDraft = state.decisionDraft.select(option.key); renderContent(); }, }); row.append(h("span", { class: "decision-radio", "aria-hidden": "true" })); const body = h("span", { class: "decision-option-body" }); body.append(h("span", { class: "decision-option-key", text: option.key })); const target = optionTargetText(option.target); if (target !== "") body.append(h("span", { class: "decision-option-target muted", text: target })); row.append(body); options.append(row); } sheet.append(options); const field = h("label", { class: "decision-field" }); field.append(h("span", { class: "decision-field-label", text: FEEDBACK_LABEL })); field.append( h("input", { class: "decision-feedback", type: "text", value: state.decisionDraft.feedback, spellcheck: "false", oninput: (event) => { state.decisionDraft = state.decisionDraft.withFeedback(event.target.value); }, }), ); sheet.append(field); if (state.decisionError) sheet.append(h("div", { class: "decision-error bad", text: state.decisionError })); const actions = h("div", { class: "decision-sheet-actions" }); actions.append( h("button", { class: "ghost decision-cancel", type: "button", text: DECISION_CANCEL, disabled: state.decisionSending, onclick: closeDecisionSheet, }), ); actions.append( h("button", { class: "decision-confirm", type: "button", text: state.decisionSending ? DECISION_SENDING : DECISION_CONFIRM, disabled: !state.decisionDraft.canSubmit || state.decisionSending, onclick: () => confirmDecision(decision), }), ); sheet.append(actions); overlay.append(sheet); return overlay; } /** Send the chosen decision; on refusal show the server's reason and re-read. */ async function confirmDecision(decision) { if (state.decisionSending || !state.decisionDraft.canSubmit) return; const option = state.decisionDraft.selected; state.decisionSending = true; state.decisionError = ""; renderContent(); try { await repo.decideRun(decision.runId, { stage: decision.stageKey, option, feedback: state.decisionDraft.feedback, }); state.decisionSending = false; state.decisionOpen = false; state.runDecision = null; state.decisionDraft = new DecisionDraft(); await selectRun(decision.runId, { silent: true }); } catch (error) { state.decisionSending = false; state.decisionError = describeError(error); await selectRun(decision.runId, { silent: true }); } renderContent(); } /** Open one of the shared confirm dialogs (cancel / retry / restart). */ function openConfirm(kind) { state.confirmKind = kind; renderContent(); } function dismissConfirm() { state.confirmKind = null; renderContent(); } /** * The shared confirm dialog: the exact Android title/message for cancel and * retry (with Keep as the dismiss), plus the browser-only "Restart from start" * secondary confirm that plainly states the whole-pipeline replay. The dismiss * button is "Keep". */ function renderConfirmDialog(d) { const kind = state.confirmKind; if (!kind) return null; const runId = kind.runId ?? d.id; let title; let message; let confirmLabel; let secondary = null; if (kind.kind === "cancel") { title = cancelDialogTitle(runId); message = CANCEL_DIALOG_MESSAGE; confirmLabel = CANCEL_CONFIRM; } else if (kind.kind === "retry") { title = retryDialogTitle(runId); message = RETRY_DIALOG_MESSAGE; confirmLabel = RETRY_CONFIRM; secondary = { label: RESTART_CONFIRM, next: { kind: "restart", runId } }; } else { title = restartDialogTitle(runId); message = RESTART_DIALOG_MESSAGE; confirmLabel = RESTART_CONFIRM; } const overlay = h("div", { class: `confirm-dialog confirm-${kind.kind}`, role: "dialog", "aria-modal": "true", "aria-label": title, }); overlay.addEventListener("click", (event) => { if (event.target === overlay) dismissConfirm(); }); const panel = h("div", { class: "confirm-panel" }); panel.append(h("h2", { class: "confirm-title", text: title })); panel.append(h("p", { class: "confirm-message", text: message })); const actions = h("div", { class: "confirm-actions" }); if (secondary) { actions.append( h("button", { class: "ghost confirm-secondary", type: "button", text: secondary.label, onclick: () => openConfirm(secondary.next), }), ); } actions.append( h("button", { class: "ghost confirm-dismiss", type: "button", text: DISMISS_KEEP, onclick: dismissConfirm, }), ); actions.append( h("button", { class: "confirm-accept", type: "button", text: confirmLabel, onclick: () => acceptConfirm(kind), }), ); panel.append(actions); overlay.append(panel); return overlay; } /** * Run the confirmed action, then a silent get_run refresh — exactly as the * Android client does. A server refusal is reported through the one shared * Action-failed dialog. */ async function acceptConfirm(kind) { const runId = kind.runId ?? state.runDetail?.id; state.confirmKind = null; renderContent(); try { if (kind.kind === "cancel") { await repo.cancelRun(runId); } else { const mode = kind.kind === "restart" ? "restart" : "resume"; await repo.retryRun(runId, { mode, requestKey: retryRequestKey(runId) }); } } catch (error) { state.actionError = describeError(error); } await selectRun(runId, { silent: true }); renderContent(); } /** The one shared "Action failed" dialog (title, the server's message, OK). */ function renderActionFailedDialog() { const overlay = h("div", { class: "action-failed", role: "dialog", "aria-modal": "true", "aria-label": ACTION_FAILED_TITLE, }); overlay.addEventListener("click", (event) => { if (event.target === overlay) dismissActionError(); }); const panel = h("div", { class: "action-failed-panel" }); panel.append(h("h2", { class: "action-failed-title", text: ACTION_FAILED_TITLE })); panel.append(h("p", { class: "action-failed-message", text: state.actionError })); panel.append( h("button", { class: "action-failed-ok", type: "button", text: ACTION_FAILED_OK, onclick: dismissActionError }), ); overlay.append(panel); return overlay; } function dismissActionError() { state.actionError = ""; renderContent(); } /** The Summary title row: the run's label plus the inline rename control (R14). */ function renderRunTitleRow(d) { const row = h("div", { class: "run-title-row" }); row.append(h("h2", { class: "run-detail-title", text: runLabelFor(d) })); if (state.renameValue == null) { row.append( h("button", { class: "ghost rename-open", type: "button", text: RENAME_ACTION, onclick: () => { state.renameValue = String(d.title ?? ""); renderContent(); }, }), ); return row; } const field = h("div", { class: "rename-field" }); field.append( h("input", { class: "rename-input", type: "text", value: state.renameValue, "aria-label": RENAME_FIELD_LABEL, oninput: (event) => { state.renameValue = event.target.value; }, }), ); field.append( h("button", { class: "rename-save", type: "button", text: RENAME_SAVE, onclick: () => saveRunTitle(d.id), }), ); field.append( h("button", { class: "ghost rename-cancel", type: "button", text: RENAME_CANCEL, onclick: () => { state.renameValue = null; renderContent(); }, }), ); row.append(field); return row; } /** * Rename the run: send `set_run_title`, then update the run detail and the runs * list row. A refusal (for example a blank title) keeps the field open and shows * the server's exact reason through the shared Action-failed dialog. */ async function saveRunTitle(id) { if (state.renameBusy) return; state.renameBusy = true; try { const detail = await repo.setRunTitle(id, String(state.renameValue ?? "")); state.renameValue = null; applyRunTitle(id, detail); await selectRun(id, { silent: true }); } catch (error) { state.actionError = describeError(error); renderContent(); } finally { state.renameBusy = false; } } /** Apply a renamed run to the loaded detail and the runs-list row. */ function applyRunTitle(id, detail) { if (state.runDetail && state.runDetail.id === id && detail) state.runDetail = detail; const title = String(detail?.title ?? ""); state.runs = state.runs.map((run) => (run.id === id ? { ...run, title } : run)); } /** Whether the configured server URL can resolve a server-relative artifact. */ function artifactsResolvable() { return resolveArtifactUrl(state.url, "/artifacts/0/0/probe") != null; } /** * The run-level gallery: one header per (stage, visit) and one grid of tiles per * visit, in the gallery order (stages first-appearance, visits by sequence). A * run with no artifacts shows the header (which already says why) and nothing * else, so the section is never blank. */ function renderArtifactGallery(steps) { const wrap = h("div", { class: "artifact-gallery" }); const groups = artifactGroups(steps); if (!groups.length) return wrap; if (!artifactsResolvable()) { wrap.append(h("div", { class: "muted artifact-hint", text: ARTIFACT_SERVER_HINT })); } const viewable = pagedArtifacts(groups); const viewerIndexOf = viewerIndexByUrl(groups); for (const group of groups) { wrap.append( h("div", { class: "artifact-group-head", text: `${group.stageKey} · visit ${group.visit}` }), renderArtifactGrid(group.artifacts, viewable, viewerIndexOf), ); } return wrap; } /** * The per-visit artifacts section shown inside one step: the summary line, the * capture notes, the no-server-URL hint and a headerless grid of that visit's * tiles (matching the Android ArtifactsSection). Its viewer pages only through * that visit's media, exactly as the Android section does. */ function renderVisitArtifacts(step) { const wrap = h("div", { class: "artifacts" }); wrap.append(h("div", { class: "artifacts-summary", text: artifactsSummary(step) })); for (const note of artifactCaptureNotes(step)) { wrap.append(h("div", { class: "artifacts-note muted", text: note })); } const artifacts = presentedArtifacts(step); if (artifacts.length) { if (!artifactsResolvable()) { wrap.append(h("div", { class: "muted artifact-hint", text: ARTIFACT_SERVER_HINT })); } const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts }; wrap.append( renderArtifactGrid(artifacts, pagedArtifacts([group]), viewerIndexByUrl([group])), ); } return wrap; } /** One visit's tiles in a CSS grid. */ function renderArtifactGrid(artifacts, viewable, viewerIndexOf) { const grid = h("div", { class: "artifact-grid" }); for (const artifact of artifacts) { grid.append(renderArtifactTile(artifact, viewable, viewerIndexOf)); } return grid; } /** * One gallery tile: an image thumbnail, a video poster with a play marker (never * a