5415 lines
182 KiB
JavaScript
5415 lines
182 KiB
JavaScript
// 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 } from "./repository.js";
|
||
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
|
||
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
|
||
import {
|
||
ForegroundAction,
|
||
bannerState,
|
||
foregroundAction,
|
||
liveBadgeState,
|
||
protocolMismatch,
|
||
serverBuildLabel,
|
||
stateBadge,
|
||
} from "./connection.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 {
|
||
CHAT_EMPTY,
|
||
CHAT_FOLLOW_THRESHOLD_PX,
|
||
CHAT_LOADING,
|
||
CHAT_NEW_ACTION,
|
||
CHAT_NO_MATCH_ACTION,
|
||
CHAT_SEARCH_LABEL,
|
||
CHAT_TAB_TITLE,
|
||
CLOSED_CHIP_LABEL,
|
||
CLOSED_SECTION_LABEL,
|
||
CLOSE_CHAT_ACTION,
|
||
CLOSE_CHAT_CONFIRM,
|
||
CLOSE_CHAT_DISMISS,
|
||
CLOSE_CHAT_TITLE,
|
||
CONVERSATION_EMPTY,
|
||
CONVERSATION_LOADING,
|
||
LOAD_OLDER_ACTION,
|
||
REOPEN_ACTION,
|
||
SELECT_CHAT_HINT,
|
||
applyChatEvent,
|
||
chatBottomDistancePx,
|
||
chatFirstScroll,
|
||
chatFollowsAt,
|
||
chatHeaderMeta,
|
||
chatNoMatchMessage,
|
||
chatOpensAtNewest,
|
||
chatShowJumpToLatest,
|
||
chatStreamState,
|
||
closeChatConfirmation,
|
||
directoryLabel,
|
||
filterSessions,
|
||
groupSessionsByDirectory,
|
||
historyResync,
|
||
mergeHistoryPage,
|
||
newChatThread,
|
||
reasoningLabel,
|
||
runningToolElapsedMillis,
|
||
sessionActivity,
|
||
sessionActivityBadge,
|
||
sessionChipLabel,
|
||
sessionMeta,
|
||
sessionStatusLabel,
|
||
sessionTitle,
|
||
sessionWorkLabel,
|
||
settledThread,
|
||
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";
|
||
|
||
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
|
||
|
||
/**
|
||
* 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";
|
||
|
||
/** 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);
|
||
|
||
const state = {
|
||
view: "pipelines",
|
||
url: localStorage.getItem(STORAGE_KEY) ?? defaultServerUrl(),
|
||
connection: client.state,
|
||
// 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,
|
||
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(),
|
||
};
|
||
|
||
let runPoll = null;
|
||
|
||
// 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);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// 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;
|
||
}
|
||
|
||
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) => {
|
||
state.url = e.target.value;
|
||
},
|
||
}),
|
||
];
|
||
// 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),
|
||
h("span", { class: "spacer" }),
|
||
h("button", { class: "ghost", text: "Refresh", onclick: () => loadCurrentView(true) }),
|
||
),
|
||
);
|
||
|
||
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();
|
||
},
|
||
});
|
||
}
|
||
|
||
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({ executing: state.runs.some((run) => run.executing) }, state.connection)),
|
||
);
|
||
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(d, state.connection)));
|
||
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 <video> element or autoplay), or a kind/name/size label. Every server string
|
||
* is set as text, never as markup.
|
||
*/
|
||
function renderArtifactTile(artifact, viewable, viewerIndexOf) {
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
const kind = artifactKind(artifact.content_type, artifact.name);
|
||
const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video;
|
||
const name = artifact.name || "(unnamed artifact)";
|
||
const tile = h("div", { class: "artifact-tile clickable" });
|
||
const openViewer = () => {
|
||
const at = viewerIndexOf.get(artifact.url);
|
||
if (at != null) openArtifactViewer(viewable, at);
|
||
};
|
||
const openTab = () => {
|
||
if (resolved) window.open(resolved, "_blank", "noopener,noreferrer");
|
||
};
|
||
if (kind === ArtifactKind.Image) {
|
||
const img = h("img", { class: "artifact-thumb", alt: name, loading: "lazy" });
|
||
if (resolved) img.src = resolved;
|
||
tile.append(img);
|
||
tile.addEventListener("click", openViewer);
|
||
} else if (kind === ArtifactKind.Video) {
|
||
tile.append(h("div", { class: "artifact-poster" }, h("span", { class: "artifact-play", text: "▶" })));
|
||
tile.append(h("div", { class: "artifact-name", text: name }));
|
||
tile.addEventListener("click", openViewer);
|
||
} else {
|
||
tile.append(
|
||
h("div", { class: "artifact-kind", text: artifactKindLabel(kind) }),
|
||
h("div", { class: "artifact-name", text: name }),
|
||
h("div", { class: "artifact-size", text: humanBytes(artifact.size_bytes) }),
|
||
);
|
||
tile.addEventListener("click", openTab);
|
||
}
|
||
tile.append(renderTileActions(resolved, media));
|
||
return tile;
|
||
}
|
||
|
||
/** The compact per-tile actions: copy-link (non-media tiles) and share. */
|
||
function renderTileActions(resolved, media) {
|
||
const actions = h("div", { class: "artifact-actions" });
|
||
const stop = (fn) => (event) => {
|
||
event.stopPropagation();
|
||
fn();
|
||
};
|
||
if (!media) {
|
||
actions.append(
|
||
h("button", {
|
||
class: "artifact-action",
|
||
type: "button",
|
||
text: "Copy link",
|
||
disabled: !resolved || !canCopyLink(),
|
||
onclick: stop(() => copyArtifactLink(resolved)),
|
||
}),
|
||
);
|
||
}
|
||
actions.append(
|
||
h("button", {
|
||
class: "artifact-action",
|
||
type: "button",
|
||
text: "Share",
|
||
disabled: !resolved || !canShare(),
|
||
onclick: stop(() => shareArtifact(resolved)),
|
||
}),
|
||
);
|
||
return actions;
|
||
}
|
||
|
||
function canCopyLink() {
|
||
return typeof navigator !== "undefined" && Boolean(navigator.clipboard?.writeText);
|
||
}
|
||
|
||
function canShare() {
|
||
return typeof navigator !== "undefined" && typeof navigator.share === "function";
|
||
}
|
||
|
||
async function copyArtifactLink(resolved) {
|
||
if (!resolved || !canCopyLink()) return;
|
||
try {
|
||
await navigator.clipboard.writeText(resolved);
|
||
} catch {
|
||
// Clipboard permission may be denied; the link is still openable.
|
||
}
|
||
}
|
||
|
||
async function shareArtifact(resolved) {
|
||
if (!resolved || !canShare()) return;
|
||
try {
|
||
await navigator.share({ url: resolved });
|
||
} catch {
|
||
// The share chooser may be dismissed.
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The step's session export: a link opening the read-only session.html in a new
|
||
* tab, or the plain notice when the visit exported nothing (parity R9).
|
||
*/
|
||
function renderSessionExport(step) {
|
||
const file = sessionExportArtifact(step);
|
||
const wrap = h("div", { class: "session-export" });
|
||
if (!file) {
|
||
wrap.append(h("span", { class: "muted", text: "No session was exported for this visit." }));
|
||
return wrap;
|
||
}
|
||
const href = resolvedArtifactUrl(file, state.url);
|
||
if (href) {
|
||
wrap.append(
|
||
h("a", {
|
||
class: "session-link",
|
||
href,
|
||
target: "_blank",
|
||
rel: "noreferrer",
|
||
text: `Open ${file.name || "session.html"}`,
|
||
}),
|
||
);
|
||
} else {
|
||
wrap.append(
|
||
h("span", { class: "muted", text: "Set the server URL in Settings to open the session." }),
|
||
);
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
let viewerOverlay = null;
|
||
let viewerKeydown = null;
|
||
|
||
/** Close the full-screen viewer and remove its Escape listener. */
|
||
function closeArtifactViewer() {
|
||
if (viewerKeydown) {
|
||
document.removeEventListener("keydown", viewerKeydown);
|
||
viewerKeydown = null;
|
||
}
|
||
viewerOverlay?.remove();
|
||
viewerOverlay = null;
|
||
}
|
||
|
||
/**
|
||
* Open the full-screen viewer at `startIndex` into `viewable`, the same ordered
|
||
* media list the grid drew. Previous/Next are disabled at the ends and absent for
|
||
* a single artifact; Escape and a backdrop click close it. Nothing autoplays: a
|
||
* non-image artifact shows a still poster placeholder instead.
|
||
*/
|
||
function openArtifactViewer(viewable, startIndex) {
|
||
closeArtifactViewer();
|
||
if (!viewable?.length) return;
|
||
let index = pagedIndex(startIndex, 0, viewable.length);
|
||
const overlay = h("div", {
|
||
class: "artifact-viewer",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": "Artifact viewer",
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) closeArtifactViewer();
|
||
});
|
||
|
||
const renderViewer = () => {
|
||
const artifact = viewable[index] ?? {};
|
||
const resolved = resolvedArtifactUrl(artifact, state.url);
|
||
const kind = artifactKind(artifact.content_type, artifact.name);
|
||
const name = artifact.name || "(unnamed artifact)";
|
||
|
||
const board = h("div", { class: "viewer-board" });
|
||
if (kind === ArtifactKind.Image && resolved) {
|
||
board.append(h("img", { class: "viewer-image", src: resolved, alt: name }));
|
||
} else {
|
||
board.append(
|
||
h(
|
||
"div",
|
||
{ class: "viewer-placeholder" },
|
||
h("span", { class: "artifact-play", text: "▶" }),
|
||
h("span", { class: "viewer-placeholder-name", text: name }),
|
||
),
|
||
);
|
||
}
|
||
|
||
const head = h(
|
||
"div",
|
||
{ class: "viewer-head" },
|
||
h("div", { class: "viewer-title", text: name }),
|
||
h("div", {
|
||
class: "viewer-position muted",
|
||
text: artifactViewerPositionLabel(index, viewable.length, artifact.content_type),
|
||
}),
|
||
);
|
||
|
||
const actions = h("div", { class: "viewer-actions" });
|
||
if (resolved) {
|
||
actions.append(
|
||
h("button", {
|
||
class: "viewer-action",
|
||
type: "button",
|
||
text: "Open",
|
||
onclick: () => window.open(resolved, "_blank", "noopener,noreferrer"),
|
||
}),
|
||
h("button", {
|
||
class: "viewer-action",
|
||
type: "button",
|
||
text: "Copy link",
|
||
disabled: !canCopyLink(),
|
||
onclick: () => copyArtifactLink(resolved),
|
||
}),
|
||
h("button", {
|
||
class: "viewer-action",
|
||
type: "button",
|
||
text: "Share",
|
||
disabled: !canShare(),
|
||
onclick: () => shareArtifact(resolved),
|
||
}),
|
||
);
|
||
}
|
||
actions.append(
|
||
h("button", {
|
||
class: "viewer-action viewer-close",
|
||
type: "button",
|
||
text: "Close viewer",
|
||
onclick: closeArtifactViewer,
|
||
}),
|
||
);
|
||
|
||
const nodes = [head, board];
|
||
if (viewable.length > 1) {
|
||
nodes.push(
|
||
h(
|
||
"div",
|
||
{ class: "viewer-nav" },
|
||
h("button", {
|
||
class: "viewer-page",
|
||
type: "button",
|
||
text: "Previous artifact",
|
||
disabled: pagedIndex(index, -1, viewable.length) === index,
|
||
onclick: () => {
|
||
index = pagedIndex(index, -1, viewable.length);
|
||
renderViewer();
|
||
},
|
||
}),
|
||
h("button", {
|
||
class: "viewer-page",
|
||
type: "button",
|
||
text: "Next artifact",
|
||
disabled: pagedIndex(index, 1, viewable.length) === index,
|
||
onclick: () => {
|
||
index = pagedIndex(index, 1, viewable.length);
|
||
renderViewer();
|
||
},
|
||
}),
|
||
),
|
||
);
|
||
}
|
||
nodes.push(actions);
|
||
overlay.replaceChildren(...nodes);
|
||
};
|
||
|
||
renderViewer();
|
||
document.body.append(overlay);
|
||
viewerOverlay = overlay;
|
||
viewerKeydown = (event) => {
|
||
if (event.key === "Escape") closeArtifactViewer();
|
||
};
|
||
document.addEventListener("keydown", viewerKeydown);
|
||
}
|
||
|
||
/** A key/value row whose value is monospace (a key, an id) rather than prose. */
|
||
function kvMono(key, value) {
|
||
return h(
|
||
"div",
|
||
{ class: "kv-row" },
|
||
h("span", { class: "kv-key", text: key }),
|
||
h("span", { class: "kv-val" }, h("code", { text: value })),
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Chat (C1 · C3 · C4 · C7 · C14)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/** The persisted per-session scroll positions, or an empty map when unreadable. */
|
||
function readChatScrollStore() {
|
||
try {
|
||
const parsed = JSON.parse(localStorage.getItem(CHAT_SCROLL_STORAGE_KEY) ?? "{}");
|
||
return parsed && typeof parsed === "object" ? parsed : {};
|
||
} catch {
|
||
return {};
|
||
}
|
||
}
|
||
|
||
/** Remember one conversation's scroll position (index of the first visible row). */
|
||
function saveChatScroll(sessionId, position) {
|
||
if (!sessionId) return;
|
||
state.chatScroll[sessionId] = { index: position.index, offset: position.offset };
|
||
try {
|
||
localStorage.setItem(CHAT_SCROLL_STORAGE_KEY, JSON.stringify(state.chatScroll));
|
||
} catch {
|
||
// storage may be full or disabled; the in-memory position still holds
|
||
}
|
||
}
|
||
|
||
/**
|
||
* The pixels the transcript still sits above its end (0 when at the bottom), via
|
||
* the same pure decision the unit tests cover. `chatBottomDistancePx` measures
|
||
* from the last row's bottom edge to the viewport's bottom edge; the live
|
||
* analogue passes the last row as the last visible one.
|
||
*/
|
||
function transcriptDistance(el) {
|
||
if (!el) return null;
|
||
const rows = el.children;
|
||
const count = rows.length;
|
||
if (count === 0) return null;
|
||
const last = rows[count - 1];
|
||
return chatBottomDistancePx({
|
||
lastVisibleIndex: count - 1,
|
||
lastVisibleEndPx: last.offsetTop + last.offsetHeight,
|
||
itemCount: count,
|
||
viewportEndPx: el.scrollTop + el.clientHeight,
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Remember the live transcript's position (and follow intent) just before a
|
||
* re-render replaces it, so `afterChatRender` can put the operator back exactly
|
||
* where they were. A no-op when no transcript is mounted.
|
||
*/
|
||
function captureChatPosition() {
|
||
const el = document.getElementById("chatTranscript");
|
||
if (!el || !el.dataset.session) return;
|
||
state.chatPending = {
|
||
sessionId: el.dataset.session,
|
||
position: currentChatPosition(el),
|
||
following: state.chatFollowing,
|
||
};
|
||
}
|
||
|
||
/** The first visible row's index and the pixels scrolled into it. */
|
||
function currentChatPosition(el) {
|
||
const rows = [...el.children];
|
||
let index = 0;
|
||
let offset = 0;
|
||
for (let i = 0; i < rows.length; i += 1) {
|
||
const row = rows[i];
|
||
if (row.offsetTop + row.offsetHeight > el.scrollTop + 1) {
|
||
index = i;
|
||
offset = Math.max(0, el.scrollTop - row.offsetTop);
|
||
break;
|
||
}
|
||
index = i;
|
||
}
|
||
return { index, offset };
|
||
}
|
||
|
||
/** The list of the server's operator sessions, narrowed by the search field. */
|
||
async function loadChatSessions(force = false) {
|
||
if (state.connection.kind !== "connected") {
|
||
state.chatError = "Connect to the server first.";
|
||
state.chatLoading = false;
|
||
renderContent();
|
||
return;
|
||
}
|
||
if (state.chatLoading) return;
|
||
state.chatLoading = true;
|
||
state.chatError = "";
|
||
renderContent();
|
||
try {
|
||
state.chatSessions = await repo.chatSessions();
|
||
state.chatLoaded = true;
|
||
} catch (error) {
|
||
state.chatError = describeError(error);
|
||
}
|
||
state.chatLoading = false;
|
||
renderContent();
|
||
}
|
||
|
||
/** Open a session: select it, subscribe its stream and load its newest history page. */
|
||
async function openChatSession(id) {
|
||
if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return;
|
||
// Remember where the operator left the conversation being closed.
|
||
const leaving = document.getElementById("chatTranscript");
|
||
if (leaving && state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(leaving));
|
||
state.chatActiveId = id;
|
||
state.chatPlaced = null;
|
||
state.chatFollowing = true;
|
||
state.chatReasoning = new Set();
|
||
state.chatToolPanels = new Set();
|
||
state.chatToolRows = new Set();
|
||
const existing = state.chatThreads.get(id);
|
||
state.chatThreads.set(id, {
|
||
...newChatThread(id),
|
||
...(existing ?? {}),
|
||
loaded: false,
|
||
loading: true,
|
||
error: "",
|
||
});
|
||
renderContent();
|
||
// Attach the shared live stream once per session per connection; its failure is
|
||
// non-fatal — history stays usable and the badge reads "not live".
|
||
subscribeChatSession(id);
|
||
await loadChatHistory(id);
|
||
}
|
||
|
||
/**
|
||
* Attach one session's shared live stream (C5): `chat_subscribe` with the session
|
||
* id as the body. Idempotent per connection — a session already subscribed is not
|
||
* asked for again. A refusal (an older server that does not know the command, or
|
||
* any other error) leaves history usable and the live badge `not live`.
|
||
*/
|
||
async function subscribeChatSession(id) {
|
||
if (!id || state.connection.kind !== "connected") return;
|
||
if (state.chatSubscriptions.has(id)) return;
|
||
try {
|
||
await repo.subscribeChat(id);
|
||
state.chatSubscriptions = new Set(state.chatSubscriptions).add(id);
|
||
} catch {
|
||
// The subscription is not live; nothing else changes. The badge says so.
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Drop the per-connection subscriptions (the server detaches them on close). */
|
||
function clearChatSubscriptions() {
|
||
if (state.chatSubscriptions.size > 0) state.chatSubscriptions = new Set();
|
||
}
|
||
|
||
/**
|
||
* Settle every conversation that was running. A socket drop (or a close) removes
|
||
* the frames feeding the turn, so no thread keeps claiming to run until a fresh
|
||
* frame proves otherwise.
|
||
*/
|
||
function settleChatThreads() {
|
||
for (const [id, thread] of state.chatThreads) {
|
||
if (thread?.running || thread?.queued) state.chatThreads.set(id, settledThread(thread));
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Fold one pushed `chat_event` frame into its conversation. Only a conversation
|
||
* this client has open is folded (a frame for a session nobody opened is
|
||
* ignored); the server only pushes frames for sessions this connection subscribed
|
||
* to, so this is a no-op in practice until a chat is opened.
|
||
*/
|
||
function onChatEvent(frame) {
|
||
const sessionId = String(frame?.session_id ?? "").trim();
|
||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||
const thread = state.chatThreads.get(sessionId);
|
||
state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now()));
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* The reconnect repair (C5): re-attach the open chat's stream and replace its
|
||
* conversation with the newest history page wholesale. Everything the gap could
|
||
* have missed is repaired; a turn that was in flight is settled. Only the open
|
||
* conversation is repaired — the others are not on screen.
|
||
*/
|
||
async function resyncOpenChat() {
|
||
const id = state.chatActiveId;
|
||
if (!id || state.connection.kind !== "connected") return;
|
||
await subscribeChatSession(id);
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
state.chatThreads.set(id, settledThread(previous));
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
state.chatThreads.set(id, historyResync(previous, page));
|
||
} catch {
|
||
// The history refresh failed; the settled thread stands and the badge is honest.
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Load (or reload) a session's newest history page and merge it in. */
|
||
async function loadChatHistory(id) {
|
||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||
try {
|
||
const page = await repo.chatHistory(id);
|
||
state.chatThreads.set(id, { ...previous, ...mergeHistoryPage(previous, page, { older: false }) });
|
||
} catch (error) {
|
||
state.chatThreads.set(id, {
|
||
...previous,
|
||
loading: false,
|
||
loaded: true,
|
||
error: describeError(error),
|
||
});
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Fetch the next opaque older page. Only offered while the server reports
|
||
* `has_more`; the cursor is the server's own `next_cursor`, passed back verbatim
|
||
* and never interpreted. Nothing auto-loads on scroll.
|
||
*/
|
||
async function loadOlderChatHistory(id) {
|
||
const thread = state.chatThreads.get(id);
|
||
if (!thread?.hasMore || thread.loading) return;
|
||
const scroller = document.getElementById("chatTranscript");
|
||
state.chatAnchor = scroller
|
||
? { sessionId: id, scrollHeight: scroller.scrollHeight, scrollTop: scroller.scrollTop }
|
||
: null;
|
||
state.chatThreads.set(id, { ...thread, loading: true });
|
||
renderContent();
|
||
try {
|
||
const page = await repo.chatHistory(id, { cursor: thread.nextCursor });
|
||
const current = state.chatThreads.get(id) ?? thread;
|
||
state.chatThreads.set(id, { ...current, ...mergeHistoryPage(current, page, { older: true }) });
|
||
} catch (error) {
|
||
state.chatThreads.set(id, {
|
||
...(state.chatThreads.get(id) ?? thread),
|
||
loading: false,
|
||
error: describeError(error),
|
||
});
|
||
}
|
||
renderContent();
|
||
}
|
||
|
||
/** Open the Close chat? confirm for [session] (the mutation only on confirm). */
|
||
function openChatClose(session) {
|
||
state.chatClose = session;
|
||
renderContent();
|
||
}
|
||
|
||
function dismissChatClose() {
|
||
state.chatClose = null;
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Run the confirmed close, then refresh the list from the server. The confirm is
|
||
* the only path that mutates the session; the dialog itself never sends.
|
||
*/
|
||
async function acceptChatClose(session) {
|
||
state.chatClose = null;
|
||
state.chatBusy = true;
|
||
renderContent();
|
||
try {
|
||
const { session: updated } = await repo.closeChat(session.id);
|
||
applyChatSessionUpdate(session.id, updated, true);
|
||
// A closed chat's turn was stopped on the server: settle its conversation and
|
||
// stop treating it as a live subscription. Nothing is deleted and it can be
|
||
// reopened from the list.
|
||
const thread = state.chatThreads.get(session.id);
|
||
if (thread) state.chatThreads.set(session.id, settledThread(thread));
|
||
if (state.chatSubscriptions.has(session.id)) {
|
||
state.chatSubscriptions = new Set(state.chatSubscriptions);
|
||
state.chatSubscriptions.delete(session.id);
|
||
}
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
}
|
||
state.chatBusy = false;
|
||
await loadChatSessions();
|
||
}
|
||
|
||
/** Clear a finished chat's closed state again, so it can be resumed. */
|
||
async function reopenChatSession(id) {
|
||
if (state.chatBusy) return;
|
||
state.chatBusy = true;
|
||
renderContent();
|
||
try {
|
||
const { session: updated } = await repo.reopenChat(id);
|
||
applyChatSessionUpdate(id, updated, false);
|
||
} catch (error) {
|
||
state.actionError = describeError(error);
|
||
}
|
||
state.chatBusy = false;
|
||
await loadChatSessions();
|
||
}
|
||
|
||
/** Apply the echoed session (or the local closed flag) to the held row. */
|
||
function applyChatSessionUpdate(id, updated, closed) {
|
||
state.chatSessions = state.chatSessions.map((session) =>
|
||
session.id === id ? { ...session, ...(updated ?? {}), closed } : session,
|
||
);
|
||
}
|
||
|
||
function renderChatList() {
|
||
const list = h("div", { class: "list chat-list" });
|
||
const toolbar = h("div", { class: "list-toolbar chat-toolbar" });
|
||
toolbar.append(
|
||
h("input", {
|
||
id: "chatSearch",
|
||
class: "chat-search",
|
||
type: "text",
|
||
placeholder: CHAT_SEARCH_LABEL,
|
||
"aria-label": CHAT_SEARCH_LABEL,
|
||
value: state.chatQuery,
|
||
spellcheck: "false",
|
||
autocomplete: "off",
|
||
oninput: (event) => {
|
||
state.chatQuery = event.target.value;
|
||
fillChatRows(rows);
|
||
},
|
||
}),
|
||
);
|
||
list.append(toolbar);
|
||
const rows = h("div", { id: "chatRows", class: "chat-rows" });
|
||
fillChatRows(rows);
|
||
list.append(rows);
|
||
return list;
|
||
}
|
||
|
||
/** The list body: the loading/error/empty states or the grouped session rows. */
|
||
function fillChatRows(rows) {
|
||
rows.replaceChildren();
|
||
if (state.chatLoading && state.chatSessions.length === 0 && !state.chatLoaded) {
|
||
rows.append(chatEmpty(CHAT_LOADING));
|
||
return;
|
||
}
|
||
if (state.chatError && state.chatSessions.length === 0) {
|
||
const empty = chatEmpty(state.chatError);
|
||
empty.append(
|
||
h("button", { class: "ghost", type: "button", text: "Retry", onclick: () => loadChatSessions(true) }),
|
||
);
|
||
rows.append(empty);
|
||
return;
|
||
}
|
||
const filtered = filterSessions(state.chatSessions, state.chatQuery);
|
||
if (filtered.length === 0 && state.chatQuery.trim() !== "") {
|
||
const empty = chatEmpty(chatNoMatchMessage(state.chatQuery));
|
||
empty.append(
|
||
h("button", {
|
||
class: "ghost",
|
||
type: "button",
|
||
text: CHAT_NO_MATCH_ACTION,
|
||
onclick: () => {
|
||
state.chatQuery = "";
|
||
renderContent();
|
||
},
|
||
}),
|
||
);
|
||
rows.append(empty);
|
||
return;
|
||
}
|
||
if (filtered.length === 0) {
|
||
// The create path is the C2 item; the action is shown but deliberately not
|
||
// wired here, exactly as the item says.
|
||
const empty = chatEmpty(CHAT_EMPTY);
|
||
empty.append(
|
||
h("button", {
|
||
class: "ghost chat-new",
|
||
type: "button",
|
||
text: CHAT_NEW_ACTION,
|
||
disabled: true,
|
||
title: "Creating a chat lands with the C2 item",
|
||
}),
|
||
);
|
||
rows.append(empty);
|
||
return;
|
||
}
|
||
|
||
const active = filtered.filter((session) => !session.closed);
|
||
const closed = filtered.filter((session) => session.closed);
|
||
const groups = groupSessionsByDirectory(active);
|
||
if (groups.length > 1) {
|
||
for (const group of groups) {
|
||
rows.append(h("div", { class: "chat-group-header", text: directoryLabel(group.directory) }));
|
||
for (const session of group.sessions) rows.append(renderChatRow(session));
|
||
}
|
||
} else {
|
||
for (const session of active) rows.append(renderChatRow(session));
|
||
}
|
||
if (closed.length > 0) {
|
||
rows.append(h("div", { class: "chat-group-header", text: CLOSED_SECTION_LABEL }));
|
||
for (const session of closed) rows.append(renderChatRow(session));
|
||
}
|
||
if (state.chatError) {
|
||
rows.append(h("div", { class: "chat-error muted", text: state.chatError }));
|
||
}
|
||
}
|
||
|
||
function chatEmpty(message) {
|
||
return h("div", { class: "empty" }, h("span", { class: "muted", text: message }));
|
||
}
|
||
|
||
/**
|
||
* One session row: title, kind chip, a Closed chip only when closed, the
|
||
* activity badge word, the work-label meta line and the close/reopen action.
|
||
* Every server string is set with textContent.
|
||
*/
|
||
function renderChatRow(session) {
|
||
const open = state.chatActiveId === session.id;
|
||
const thread = state.chatThreads.get(session.id) ?? null;
|
||
const activity = sessionActivity(thread?.running === true, false);
|
||
const badge = sessionActivityBadge(activity, open);
|
||
const row = h("div", {
|
||
class: `row chat-row${open ? " selected" : ""}`,
|
||
role: "button",
|
||
tabindex: "0",
|
||
"data-session": session.id,
|
||
onclick: () => openChatSession(session.id),
|
||
onkeydown: (event) => {
|
||
// Only the row itself opens on Enter/Space; a nested Close chat…/Reopen
|
||
// button handles its own keyboard activation (and must not double-fire).
|
||
if (event.target !== event.currentTarget) return;
|
||
if (event.key === "Enter" || event.key === " ") {
|
||
event.preventDefault();
|
||
openChatSession(session.id);
|
||
}
|
||
},
|
||
});
|
||
const head = h("div", { class: "row-head" });
|
||
head.append(h("span", { class: "row-title chat-row-title", text: sessionTitle(session) }));
|
||
const chip = sessionChipLabel(session);
|
||
if (chip) head.append(h("span", { class: "chip chat-kind-chip", text: chip }));
|
||
if (session.closed) head.append(h("span", { class: "chip chat-closed-chip", text: CLOSED_CHIP_LABEL }));
|
||
if (badge) {
|
||
head.append(
|
||
h("span", { class: `chat-activity chat-activity-${activity}` },
|
||
h("span", { class: "chat-activity-dot", "aria-hidden": "true" }),
|
||
h("span", { class: "chat-activity-word", text: badge }),
|
||
),
|
||
);
|
||
}
|
||
row.append(head);
|
||
row.append(
|
||
h("span", {
|
||
class: "row-meta chat-row-meta",
|
||
text: sessionMeta(session, sessionWorkLabel(session.busy === true, thread)),
|
||
}),
|
||
);
|
||
const actions = h("div", { class: "chat-row-actions" });
|
||
if (session.closed) {
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost chat-reopen",
|
||
type: "button",
|
||
text: REOPEN_ACTION,
|
||
disabled: state.chatBusy,
|
||
onclick: (event) => {
|
||
event.stopPropagation();
|
||
reopenChatSession(session.id);
|
||
},
|
||
}),
|
||
);
|
||
} else {
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost chat-close",
|
||
type: "button",
|
||
text: CLOSE_CHAT_ACTION,
|
||
disabled: state.chatBusy,
|
||
onclick: (event) => {
|
||
event.stopPropagation();
|
||
openChatClose(session);
|
||
},
|
||
}),
|
||
);
|
||
}
|
||
row.append(actions);
|
||
return row;
|
||
}
|
||
|
||
/** The active conversation: identity, context, transcript and its controls. */
|
||
function renderChatConversation() {
|
||
const pane = h("div", { class: "detail chat-detail" });
|
||
if (!state.chatActiveId) {
|
||
pane.append(chatEmpty(SELECT_CHAT_HINT));
|
||
appendChatDialogs(pane);
|
||
return pane;
|
||
}
|
||
const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null;
|
||
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
|
||
const title = session ? sessionTitle(session) : state.chatActiveId.slice(0, 18);
|
||
|
||
const bar = h("div", { class: "chat-bar" });
|
||
const titles = h("div", { class: "chat-bar-titles" });
|
||
titles.append(h("h2", { class: "chat-bar-title", text: title }));
|
||
const meta = chatHeaderMeta({
|
||
model: session?.model,
|
||
tag: session?.tag,
|
||
directory: session?.directory,
|
||
});
|
||
if (meta !== "") titles.append(h("div", { class: "chat-bar-meta muted", text: meta }));
|
||
bar.append(titles);
|
||
if (thread?.hasMore) {
|
||
bar.append(
|
||
h("button", {
|
||
class: "ghost chat-load-older",
|
||
type: "button",
|
||
text: LOAD_OLDER_ACTION,
|
||
disabled: thread.loading,
|
||
onclick: () => loadOlderChatHistory(state.chatActiveId),
|
||
}),
|
||
);
|
||
}
|
||
pane.append(bar);
|
||
|
||
// The context line: the kind chip, the activity word and directory · model.
|
||
const context = h("div", { class: "chat-context" });
|
||
const chip = session ? sessionChipLabel(session) : null;
|
||
if (chip) context.append(h("span", { class: "chip chat-kind-chip", text: chip }));
|
||
context.append(
|
||
h("span", {
|
||
class: "chat-context-activity",
|
||
text: sessionStatusLabel(thread?.running === true, session?.closed === true),
|
||
}),
|
||
);
|
||
// The live-stream badge (C5): live while this session is subscribed, the same
|
||
// words as the run badge (`live` / `reconnecting` / `not live`).
|
||
context.append(
|
||
renderLiveBadge({
|
||
...chatStreamState(state.connection.kind, state.chatSubscriptions.has(state.chatActiveId)),
|
||
title: "Live chat stream",
|
||
}),
|
||
);
|
||
const contextMeta = [session?.directory, session?.model]
|
||
.map((value) => String(value ?? "").trim())
|
||
.filter((value) => value !== "")
|
||
.join(" · ");
|
||
if (contextMeta !== "") context.append(h("span", { class: "chat-context-meta muted", text: contextMeta }));
|
||
pane.append(context);
|
||
|
||
if (thread?.loading && !thread?.loaded) {
|
||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_LOADING }));
|
||
} else if (thread?.error && !thread?.loaded) {
|
||
const empty = chatEmpty(thread.error);
|
||
empty.append(
|
||
h("button", {
|
||
class: "ghost",
|
||
type: "button",
|
||
text: "Retry",
|
||
onclick: () => loadChatHistory(state.chatActiveId),
|
||
}),
|
||
);
|
||
pane.append(empty);
|
||
} else {
|
||
const rows = transcriptRows(thread?.messages ?? []);
|
||
const running = thread?.running === true;
|
||
if (rows.length === 0 && !running) {
|
||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
|
||
} else {
|
||
pane.append(renderChatTranscript(state.chatActiveId, rows, { running, now: Date.now() }));
|
||
}
|
||
if (thread?.error && thread?.loaded) {
|
||
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
|
||
}
|
||
}
|
||
|
||
appendChatDialogs(pane);
|
||
return pane;
|
||
}
|
||
|
||
/**
|
||
* The chat overlays, appended to the conversation pane whether or not a
|
||
* conversation is open: the row's own `Close chat…` action is offered on every
|
||
* open row, so its confirm must appear even when no chat is selected.
|
||
*/
|
||
function appendChatDialogs(pane) {
|
||
if (state.chatClose) pane.append(renderChatCloseDialog(state.chatClose));
|
||
if (state.actionError) pane.append(renderActionFailedDialog());
|
||
}
|
||
|
||
/**
|
||
* The transcript: one column of turns. An operator message is its own
|
||
* right-aligned bubble (with the sending client's label when the server echoed
|
||
* one); consecutive assistant messages are one left-aligned agent bubble, drawn
|
||
* in order as the reasoning block, then the tool-call chip, then the answer
|
||
* markdown. No timestamps, model or agent are shown inside the transcript.
|
||
*/
|
||
function renderChatTranscript(sessionId, rows, { running = false, now = Date.now() } = {}) {
|
||
const wrap = h("div", { class: "chat-transcript-wrap" });
|
||
const transcript = h("div", {
|
||
class: "chat-transcript",
|
||
id: "chatTranscript",
|
||
"data-session": sessionId,
|
||
});
|
||
const thread = state.chatThreads.get(sessionId) ?? null;
|
||
let lastAgent = -1;
|
||
rows.forEach((row, index) => {
|
||
if (row.kind === "agent") lastAgent = index;
|
||
});
|
||
rows.forEach((row, index) => {
|
||
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
|
||
else {
|
||
const streaming = running && index === lastAgent;
|
||
const elapsed = (part) => threadToolElapsedMillis(thread, part, now);
|
||
transcript.append(renderChatAgentTurn(row.turn, streaming, elapsed));
|
||
}
|
||
});
|
||
// The running indicator sits under the transcript, after the last agent turn:
|
||
// a spinner, the phase headline, the turn's elapsed, then one line per running
|
||
// tool (a call over 60 s is tinted and marked `· long`).
|
||
if (running && thread) transcript.append(renderChatRunningIndicator(thread, now));
|
||
wrap.append(transcript);
|
||
wrap.append(
|
||
h("button", {
|
||
class: "ghost chat-jump",
|
||
id: "chatJump",
|
||
type: "button",
|
||
text: "Jump to latest",
|
||
hidden: true,
|
||
onclick: () => {
|
||
state.chatFollowing = true;
|
||
const el = document.getElementById("chatTranscript");
|
||
if (el) el.scrollTop = el.scrollHeight;
|
||
updateChatJump(el);
|
||
},
|
||
}),
|
||
);
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
|
||
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
|
||
* with its own elapsed. A call that has passed [TOOL_LONG_RUNNING_MILLIS] is
|
||
* tinted and marked `· long` — the same threshold the tool chip uses.
|
||
*/
|
||
function renderChatRunningIndicator(thread, now) {
|
||
const wrap = h("div", { class: "chat-running", id: "chatRunning" });
|
||
const head = h("div", { class: "chat-running-head" });
|
||
head.append(h("span", { class: "spinner chat-running-spinner", "aria-hidden": "true" }));
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-running-label",
|
||
text: turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING),
|
||
}),
|
||
);
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-running-elapsed",
|
||
text: `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`,
|
||
}),
|
||
);
|
||
wrap.append(head);
|
||
for (const part of threadRunningTools(thread.messages)) {
|
||
wrap.append(renderChatRunningTool(thread, part, now));
|
||
}
|
||
return wrap;
|
||
}
|
||
|
||
function renderChatRunningTool(thread, part, now) {
|
||
const line = h("div", { class: "chat-running-tool", "data-part-id": String(part?.id ?? "") });
|
||
const name = toolLabel(part);
|
||
const detail = toolDetail(part);
|
||
line.append(h("span", { class: "chat-running-tool-text", text: detail == null ? name : `${name} ${detail}` }));
|
||
line.append(
|
||
h("span", {
|
||
class: "chat-running-tool-elapsed muted",
|
||
text: formatToolDuration(threadToolElapsedMillis(thread, part, now)),
|
||
}),
|
||
);
|
||
if (toolLongRunning(threadToolElapsedMillis(thread, part, now))) {
|
||
line.classList.add("chat-running-tool-long");
|
||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
}
|
||
return line;
|
||
}
|
||
|
||
/** One operator turn, right-aligned, carrying its sender label when present. */
|
||
function renderChatUserMessage(message) {
|
||
const turn = h("div", { class: "chat-turn chat-turn-user" });
|
||
const bubble = h("div", { class: "chat-bubble user-bubble" });
|
||
const client = String(message?.client ?? "").trim();
|
||
if (client !== "") bubble.append(h("div", { class: "chat-client", text: message.client }));
|
||
const text = (message?.parts ?? [])
|
||
.filter((part) => part?.type === "text" || !part?.type)
|
||
.map((part) => String(part?.text ?? ""))
|
||
.join("\n")
|
||
.trim();
|
||
if (text !== "") bubble.append(h("div", { class: "chat-user-text", text }));
|
||
turn.append(bubble);
|
||
return turn;
|
||
}
|
||
|
||
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
|
||
function renderChatAgentTurn(turn, streaming = false, elapsedMillis = () => 0) {
|
||
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
|
||
const bubble = h("div", { class: "chat-bubble agent-bubble" });
|
||
const steps = turn.reasoningSteps;
|
||
if (steps.length > 0) bubble.append(renderChatReasoning(turn, streaming));
|
||
if (turn.tools.length > 0) {
|
||
const tools = renderChatToolCalls(turn, { streaming, elapsedMillis });
|
||
if (tools) bubble.append(tools);
|
||
}
|
||
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
|
||
wrap.append(bubble);
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* The turn's one collapsible reasoning block. The open/closed state lives on the
|
||
* conversation keyed by the turn, so it survives a re-render; toggling it never
|
||
* rebuilds the transcript (and so never moves the operator's scroll). The label is
|
||
* the app's own (see `reasoningLabel`) with the turn's server-reported duration
|
||
* appended when it has one; a settled history turn reads `Reasoning` (or
|
||
* `Reasoning · N steps`), a live one `Thinking…`/`Thinking · N steps`. Live
|
||
* elapsed time is C5's; this renders the parts' own timing.
|
||
*/
|
||
function renderChatReasoning(turn, streaming = false) {
|
||
const expanded = state.chatReasoning.has(turn.key);
|
||
const block = h("div", { class: "chat-reasoning" });
|
||
const toggle = h("button", {
|
||
class: "chat-reasoning-toggle",
|
||
type: "button",
|
||
"aria-expanded": String(expanded),
|
||
});
|
||
toggle.append(
|
||
h("span", {
|
||
class: "chat-reasoning-icon",
|
||
role: "img",
|
||
"aria-label": expanded ? "Hide reasoning" : "Show reasoning",
|
||
text: expanded ? "\u25be" : "\u25b8",
|
||
}),
|
||
);
|
||
const label = reasoningLabel(turn.reasoningSteps.length, streaming);
|
||
const elapsedMillis = turnElapsedMillis(turn.parts);
|
||
const duration = elapsedMillis == null ? null : formatDuration(Math.trunc(elapsedMillis / 1000));
|
||
toggle.append(
|
||
h("span", {
|
||
class: "chat-reasoning-label",
|
||
text: duration == null ? label : `${label} · ${duration}`,
|
||
}),
|
||
);
|
||
const body = h("div", { class: "chat-reasoning-body", text: turn.reasoning });
|
||
body.hidden = !expanded;
|
||
toggle.addEventListener("click", () => {
|
||
const next = body.hidden;
|
||
body.hidden = !next;
|
||
toggle.setAttribute("aria-expanded", String(next));
|
||
const icon = toggle.querySelector(".chat-reasoning-icon");
|
||
icon.textContent = next ? "\u25be" : "\u25b8";
|
||
icon.setAttribute("aria-label", next ? "Hide reasoning" : "Show reasoning");
|
||
if (next) state.chatReasoning.add(turn.key);
|
||
else state.chatReasoning.delete(turn.key);
|
||
});
|
||
block.append(toggle, body);
|
||
return block;
|
||
}
|
||
|
||
/**
|
||
* One turn's tool calls behind a single summary chip (C6), the browser's port of
|
||
* `ui/chat/ChatToolCalls.kt`: `N tools called`, a spinner while any call is in
|
||
* flight, a `· long` mark (error tint) once a running call has passed
|
||
* [TOOL_LONG_RUNNING_MILLIS], error styling once a call failed, and a chevron
|
||
* naming the panel it opens. The panel is a fixed overlay anchored below the chip
|
||
* (flipped above when there is no room), with a header count, a close control, an
|
||
* internally scrolling list, and per-row expand state; because it never joins the
|
||
* transcript's flow, opening or closing it cannot re-flow the conversation nor
|
||
* move its scroll position (C14).
|
||
*
|
||
* [streaming] is whether the turn is still live, and [elapsedMillis] the live age
|
||
* of a running call (the conversation supplies it from its own clock, so the
|
||
* `long` mark is derived from real time, never guessed). A settled history turn
|
||
* passes neither, so a stored `running` status cannot spin or wear the mark.
|
||
*/
|
||
function renderChatToolCalls(turn, { streaming = false, elapsedMillis = () => 0 } = {}) {
|
||
const parts = turn.tools;
|
||
if (parts.length === 0) return null;
|
||
const count = toolCallCount(turn.parts);
|
||
const running = streaming && toolsRunning(turn.parts);
|
||
const failed = parts.some((part) => toolFailed(part.state));
|
||
const long = running && parts.some((part) => toolRunning(part) && toolLongRunning(elapsedMillis(part)));
|
||
const turnKey = turn.key;
|
||
|
||
const wrap = h("div", { class: "chat-tools" });
|
||
const open = state.chatToolPanels.has(turnKey);
|
||
const chip = h("button", {
|
||
class: `chip chat-tool-chip${failed ? " chat-tool-chip-failed" : ""}`,
|
||
type: "button",
|
||
"aria-label": toolCallsAnnouncement(count),
|
||
"aria-expanded": String(open),
|
||
});
|
||
if (running) {
|
||
chip.append(h("span", { class: "spinner chat-tool-spinner", "aria-hidden": "true" }));
|
||
} else {
|
||
chip.append(
|
||
h("span", {
|
||
class: `chat-tool-icon${failed ? " chat-tool-icon-failed" : ""}`,
|
||
"aria-hidden": "true",
|
||
text: failed ? "\u26a0" : "\u29c9",
|
||
}),
|
||
);
|
||
}
|
||
chip.append(h("span", { class: "chat-tool-label", text: toolCallsLabel(count) }));
|
||
if (long) chip.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
const chevron = h("span", {
|
||
class: "chat-tool-chevron",
|
||
role: "img",
|
||
"aria-label": open ? "Hide tool calls" : "Show tool calls",
|
||
text: open ? "\u25b4" : "\u25be",
|
||
});
|
||
chip.append(chevron);
|
||
wrap.append(chip);
|
||
|
||
const panel = h("div", { class: "chat-tool-panel", role: "dialog", "aria-label": toolCallsLabel(count) });
|
||
panel.hidden = !open;
|
||
const head = h("div", { class: "chat-tool-panel-head" });
|
||
head.append(h("span", { class: "chat-tool-panel-count", text: toolCallsLabel(count) }));
|
||
const close = h("button", {
|
||
class: "ghost chat-tool-close",
|
||
type: "button",
|
||
"aria-label": "Close tool calls",
|
||
title: "Close tool calls",
|
||
text: "\u00d7",
|
||
});
|
||
head.append(close);
|
||
panel.append(head);
|
||
const list = h("div", { class: "chat-tool-list" });
|
||
for (const part of parts) {
|
||
const id = String(part?.id ?? "");
|
||
const holder = h("div", { class: "chat-tool-row-holder" });
|
||
const build = () =>
|
||
renderToolCallRow(part, {
|
||
expanded: state.chatToolRows.has(id),
|
||
onToggle: () => {
|
||
if (state.chatToolRows.has(id)) state.chatToolRows.delete(id);
|
||
else state.chatToolRows.add(id);
|
||
holder.replaceChild(build(), holder.firstChild);
|
||
},
|
||
});
|
||
holder.append(build());
|
||
list.append(holder);
|
||
}
|
||
panel.append(list);
|
||
wrap.append(panel);
|
||
|
||
const setOpen = (next) => {
|
||
if (next) state.chatToolPanels.add(turnKey);
|
||
else state.chatToolPanels.delete(turnKey);
|
||
panel.hidden = !next;
|
||
chip.setAttribute("aria-expanded", String(next));
|
||
chevron.setAttribute("aria-label", next ? "Hide tool calls" : "Show tool calls");
|
||
chevron.textContent = next ? "\u25b4" : "\u25be";
|
||
if (next) positionChatToolPanel(panel, chip);
|
||
};
|
||
chip.addEventListener("click", (event) => {
|
||
event.stopPropagation();
|
||
setOpen(panel.hidden);
|
||
});
|
||
close.addEventListener("click", () => setOpen(false));
|
||
if (open) {
|
||
// The panel is built before its turn is attached to the document, so its
|
||
// rect is not measurable yet; place it on the next frame, when it is.
|
||
const place = () => positionChatToolPanel(panel, chip);
|
||
if (typeof requestAnimationFrame === "function") requestAnimationFrame(place);
|
||
else setTimeout(place, 0);
|
||
}
|
||
|
||
return wrap;
|
||
}
|
||
|
||
/**
|
||
* Places the tool panel below its chip, or above it when there is no room, keeping
|
||
* it inside the viewport margins — the browser's port of
|
||
* `ToolPanelPositionProvider`. Resolved in px from the live rects, so it is
|
||
* independent of any layout guess.
|
||
*/
|
||
function positionChatToolPanel(panel, chip) {
|
||
const gap = 4;
|
||
const margin = 8;
|
||
const chipRect = chip.getBoundingClientRect();
|
||
const rect = panel.getBoundingClientRect();
|
||
let top = chipRect.bottom + gap;
|
||
if (top + rect.height > window.innerHeight - margin) top = chipRect.top - rect.height - gap;
|
||
top = Math.max(margin, Math.min(top, window.innerHeight - rect.height - margin));
|
||
const left = Math.max(margin, Math.min(chipRect.left, window.innerWidth - rect.width - margin));
|
||
panel.style.top = `${Math.round(top)}px`;
|
||
panel.style.left = `${Math.round(left)}px`;
|
||
}
|
||
|
||
/**
|
||
* One call inside the panel: a header naming the call, its `+N -M` stat for an
|
||
* edit and its duration, and — expanded in place — the pretty-printed INPUT, the
|
||
* synthesised edit diff, then the ERROR block for a failed call or the OUTPUT for
|
||
* a settled one. Rows expand and collapse independently. Exported so the smoke can
|
||
* render a representative row through this same builder.
|
||
*/
|
||
export function renderToolCallRow(part, { expanded = false, onToggle = null } = {}) {
|
||
const row = toolCallRow(part);
|
||
const node = h("div", { class: `chat-tool-row${row.error != null ? " chat-tool-row-failed" : ""}` });
|
||
const head = h("button", {
|
||
class: "chat-tool-row-head",
|
||
type: "button",
|
||
"aria-expanded": String(expanded),
|
||
});
|
||
head.append(
|
||
h("span", {
|
||
class: `chat-tool-icon${row.error != null ? " chat-tool-icon-failed" : ""}`,
|
||
role: "img",
|
||
"aria-label": row.error != null ? "Failed tool call" : "",
|
||
"aria-hidden": row.error != null ? null : "true",
|
||
text: row.error != null ? "\u26a0" : row.diff != null ? "\u270e" : "\u29c9",
|
||
}),
|
||
);
|
||
const titles = h("span", { class: "chat-tool-row-titles" });
|
||
titles.append(h("span", { class: "chat-tool-name", text: row.name }));
|
||
if (row.detail != null) titles.append(h("span", { class: "chat-tool-detail", text: row.detail }));
|
||
head.append(titles);
|
||
if (row.diff != null) {
|
||
head.append(h("span", { class: "chat-tool-stat", text: changeStat(row.diff.added, row.diff.removed) }));
|
||
}
|
||
if (row.duration != null) head.append(h("span", { class: "chat-tool-duration", text: row.duration }));
|
||
head.append(
|
||
h("span", {
|
||
class: "chat-tool-row-chevron",
|
||
role: "img",
|
||
"aria-label": expanded ? `Collapse ${row.name}` : `Expand ${row.name}`,
|
||
text: expanded ? "\u25b4" : "\u25be",
|
||
}),
|
||
);
|
||
node.append(head);
|
||
if (expanded) {
|
||
const body = h("div", { class: "chat-tool-body" });
|
||
const input = toolSection("INPUT", row.input);
|
||
if (input) body.append(input);
|
||
if (row.diff != null) body.append(renderToolDiff(row.diff));
|
||
if (row.error != null) {
|
||
const error = toolSection("ERROR", row.error);
|
||
if (error) body.append(error);
|
||
} else {
|
||
const output = toolSection("OUTPUT", row.output);
|
||
if (output) body.append(output);
|
||
}
|
||
node.append(body);
|
||
}
|
||
if (typeof onToggle === "function") {
|
||
head.addEventListener("click", () => onToggle());
|
||
}
|
||
return node;
|
||
}
|
||
|
||
/** One monospace section card (INPUT/OUTPUT/ERROR); blank content renders none. */
|
||
function toolSection(label, text) {
|
||
if (text == null || String(text).trim() === "") return null;
|
||
const section = h("div", { class: "chat-tool-section" });
|
||
section.append(h("div", { class: "chat-tool-section-label", text: label }));
|
||
section.append(h("pre", { class: "chat-tool-section-body", text }));
|
||
return section;
|
||
}
|
||
|
||
/**
|
||
* The unified diff body of an edit call: line-by-line monospace with `+`/`-`
|
||
* gutter symbols and the app's success/failure hues, the shared line language of
|
||
* the run Changes viewer. A diff longer than the rendered cap is summarised with
|
||
* an omitted note. Exported so the smoke can render a representative sample.
|
||
*/
|
||
export function renderToolDiff(diff) {
|
||
const card = h("div", { class: "chat-tool-diff" });
|
||
if (diff.omitted > 0) {
|
||
card.append(
|
||
h("div", {
|
||
class: "chat-tool-diff-note",
|
||
text: `\u2026 ${diff.omitted} more changed ${diff.omitted === 1 ? "line" : "lines"} not shown`,
|
||
}),
|
||
);
|
||
}
|
||
for (const line of diff.lines) {
|
||
card.append(
|
||
h("div", {
|
||
class: `chat-tool-diff-line ${diffLineClass(line.kind)}`,
|
||
text: `${diffLineSymbol(line.kind)} ${line.text}`,
|
||
}),
|
||
);
|
||
}
|
||
return card;
|
||
}
|
||
|
||
/**
|
||
* Render assistant markdown by building DOM nodes, never by assigning innerHTML.
|
||
* Exported so the live UI smoke can exercise the page's own renderer for the
|
||
* fenced-code path the live transcript does not carry; the page itself calls it
|
||
* directly.
|
||
*/
|
||
export function renderMarkdown(text) {
|
||
const wrap = h("div", { class: "markdown" });
|
||
for (const block of parseMarkdown(text)) wrap.append(renderMarkdownBlock(block));
|
||
return wrap;
|
||
}
|
||
|
||
function renderMarkdownBlock(block) {
|
||
if (block.kind === "heading") {
|
||
const level = Math.min(Math.max(block.level, 1), 4) + 2; // h3..h6, never h1/h2
|
||
return h(`h${level}`, { class: "md-heading" }, ...renderInlineNodes(parseInline(block.text)));
|
||
}
|
||
if (block.kind === "paragraph") {
|
||
return h("p", { class: "md-paragraph" }, ...renderInlineNodes(parseInline(block.text)));
|
||
}
|
||
if (block.kind === "code") {
|
||
const code = h("div", { class: "md-code-block" });
|
||
code.append(h("div", { class: "md-code-label", text: codeBlockLabel(block.language) }));
|
||
code.append(h("pre", { class: "md-pre" }, h("code", { text: block.code })));
|
||
return code;
|
||
}
|
||
if (block.kind === "rule") return h("hr", { class: "md-rule" });
|
||
if (block.kind === "quote") {
|
||
const quote = h("blockquote", { class: "md-quote" });
|
||
for (const line of block.lines) {
|
||
if (line.trim() !== "") quote.append(h("p", {}, ...renderInlineNodes(parseInline(line))));
|
||
}
|
||
return quote;
|
||
}
|
||
if (block.kind === "list") {
|
||
const list = h(block.ordered ? "ol" : "ul", { class: "md-list" });
|
||
for (const item of block.items) {
|
||
list.append(h("li", {}, ...renderInlineNodes(parseInline(item))));
|
||
}
|
||
return list;
|
||
}
|
||
if (block.kind === "table") {
|
||
const table = h("table", { class: "md-table" });
|
||
const head = h("thead");
|
||
const headRow = h("tr");
|
||
for (const cell of block.header) headRow.append(h("th", {}, ...renderInlineNodes(parseInline(cell))));
|
||
head.append(headRow);
|
||
table.append(head);
|
||
const body = h("tbody");
|
||
for (const row of block.rows) {
|
||
const tr = h("tr");
|
||
for (const cell of row) tr.append(h("td", {}, ...renderInlineNodes(parseInline(cell))));
|
||
body.append(tr);
|
||
}
|
||
table.append(body);
|
||
return table;
|
||
}
|
||
// Anything outside the subset stays plain text and is never dropped.
|
||
return h("p", { class: "md-paragraph", text: block.text ?? "" });
|
||
}
|
||
|
||
function renderInlineNodes(spans) {
|
||
return (spans ?? []).map((span) => {
|
||
if (span.kind === "code") return h("code", { class: "md-code", text: span.text });
|
||
if (span.kind === "strong") return h("strong", {}, ...renderInlineNodes(span.spans));
|
||
if (span.kind === "emphasis") return h("em", {}, ...renderInlineNodes(span.spans));
|
||
if (span.kind === "link") {
|
||
// Only http(s) targets become links: the transcript is untrusted model
|
||
// output, so a javascript:/data: target is shown as its label, never made
|
||
// clickable. Nothing is dropped either way.
|
||
if (/^https?:\/\//i.test(span.url)) {
|
||
return h(
|
||
"a",
|
||
{ class: "md-link", href: span.url, rel: "noreferrer noopener", target: "_blank" },
|
||
...renderInlineNodes(span.spans),
|
||
);
|
||
}
|
||
return h("span", { class: "md-link-plain" }, ...renderInlineNodes(span.spans));
|
||
}
|
||
return document.createTextNode(String(span.text ?? ""));
|
||
});
|
||
}
|
||
|
||
/** The Close chat? confirm: the exact Android body naming the session title. */
|
||
function renderChatCloseDialog(session) {
|
||
const overlay = h("div", {
|
||
class: "confirm-dialog confirm-chat-close",
|
||
role: "dialog",
|
||
"aria-modal": "true",
|
||
"aria-label": CLOSE_CHAT_TITLE,
|
||
});
|
||
overlay.addEventListener("click", (event) => {
|
||
if (event.target === overlay) dismissChatClose();
|
||
});
|
||
const panel = h("div", { class: "confirm-panel" });
|
||
panel.append(h("h2", { class: "confirm-title", text: CLOSE_CHAT_TITLE }));
|
||
panel.append(
|
||
h("p", { class: "confirm-message", text: closeChatConfirmation(sessionTitle(session)) }),
|
||
);
|
||
const actions = h("div", { class: "confirm-actions" });
|
||
actions.append(
|
||
h("button", {
|
||
class: "ghost confirm-dismiss",
|
||
type: "button",
|
||
text: CLOSE_CHAT_DISMISS,
|
||
onclick: dismissChatClose,
|
||
}),
|
||
);
|
||
actions.append(
|
||
h("button", {
|
||
class: "confirm-accept confirm-close-chat",
|
||
type: "button",
|
||
text: CLOSE_CHAT_CONFIRM,
|
||
onclick: () => acceptChatClose(session),
|
||
}),
|
||
);
|
||
panel.append(actions);
|
||
overlay.append(panel);
|
||
return overlay;
|
||
}
|
||
|
||
/**
|
||
* Wire the freshly rendered transcript: restore the operator's saved position
|
||
* (or open at the newest message when they have none), preserve the visual
|
||
* position across a prepended older page, follow new content while following,
|
||
* and offer "Jump to latest" only when not following and something is below the
|
||
* fold. Only the operator's own wheel/drag changes that intent; nothing here ever
|
||
* auto-loads older history on scroll.
|
||
*/
|
||
function afterChatRender() {
|
||
const el = document.getElementById("chatTranscript");
|
||
if (!el) {
|
||
state.chatPending = null;
|
||
return;
|
||
}
|
||
const sessionId = el.dataset.session;
|
||
const itemCount = el.children.length;
|
||
const thread = state.chatThreads.get(sessionId) ?? null;
|
||
// The position captured from the previous render (if it was this session), and
|
||
// the paging anchor (if an older page is being fetched). Both are consumed once.
|
||
const pending = state.chatPending?.sessionId === sessionId ? state.chatPending : null;
|
||
state.chatPending = null;
|
||
const anchor = state.chatAnchor?.sessionId === sessionId ? state.chatAnchor : null;
|
||
// A re-render is not the operator's gesture: the intent flag is re-armed only
|
||
// by a wheel/drag on the transcript below.
|
||
state.chatUserIntent = false;
|
||
|
||
if (anchor && thread?.loading !== true) {
|
||
// The render that actually carries the prepended older page: keep the same
|
||
// message at the same place by the height the page added. The loading frame
|
||
// itself is skipped, so the anchor survives until the content arrives.
|
||
const delta = el.scrollHeight - anchor.scrollHeight;
|
||
el.scrollTop = anchor.scrollTop + Math.max(0, delta);
|
||
state.chatAnchor = null;
|
||
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
|
||
} else if (state.chatPlaced === sessionId) {
|
||
// A re-render of a conversation already placed (a dialog, a refresh, the
|
||
// loading frame of a paging fetch): put the operator back exactly where they
|
||
// were, so nothing they did not do moves their view.
|
||
const restore = pending ? pending.position : state.chatScroll[sessionId] ?? null;
|
||
const follow = pending ? pending.following : state.chatFollowing;
|
||
if (follow || restore == null) {
|
||
el.scrollTop = el.scrollHeight;
|
||
state.chatFollowing = true;
|
||
} else {
|
||
const first = chatFirstScroll(restore, itemCount);
|
||
const row = el.children[first.index];
|
||
el.scrollTop = row ? row.offsetTop + first.offset : el.scrollHeight;
|
||
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
|
||
}
|
||
} else {
|
||
const saved = state.chatScroll[sessionId] ?? null;
|
||
if (chatOpensAtNewest(saved)) {
|
||
// No position of the operator's own: land on the newest content instantly —
|
||
// the end of the transcript, so a last turn taller than the viewport opens
|
||
// at its newest part rather than its first — and follow.
|
||
el.scrollTop = el.scrollHeight;
|
||
state.chatFollowing = true;
|
||
} else {
|
||
const first = chatFirstScroll(saved, itemCount);
|
||
const row = el.children[first.index];
|
||
el.scrollTop = row ? row.offsetTop + first.offset : el.scrollHeight;
|
||
state.chatFollowing = chatFollowsAt(transcriptDistance(el), CHAT_FOLLOW_THRESHOLD_PX, itemCount);
|
||
}
|
||
state.chatPlaced = sessionId;
|
||
}
|
||
|
||
// Only a scroll that happens during the operator's own gesture (a wheel, or a
|
||
// pointer/touch press that is still down) is theirs; a programmatic placement,
|
||
// follow or anchor restore never changes the intent. A plain click that never
|
||
// scrolls therefore leaves the intent alone.
|
||
let gesture = false;
|
||
const beginGesture = () => {
|
||
gesture = true;
|
||
};
|
||
const endGesture = () => {
|
||
gesture = false;
|
||
};
|
||
el.addEventListener("wheel", () => {
|
||
state.chatUserIntent = true;
|
||
state.chatFollowing = false;
|
||
updateChatJump(el);
|
||
});
|
||
el.addEventListener("pointerdown", beginGesture);
|
||
el.addEventListener("pointerup", endGesture);
|
||
el.addEventListener("pointercancel", endGesture);
|
||
el.addEventListener("touchstart", beginGesture, { passive: true });
|
||
el.addEventListener("touchend", endGesture);
|
||
el.addEventListener("touchcancel", endGesture);
|
||
el.addEventListener("scroll", () => {
|
||
if (state.chatUserIntent || gesture) {
|
||
state.chatUserIntent = true;
|
||
state.chatFollowing = chatFollowsAt(
|
||
transcriptDistance(el),
|
||
CHAT_FOLLOW_THRESHOLD_PX,
|
||
el.children.length,
|
||
);
|
||
}
|
||
updateChatJump(el);
|
||
clearTimeout(state.chatScrollTimer);
|
||
state.chatScrollTimer = setTimeout(() => {
|
||
if (state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(el));
|
||
}, 200);
|
||
});
|
||
|
||
updateChatJump(el);
|
||
}
|
||
|
||
/** Offer "Jump to latest" only when not following and something is below the fold. */
|
||
function updateChatJump(el) {
|
||
const jump = document.getElementById("chatJump");
|
||
if (!jump) return;
|
||
const count = el ? el.children.length : 0;
|
||
jump.hidden = !chatShowJumpToLatest(
|
||
state.chatFollowing,
|
||
transcriptDistance(el),
|
||
CHAT_FOLLOW_THRESHOLD_PX,
|
||
count,
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Omni-search (S1/S2)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
/** Open the search field and ask for focus; the current view is left alone. */
|
||
function openSearch() {
|
||
if (state.searchOpen) return;
|
||
state.searchOpen = true;
|
||
state.searchError = "";
|
||
state.searchFocusPending = true;
|
||
renderHeader();
|
||
renderSearch();
|
||
}
|
||
|
||
/**
|
||
* Close and clear the search: the pending debounce is dropped, an in-flight reply
|
||
* is invalidated by recording a fresh edit, and the query, results, error and
|
||
* loading flag are reset. The view, the selection and the loaded data are
|
||
* deliberately untouched, so closing restores exactly the state that was on
|
||
* screen before the search opened.
|
||
*/
|
||
function closeSearch() {
|
||
cancelSearchDebounce();
|
||
// Recording an empty edit advances the sequencer, so a reply for a request
|
||
// still in flight can no longer be accepted.
|
||
state.searchSequencer.edit("");
|
||
state.searchOpen = false;
|
||
state.searchQuery = "";
|
||
state.searchResults = [];
|
||
state.searchLoading = false;
|
||
state.searchError = "";
|
||
state.searchLoaded = false;
|
||
state.searchFocusPending = false;
|
||
renderHeader();
|
||
renderSearch();
|
||
}
|
||
|
||
function cancelSearchDebounce() {
|
||
if (searchTimer) {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = null;
|
||
}
|
||
searchEdit = null;
|
||
}
|
||
|
||
/**
|
||
* A keystroke. A blank/whitespace query clears the results locally and sends
|
||
* nothing; otherwise the previous results stay visible, the request is marked in
|
||
* flight and the send is debounced `SEARCH_DEBOUNCE_MS` from the last keystroke.
|
||
* Recording the edit is itself enough to drop any older reply still in flight.
|
||
*/
|
||
function onSearchInput(value) {
|
||
state.searchQuery = value;
|
||
state.searchError = "";
|
||
cancelSearchDebounce();
|
||
if (!searchQuerySendable(value)) {
|
||
state.searchSequencer.edit("");
|
||
state.searchResults = [];
|
||
state.searchLoading = false;
|
||
state.searchLoaded = false;
|
||
refreshSearch();
|
||
return;
|
||
}
|
||
state.searchLoading = true;
|
||
searchEdit = state.searchSequencer.edit(value);
|
||
refreshSearch();
|
||
searchTimer = setTimeout(() => {
|
||
searchTimer = null;
|
||
const sent = state.searchSequencer.begin(searchEdit);
|
||
if (sent) runSearch(sent);
|
||
}, SEARCH_DEBOUNCE_MS);
|
||
}
|
||
|
||
/** Send the current query at once (Enter, or a kind change), skipping the debounce. */
|
||
function sendSearchNow() {
|
||
const query = state.searchQuery;
|
||
cancelSearchDebounce();
|
||
if (!searchQuerySendable(query)) {
|
||
state.searchSequencer.edit("");
|
||
state.searchResults = [];
|
||
state.searchLoading = false;
|
||
state.searchError = "";
|
||
state.searchLoaded = false;
|
||
refreshSearch();
|
||
return;
|
||
}
|
||
const sent = state.searchSequencer.begin(state.searchSequencer.edit(query));
|
||
if (sent) runSearch(sent);
|
||
}
|
||
|
||
/**
|
||
* A kind-filter change: the in-hand filter is re-applied immediately so the list
|
||
* always matches the control, and — when the query is non-blank — a fresh server
|
||
* request is sent with the new kind. A sort change never sends a request.
|
||
*/
|
||
function setSearchKind(kind) {
|
||
state.searchKind = kind;
|
||
refreshSearch();
|
||
if (searchQuerySendable(state.searchQuery)) sendSearchNow();
|
||
}
|
||
|
||
function setSearchSort(sort) {
|
||
state.searchSort = sort;
|
||
refreshSearch();
|
||
}
|
||
|
||
/**
|
||
* Run one query and apply the reply only if it is still the newest edit. A reply
|
||
* without a `search_results` payload (an older server's pong) or a rejection
|
||
* naming an unknown command reports the app's "cannot search" sentence; any other
|
||
* failure carries the server's own text. A stale reply is dropped entirely.
|
||
*/
|
||
async function runSearch(sent) {
|
||
try {
|
||
const reply = await repo.search(sent.query, state.searchKind);
|
||
if (!state.searchSequencer.accepts(sent.token)) return;
|
||
if (reply == null) {
|
||
state.searchLoading = false;
|
||
state.searchLoaded = true;
|
||
state.searchError = searchFailureText(null);
|
||
refreshSearch();
|
||
return;
|
||
}
|
||
state.searchResults = Array.isArray(reply.results) ? reply.results : [];
|
||
state.searchLoading = false;
|
||
state.searchError = "";
|
||
state.searchLoaded = true;
|
||
refreshSearch();
|
||
} catch (error) {
|
||
if (!state.searchSequencer.accepts(sent.token)) return;
|
||
state.searchLoading = false;
|
||
state.searchLoaded = true;
|
||
state.searchError = searchFailureText(error);
|
||
refreshSearch();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Re-render the search panel's controls and results in place. Only the results
|
||
* area, the summary and the select values are touched, so a keystroke never
|
||
* rebuilds (and so never blurs) the query field.
|
||
*/
|
||
function refreshSearch() {
|
||
const kindSelect = document.getElementById("searchKind");
|
||
if (kindSelect) kindSelect.value = state.searchKind;
|
||
const sortSelect = document.getElementById("searchSort");
|
||
if (sortSelect) sortSelect.value = state.searchSort;
|
||
const summary = document.getElementById("searchSummary");
|
||
if (summary) summary.textContent = searchControlsSummary(state.searchKind, state.searchSort);
|
||
const area = document.getElementById("searchResults");
|
||
if (area) fillSearchResults(area);
|
||
}
|
||
|
||
/**
|
||
* The full-width search panel: the controls row (kind select, sort select, the
|
||
* one-line summary and the Clear filter reset) and a bounded scrolling result
|
||
* area. Rendered only while the search is open; the panel is one flat list, with
|
||
* no per-kind grouping headers, matching the app.
|
||
*/
|
||
function renderSearch() {
|
||
if (!state.searchOpen) {
|
||
searchHost.replaceChildren();
|
||
return;
|
||
}
|
||
const kindSelect = h(
|
||
"select",
|
||
{
|
||
id: "searchKind",
|
||
class: "search-select",
|
||
"aria-label": "Filter results",
|
||
onchange: (event) => setSearchKind(event.target.value),
|
||
},
|
||
...SEARCH_KINDS.map((option) => h("option", { value: option.value, text: option.label })),
|
||
);
|
||
kindSelect.value = state.searchKind;
|
||
const sortSelect = h(
|
||
"select",
|
||
{
|
||
id: "searchSort",
|
||
class: "search-select",
|
||
"aria-label": "Sort results in hand",
|
||
onchange: (event) => setSearchSort(event.target.value),
|
||
},
|
||
...SEARCH_SORTS.map((option) => h("option", { value: option.value, text: option.label })),
|
||
);
|
||
sortSelect.value = state.searchSort;
|
||
|
||
const controls = h(
|
||
"div",
|
||
{ class: "search-controls" },
|
||
h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Kind" }), kindSelect),
|
||
h("label", { class: "search-field" }, h("span", { class: "search-field-label", text: "Sort" }), sortSelect),
|
||
h("span", {
|
||
id: "searchSummary",
|
||
class: "search-summary muted",
|
||
text: searchControlsSummary(state.searchKind, state.searchSort),
|
||
}),
|
||
h("button", {
|
||
id: "searchClearFilter",
|
||
class: "ghost search-clear",
|
||
type: "button",
|
||
text: "Clear filter",
|
||
onclick: () => setSearchKind(DEFAULT_SEARCH_KIND),
|
||
}),
|
||
);
|
||
|
||
const area = h("div", { id: "searchResults", class: "search-results", "aria-live": "polite" });
|
||
fillSearchResults(area);
|
||
searchHost.replaceChildren(h("div", { id: "searchPanel", class: "search-panel" }, controls, area));
|
||
}
|
||
|
||
/**
|
||
* Fill the results area from the current state. A first load with nothing yet
|
||
* shows the spinner and `Searching…`; a refresh that retained results shows a thin
|
||
* progress bar above them; an error takes precedence over the results; otherwise
|
||
* the filtered and sorted rows, or the empty-state line.
|
||
*/
|
||
function fillSearchResults(area) {
|
||
const shown = sortSearchResults(
|
||
filterSearchResults(state.searchResults, state.searchKind),
|
||
state.searchSort,
|
||
);
|
||
const nodes = [];
|
||
if (searchPanelProgress(state)) {
|
||
nodes.push(h("div", { class: "search-progress", role: "progressbar", "aria-label": "Searching" }));
|
||
}
|
||
const body = searchPanelBody(state, shown, state.searchKind);
|
||
if (body.kind === "error") {
|
||
nodes.push(h("div", { class: "search-error", text: body.message }));
|
||
} else if (body.kind === "results") {
|
||
for (const hit of shown) nodes.push(renderSearchResultRow(hit));
|
||
} else if (body.kind === "searching") {
|
||
nodes.push(
|
||
h(
|
||
"div",
|
||
{ class: "search-searching muted" },
|
||
h("span", { class: "spinner", "aria-hidden": "true" }),
|
||
h("span", { text: "Searching…" }),
|
||
),
|
||
);
|
||
} else if (body.kind === "empty") {
|
||
nodes.push(h("div", { class: "search-empty muted", text: body.message }));
|
||
}
|
||
area.replaceChildren(...nodes);
|
||
}
|
||
|
||
/**
|
||
* One result row: a compact kind label (the accessibility counterpart of the
|
||
* app's type glyph), the title and — for a text match — the server snippet with
|
||
* the first case-insensitive query occurrence emphasised. A known payload is
|
||
* clickable and routes to its destination; an unknown/absent payload is rendered
|
||
* read-only and is never clickable. Every server string is set as text.
|
||
*/
|
||
function renderSearchResultRow(hit) {
|
||
const row = searchRow(hit, state.searchQuery);
|
||
const target = searchTarget(hit);
|
||
const element = h("div", {
|
||
class: `search-row${target ? " clickable" : " readonly"}`,
|
||
"data-kind": String(hit?.kind ?? ""),
|
||
});
|
||
if (target) {
|
||
const route = () => routeSearchResult(hit);
|
||
element.setAttribute("role", "button");
|
||
element.setAttribute("tabindex", "0");
|
||
if (target.kind === "pipeline") {
|
||
element.setAttribute("data-target", `pipeline:${target.pipelineId}:v${target.version}`);
|
||
} else if (target.matchedField) {
|
||
element.setAttribute("data-target", `run:${target.runId}:${target.sequence}:${target.matchedField}`);
|
||
} else {
|
||
element.setAttribute("data-target", `run:${target.runId}${target.sequence ? `:${target.sequence}` : ""}`);
|
||
}
|
||
element.addEventListener("click", route);
|
||
element.addEventListener("keydown", (event) => {
|
||
if (event.key === "Enter" || event.key === " ") {
|
||
event.preventDefault();
|
||
route();
|
||
}
|
||
});
|
||
}
|
||
element.append(h("span", { class: "search-kind muted", text: searchResultKindLabel(hit) }));
|
||
const main = h("div", { class: "search-row-main" });
|
||
main.append(h("div", { class: "search-row-title", text: row.title }));
|
||
if (row.snippet != null) {
|
||
const line = h("div", { class: "search-row-snippet muted" });
|
||
for (const span of row.snippet) {
|
||
if (span.matched) {
|
||
line.append(h("strong", { class: "search-match" }, h("u", {}, span.text)));
|
||
} else {
|
||
line.append(document.createTextNode(span.text));
|
||
}
|
||
}
|
||
main.append(line);
|
||
} else if (row.secondary) {
|
||
main.append(h("div", { class: "search-row-secondary muted", text: row.secondary }));
|
||
}
|
||
element.append(main);
|
||
return element;
|
||
}
|
||
|
||
/**
|
||
* Route one selected result through the page's existing navigation, exactly as
|
||
* the app does. The search is closed and cleared first, so every selection leaves
|
||
* the panel; a known payload then opens the pipeline detail (at the result
|
||
* version, 0 = latest), the run detail, the run-detail tab holding a text match,
|
||
* or the recorded visit's stage pane (the artifact route is that same pane). A
|
||
* visit that cannot be located falls back to the plain run detail. An unknown
|
||
* result has no target and never navigates.
|
||
*/
|
||
async function routeSearchResult(hit) {
|
||
const target = searchTarget(hit);
|
||
if (!target) return;
|
||
closeSearch();
|
||
state.error = "";
|
||
if (target.kind === "pipeline") {
|
||
state.view = "pipelines";
|
||
state.selectedRunId = null;
|
||
await selectPipeline({ id: target.pipelineId, version: target.version });
|
||
return;
|
||
}
|
||
state.view = "runs";
|
||
await selectRun(target.runId);
|
||
if (!state.runDetail) return;
|
||
const resolved = resolveRunTarget(target, target.runId, state.runDetail.steps ?? []);
|
||
if (resolved.tab) {
|
||
state.runTab = resolved.tab;
|
||
renderContent();
|
||
} else if (resolved.stageKey != null) {
|
||
openStagePane(resolved.stageKey, resolved.visitIndex);
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Actions
|
||
// ---------------------------------------------------------------------------
|
||
|
||
function setError(err) {
|
||
state.error = err instanceof Error ? err.message : String(err);
|
||
state.loading = false;
|
||
renderContent();
|
||
}
|
||
|
||
/**
|
||
* Validate the URL field, remember it and open the socket. Shared by Connect,
|
||
* the manual Reconnect control and the foreground recovery so all three take the
|
||
* same validate → persist → repo.connect path. `repo.connect` resets the
|
||
* attempt/backoff inside client.js, cancelling a pending retry delay.
|
||
*
|
||
* `surfaceError` is false for the background (foreground-recovery) caller so a
|
||
* stale, invalid URL field cannot spray an error into the UI on every
|
||
* visibilitychange/online event.
|
||
*/
|
||
function openConfiguredEndpoint({ surfaceError = true } = {}) {
|
||
const validated = validateServerUrl(state.url);
|
||
if (!validated.valid) {
|
||
if (surfaceError) {
|
||
state.error = validated.message;
|
||
renderContent();
|
||
}
|
||
return;
|
||
}
|
||
state.error = "";
|
||
localStorage.setItem(STORAGE_KEY, state.url.trim());
|
||
repo.connect(validated);
|
||
}
|
||
|
||
function onConnectClicked() {
|
||
if (state.connection.kind === "connected") {
|
||
repo.disconnect();
|
||
stopRunPoll();
|
||
return;
|
||
}
|
||
openConfiguredEndpoint();
|
||
// The `state` listener kicks off the initial load once connected.
|
||
}
|
||
|
||
/**
|
||
* The manual reconnect control (T3): re-open the same validated endpoint now.
|
||
* `repo.connect` (client.connect) resets the attempt/backoff, so a pending
|
||
* retry delay is cancelled and the socket is reopened immediately.
|
||
*/
|
||
function onReconnectClicked() {
|
||
openConfiguredEndpoint();
|
||
}
|
||
|
||
/**
|
||
* Return-to-foreground recovery (T4), the page's counterpart of
|
||
* ForegroundReconnector: called when the tab becomes visible again or the
|
||
* browser comes back online. Idle is the client's own deliberate-disconnect
|
||
* state and is left alone; Connecting and Disconnected are driven back to the
|
||
* socket at once, cancelling the pending backoff inside client.connect. A
|
||
* Connected socket is trusted because the browser's own online/visibility event
|
||
* is the liveness signal available to the page (it has no in-page positive ping
|
||
* probe like ForegroundReconnector.confirm()); that deviation is recorded in
|
||
* web/PARITY.md. Idempotent: repeated events just re-open the same endpoint.
|
||
*/
|
||
function onForegroundActive() {
|
||
if (foregroundAction(state.connection, true) !== ForegroundAction.Reconnect) return;
|
||
openConfiguredEndpoint({ surfaceError: false });
|
||
}
|
||
|
||
async function onConnected() {
|
||
let reply;
|
||
try {
|
||
reply = await repo.ping();
|
||
} catch (err) {
|
||
setError(err);
|
||
return;
|
||
}
|
||
// Remember the server's build/protocol so the banner can name a stale server
|
||
// and warn about a protocol mismatch (T5); the ping is the only source.
|
||
state.serverProtocol = reply?.protocol ?? null;
|
||
state.serverBuild = reply?.build ?? null;
|
||
renderBanner();
|
||
await loadCurrentView();
|
||
}
|
||
|
||
async function loadCurrentView(force = false) {
|
||
if (state.connection.kind !== "connected") {
|
||
state.error = "Connect to the server first.";
|
||
renderContent();
|
||
return;
|
||
}
|
||
if (state.view === "templates") {
|
||
await loadTemplates(force);
|
||
return;
|
||
}
|
||
if (state.view === "chat") {
|
||
await loadChatSessions(force);
|
||
return;
|
||
}
|
||
state.loading = true;
|
||
state.error = "";
|
||
renderContent();
|
||
try {
|
||
if (state.view === "pipelines") {
|
||
state.pipelines = await repo.listPipelines();
|
||
state.pipelinesLoaded = true;
|
||
// The last-run line joins list_runs onto the pipelines, so the history is
|
||
// fetched alongside them; runsLoaded distinguishes a genuinely empty
|
||
// history from one that has not arrived yet.
|
||
const { runs, usage } = await repo.listRuns();
|
||
state.runs = runs;
|
||
if (usage) state.usage = usage;
|
||
state.runsLoaded = true;
|
||
} else {
|
||
const { runs, usage } = await repo.listRuns();
|
||
state.runs = runs;
|
||
state.usage = usage;
|
||
state.runsLoaded = true;
|
||
}
|
||
state.loading = false;
|
||
renderContent();
|
||
// The run list the attention surface derives from has just (re)loaded, so
|
||
// bring the bell's badge up to date.
|
||
refreshAttentionBell();
|
||
// Keep the current selection fresh after a refresh.
|
||
if (force && state.view === "runs" && state.selectedRunId) {
|
||
await selectRun(state.selectedRunId, { silent: true });
|
||
}
|
||
} catch (err) {
|
||
setError(err);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Loads the template catalogue, then validates each template's source once and
|
||
* caches the parsed graph (null when it did not parse) so a card's stage count
|
||
* and the detail's stage list read the same result and can never disagree.
|
||
*/
|
||
async function loadTemplates(force = false) {
|
||
state.templateLoading = true;
|
||
state.error = "";
|
||
renderContent();
|
||
try {
|
||
state.templates = await repo.listTemplates();
|
||
for (const entry of state.templates) {
|
||
if (force || !state.templateGraphs.has(entry.key)) {
|
||
state.templateGraphs.set(entry.key, await validateTemplate(entry));
|
||
}
|
||
}
|
||
state.templateLoading = false;
|
||
renderContent();
|
||
} catch (err) {
|
||
state.templateLoading = false;
|
||
setError(err);
|
||
}
|
||
}
|
||
|
||
/** The parsed graph for a template, or null when the server cannot parse its source. */
|
||
async function validateTemplate(entry) {
|
||
try {
|
||
return await repo.validate(entry.source);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function selectTemplate(key) {
|
||
state.selectedTemplateKey = key;
|
||
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;
|
||
renderContent();
|
||
}
|
||
|
||
async function selectPipeline(summary) {
|
||
state.selectedPipelineId = summary.id;
|
||
state.pipelineDetail = null;
|
||
state.pipelineTab = "summary";
|
||
state.versionsExpanded = false;
|
||
renderContent();
|
||
try {
|
||
state.pipelineDetail = await repo.getPipeline(summary.id, summary.version);
|
||
renderContent();
|
||
} catch (err) {
|
||
setError(err);
|
||
}
|
||
}
|
||
|
||
async function selectRun(id, { silent = false } = {}) {
|
||
state.selectedRunId = id;
|
||
if (!silent) {
|
||
// A different run reseeds the detail: Summary tab, every section closed and
|
||
// no stage pane left over from the run the operator navigated away from. Drop
|
||
// the mounted run graph first so a live run's timer can never outlive it.
|
||
state.runGraph?.unmount();
|
||
state.runGraph = null;
|
||
state.runDetail = null;
|
||
state.runTab = "summary";
|
||
state.runSections = new Set();
|
||
state.runStagePane = null;
|
||
state.runStageSections = new Set();
|
||
// A different run reseeds the run-level action state, so a decision sheet,
|
||
// confirm dialog, rename field or failure report never leaks across runs.
|
||
state.runDecision = null;
|
||
state.decisionOpen = false;
|
||
state.decisionDraft = new DecisionDraft();
|
||
state.decisionSending = false;
|
||
state.decisionError = "";
|
||
state.confirmKind = null;
|
||
state.renameValue = null;
|
||
state.actionError = "";
|
||
renderContent();
|
||
}
|
||
try {
|
||
state.runDetail = await repo.getRun(id);
|
||
renderContent();
|
||
updateRunPoll();
|
||
} catch (err) {
|
||
if (!silent) setError(err);
|
||
else stopRunPoll();
|
||
}
|
||
}
|
||
|
||
function updateRunPoll() {
|
||
stopRunPoll();
|
||
if (state.view === "runs" && state.selectedRunId && isExecuting(state.runDetail)) {
|
||
runPoll = setInterval(() => selectRun(state.selectedRunId, { silent: true }), 1000);
|
||
}
|
||
}
|
||
|
||
function stopRunPoll() {
|
||
if (runPoll) {
|
||
clearInterval(runPoll);
|
||
runPoll = null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* (Re)start the shared runs-list clock: it ticks once a second only while a
|
||
* shown run is executing, updating each running row's meta line in place (never
|
||
* a full re-render, so an open filter/sort menu is not torn down). The elapsed
|
||
* value is derived from the run's server start timestamp, so it survives a
|
||
* reconnect.
|
||
*/
|
||
function refreshListClock() {
|
||
stopListClock();
|
||
listNow = Date.now();
|
||
if (state.view === "runs" && state.runs.some((run) => run.executing)) {
|
||
listClock = setInterval(() => {
|
||
listNow = Date.now();
|
||
for (const node of document.querySelectorAll(".run-row-meta[data-run-id]")) {
|
||
const id = Number(node.getAttribute("data-run-id"));
|
||
const run = state.runs.find((candidate) => candidate.id === id);
|
||
if (run && run.executing) node.textContent = metaText(run, listNow);
|
||
}
|
||
}, 1000);
|
||
}
|
||
}
|
||
|
||
function stopListClock() {
|
||
if (listClock) {
|
||
clearInterval(listClock);
|
||
listClock = null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* (Re)start the run detail's own clock: it ticks once a second only while the
|
||
* shown run is executing, updating just the Duration row in place (never a full
|
||
* re-render, so an open stage pane and its scroll are not torn down). The value
|
||
* is derived from the server's start timestamp, so it survives a reconnect.
|
||
*/
|
||
function refreshDetailClock() {
|
||
stopDetailClock();
|
||
detailNow = Date.now();
|
||
if (state.view === "runs" && isExecuting(state.runDetail)) {
|
||
detailClock = setInterval(() => {
|
||
detailNow = Date.now();
|
||
const node = document.querySelector(".run-duration[data-run-id]");
|
||
if (node && state.runDetail) node.textContent = runDurationText(state.runDetail, detailNow) ?? "";
|
||
}, 1000);
|
||
}
|
||
}
|
||
|
||
function stopDetailClock() {
|
||
if (detailClock) {
|
||
clearInterval(detailClock);
|
||
detailClock = null;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* (Re)start the chat indicator's clock: it ticks once a second only while the
|
||
* open conversation has a turn in flight, updating the phase, the elapsed and the
|
||
* per-tool `· long` marks in place (never a full re-render).
|
||
*/
|
||
function refreshChatClock() {
|
||
stopChatClock();
|
||
chatNow = Date.now();
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
if (state.view === "chat" && thread?.running) {
|
||
chatClock = setInterval(() => {
|
||
chatNow = Date.now();
|
||
updateChatIndicator(chatNow);
|
||
}, 1000);
|
||
}
|
||
}
|
||
|
||
function stopChatClock() {
|
||
if (chatClock) {
|
||
clearInterval(chatClock);
|
||
chatClock = null;
|
||
}
|
||
}
|
||
|
||
/** Refresh the running indicator in place from the thread's own state at [now]. */
|
||
function updateChatIndicator(now) {
|
||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||
const el = document.getElementById("chatRunning");
|
||
if (!thread?.running || !el) return;
|
||
const label = el.querySelector(".chat-running-label");
|
||
if (label) label.textContent = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING);
|
||
const elapsed = el.querySelector(".chat-running-elapsed");
|
||
if (elapsed) elapsed.textContent = `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`;
|
||
for (const part of threadRunningTools(thread.messages)) {
|
||
const line = el.querySelector(`.chat-running-tool[data-part-id="${String(part?.id ?? "")}"]`);
|
||
if (!line) continue;
|
||
const age = threadToolElapsedMillis(thread, part, now);
|
||
const toolElapsed = line.querySelector(".chat-running-tool-elapsed");
|
||
if (toolElapsed) toolElapsed.textContent = formatToolDuration(age);
|
||
const mark = line.querySelector(".chat-tool-long");
|
||
if (toolLongRunning(age) && !mark) {
|
||
line.classList.add("chat-running-tool-long");
|
||
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Boot
|
||
// ---------------------------------------------------------------------------
|
||
|
||
client.addEventListener("state", (event) => {
|
||
const next = event.detail;
|
||
const wasConnected = state.connection.kind === "connected";
|
||
const previousKind = state.connection.kind;
|
||
state.connection = next;
|
||
if (next.kind === "connected" && !wasConnected) {
|
||
onConnected();
|
||
}
|
||
if (next.kind !== "connected" && previousKind === "connected") {
|
||
stopRunPoll();
|
||
stopListClock();
|
||
stopDetailClock();
|
||
stopChatClock();
|
||
// The socket dropped: the server detaches every chat subscription with it
|
||
// (there is no chat_unsubscribe), and the frames feeding any running turn are
|
||
// gone, so no thread keeps claiming to run until a fresh frame proves it.
|
||
clearChatSubscriptions();
|
||
settleChatThreads();
|
||
}
|
||
// A reconnect (not a first connect): re-attach the open chat's stream and
|
||
// refresh its history wholesale, so a gap that swallowed the end of a turn is
|
||
// repaired rather than shown stale.
|
||
if (next.kind === "connected" && (previousKind === "connecting" || previousKind === "disconnected")) {
|
||
resyncOpenChat();
|
||
}
|
||
render();
|
||
});
|
||
|
||
// The client surfaces every unsolicited envelope as a DOM-free `frame` event
|
||
// (client.js). Only the chat stream is folded here; a frame for any other type is
|
||
// ignored.
|
||
client.addEventListener("frame", (event) => {
|
||
const message = event.detail;
|
||
if (!message || message.type !== Protocol.CHAT_EVENT) return;
|
||
const frame = message[ChatKeys.EVENT];
|
||
if (frame) onChatEvent(frame);
|
||
});
|
||
|
||
// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the
|
||
// omni-search field and the attention sheet are modal: Escape closes the topmost
|
||
// one (the artifact viewer or the diff viewer, when either is above, owns Escape
|
||
// first via its own listener). The attention sheet, when open, is the topmost
|
||
// overlay and owns Escape first. Registered once; every branch is a no-op when
|
||
// nothing is open.
|
||
document.addEventListener("keydown", (event) => {
|
||
if (event.key !== "Escape") return;
|
||
if (state.attentionSheetOpen) {
|
||
event.preventDefault();
|
||
closeAttentionSheet();
|
||
return;
|
||
}
|
||
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
|
||
if (state.templateCreateOpen) {
|
||
event.preventDefault();
|
||
closeTemplateCreateDialog();
|
||
return;
|
||
}
|
||
if (state.actionError) {
|
||
event.preventDefault();
|
||
dismissActionError();
|
||
return;
|
||
}
|
||
if (state.chatClose) {
|
||
event.preventDefault();
|
||
dismissChatClose();
|
||
return;
|
||
}
|
||
if (state.confirmKind) {
|
||
event.preventDefault();
|
||
dismissConfirm();
|
||
return;
|
||
}
|
||
if (state.decisionOpen) {
|
||
event.preventDefault();
|
||
closeDecisionSheet();
|
||
return;
|
||
}
|
||
if (state.runStagePane) {
|
||
event.preventDefault();
|
||
closeStagePane();
|
||
return;
|
||
}
|
||
if (state.searchOpen) {
|
||
event.preventDefault();
|
||
closeSearch();
|
||
}
|
||
});
|
||
|
||
// Return-to-foreground recovery (T4): the page becomes visible again, or the
|
||
// browser reports it is back online, and the client drives its socket back
|
||
// without waiting out the backoff. DOM-only, and idempotent.
|
||
document.addEventListener("visibilitychange", () => {
|
||
if (document.visibilityState === "visible") onForegroundActive();
|
||
});
|
||
window.addEventListener("online", onForegroundActive);
|
||
|
||
// Prefill from a previous session only; the user still confirms with Connect.
|
||
// The attention surface's dismissed identities are loaded once here, before the
|
||
// first render, so the bell's badge is correct from the very first paint.
|
||
state.attentionDismissed = loadAttentionDismissed();
|
||
render();
|