diff --git a/web/AGENTS.md b/web/AGENTS.md index dcdca318..349d8894 100644 --- a/web/AGENTS.md +++ b/web/AGENTS.md @@ -12,9 +12,10 @@ not this one, decides whether a feature is done. framework and no runtime dependency** — no React/Vue/Svelte, no bundler required. Keep it that way unless a concrete feature cannot be built without one, and say why in the item's note. -- **Simple but beautiful**: hand-written CSS (`styles.css`), the app's dark - palette and spacing, real attention to hierarchy and detail. "Simple" is about - the stack, never about the finish. +- **Simple but beautiful**: hand-written CSS split by area (`base.css`, + `lists.css`, `run-detail.css`, `chat.css`, `graph.css`, `dialogs.css`, + `settings.css`), the app's dark palette and spacing, real attention to + hierarchy and detail. "Simple" is about the stack, never about the finish. - **Trusted LAN/VPN only.** The server has no authentication; the page stores nothing but the server URL in `localStorage`. Never bake in a server address, never store secrets, never expose the API to an untrusted network. @@ -27,8 +28,11 @@ not this one, decides whether a feature is done. | `src/serverUrl.js` | `data/transport/ServerUrl.kt` | `validateServerUrl`, `resolveArtifactUrl` | | `src/client.js` | `data/transport/PipelinesClient.kt` | one reused socket, id matching, timeout, backoff. **DOM-free** | | `src/repository.js` | `data/PipelinesRepository.kt` | typed request builders | -| `src/app.js` | `ui/**` | the DOM UI. Grow it toward `PARITY.md` | -| `index.html`, `styles.css` | — | shell + styling | +| `src/app.js` | `ui/**` | page shell: boot, state, client wiring, connection/banner, navigation/routes, render dispatch, header | +| `src/dom.js` | — | `h()`, shared DOM helpers and clipboard/share actions | +| `src/format.js` | `ui/Format.kt` (DOM-facing bits) | status tone and error-text helpers | +| `src/views/*.js` | `ui/**` | one module per destination/dialog surface: attention, settings, pipelines, templates, runs, runDetail, chat, search, dialogs | +| `index.html`, `*.css` | — | shell + area styles linked in a fixed order | | `serve.mjs` | — | static server + `/connect` proxy | | `test/*.test.mjs` | `app/src/test/**` | `node --test`, no server needed | | `test/smoke.mjs` | — | protocol smoke against a live server | diff --git a/web/src/app.js b/web/src/app.js index 89319f82..686c44bc 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -1,16 +1,17 @@ -// 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. +// Spike web UI: the page shell. Boot, shared state, the one reused client and +// repository, connection/banner wiring, navigation + URL routes, render dispatch +// and the top bar. Feature views live under ./views/ and shared DOM/format +// helpers in ./dom.js and ./format.js. Every server value is set with +// textContent, never innerHTML. import { PipelinesClient, ProtocolError } from "./client.js"; -import { PipelinesRepository, SHELL_OUTPUT_LIMIT, newChatOperationId } from "./repository.js"; +import { PipelinesRepository } from "./repository.js"; import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js"; -import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js"; +import { validateServerUrl } from "./serverUrl.js"; import { ForegroundAction, RunStream, bannerState, foregroundAction, - liveBadgeState, protocolMismatch, serverBuildLabel, stateBadge, @@ -21,431 +22,48 @@ import { isTerminalRunStatus, runDetailNeedsFullSync, } from "./runEvents.js"; -import { - SERVER_URL_HELPER, - SERVER_URL_PLACEHOLDER, - TEMPLATES_CARD_LABEL, - TEMPLATES_CARD_SECONDARY, - TRUST_BODY, - TRUST_TITLE, - WORKSPACE_HELPER, - WORKSPACE_PLACEHOLDER, - canSaveWorkspace, - connectionActionKind, - connectionActions, - connectionCard, - readServerUrl, - readWorkspace, - savedWorkspaceLine, - workspaceErrorText, - writeServerUrl, - writeWorkspace, -} from "./settings.js"; -import { - ArtifactKind, - artifactCaptureNotes, - artifactGroups, - artifactKind, - artifactKindLabel, - artifactsHeader, - artifactsSummary, - artifactViewerPositionLabel, - displayVisit, - humanBytes, - pagedArtifacts, - pagedIndex, - presentedArtifacts, - resolvedArtifactUrl, - sessionExportArtifact, - viewerIndexByUrl, -} from "./artifacts.js"; -import { - PIPELINE_GRAPH_EMPTY, - RUN_GRAPH_MISSING, - RUN_GRAPH_NOTE, - layoutGraph, - mount as mountGraph, -} from "./graph.js"; +import { readServerUrl, readWorkspace, writeServerUrl } from "./settings.js"; +import { layoutGraph } from "./graph.js"; import { DEFAULT_ROUTE, parseRoute, serializeRoute } from "./routes.js"; +import { EMPTY_PIPELINE_FILTERS } from "./pipelines.js"; import { - 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 { - NOTIFICATION_RATIONALE, - NOTIFY_STORAGE_KEY, - createAlertLedger, - decodeNotificationSettings, - encodeNotificationSettings, - notificationEnvironment, - notificationPermissionState, -} from "./notify.js"; +import { runDurationText, runTimeline, clampVisitIndex } from "./runDetail.js"; +import { createAlertLedger } from "./notify.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 { DecisionDraft, pendingDecision } from "./actions.js"; +import { CHAT_TAB_TITLE } from "./chat.js"; +import { h } from "./dom.js"; +import { describeError, isExecuting } from "./format.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"; + createAttentionView, + loadAttentionDismissed, + loadNotifyAsked, +} from "./views/attention.js"; +import { createSettingsView } from "./views/settings.js"; +import { createPipelinesView } from "./views/pipelines.js"; +import { createTemplatesView } from "./views/templates.js"; +import { createRunsView } from "./views/runs.js"; +import { createDialogsView } from "./views/dialogs.js"; +import { createRunDetailView } from "./views/runDetail.js"; import { - BACKGROUND_TASKS_TITLE, - CHAT_ACTIONS_LABEL, - CHAT_ATTACH_LABEL, - CHAT_COMMAND_DISMISS_LABEL, - CHAT_COMMAND_GLYPH, - CHAT_COMPOSER_PLACEHOLDER, - CHAT_CREATE_BACK_LABEL, - CHAT_CREATE_CANCEL, - CHAT_CREATE_CONFIRM, - CHAT_CREATE_LOADING, - CHAT_CREATE_MODEL_NOTE, - CHAT_CREATE_PROMPT, - CHAT_CREATE_TITLE, - CHAT_EMPTY, - CHAT_FOLLOW_THRESHOLD_PX, - CHAT_HIDE_ACTION, - CHAT_LOADING, - CHAT_NEW_ACTION, - CHAT_NO_MATCH_ACTION, - CHAT_QUEUED_NOTICE, - CHAT_REMOVED_MESSAGE, - CHAT_RENAME_ACTION, - CHAT_RENAME_DISMISS, - CHAT_RENAME_FIELD_LABEL, - CHAT_RENAME_HELPER, - CHAT_RENAME_SAVE, - CHAT_RENAME_TITLE, - CHAT_SEARCH_LABEL, - CHAT_SEND_LABEL, - CHAT_STOP_LABEL, - CHAT_TAB_TITLE, - CHAT_UNDO_ACTION, - CLOSED_CHIP_LABEL, - CLOSED_SECTION_LABEL, - CLOSE_CHAT_ACTION, - CLOSE_CHAT_CONFIRM, - CLOSE_CHAT_DISMISS, - CLOSE_CHAT_TITLE, - COMPOSER_SEND, - COMPOSER_STOP, - CONVERSATION_EMPTY, - CONVERSATION_LOADING, - LOAD_OLDER_ACTION, - REOPEN_ACTION, - SELECT_CHAT_HINT, - APPROVAL_CONTROL_ALWAYS, - APPROVAL_CONTROL_ONCE, - APPROVAL_CONTROL_REJECT, - DECISION_ALWAYS, - DECISION_ONCE, - DECISION_REJECT, - RISK_REVIEW_LABEL, - WAITING_FOR_APPROVAL_LABEL, - SHELL_DETAILS_LABEL, - SHELL_OUTPUT_EMPTY, - SHELL_OUTPUT_ERROR, - SHELL_OUTPUT_LABELS, - SHELL_OUTPUT_LOADING, - SHELL_OUTPUT_READY, - SHELL_OUTPUT_UNAVAILABLE, - SHELL_ROW_LABEL, - applyChatEvent, - applyChatOverrides, - applyChatPermission, - appendChatNotice, - approvalCard, - attachmentDisplayName, - attachmentError, - attachmentFiles, - backgroundTasksRunningLabel, - chatBottomDistancePx, - chatCommandEffect, - chatCommandHelp, - chatCommandSuggestions, - chatCreateFailed, - chatCreateSucceeded, - chatFirstScroll, - chatFollowsAt, - chatHeaderMeta, - chatNoMatchMessage, - chatNoticeLabel, - chatOpensAtNewest, - chatShowJumpToLatest, - chatStartInLabel, - chatStreamState, - closeChatConfirmation, - composerAction, - composerCanSend, - composerSendEnabled, - composerSubmit, - decodeChatOverrides, - decodeChatSeen, - defaultDirectoryChoice, - directoryChoices, - directoryLabel, - dismissChatNotice as dismissChatNoticeModel, - emptyChatOverrides, - emptyChatSeen, - encodeChatOverrides, - encodeChatSeen, - filterSessions, - groupSessionsByDirectory, - hideChatOverride, - historyResync, - isChatSessionUnseen, - makeChatNotice, - markChatUnseen, - mergeHistoryPage, - mergeShellFrame, - newChatCreateState, - newChatThread, - parseChatInput, - queuedAfterFrame, - readChatSeen, - reasoningLabel, - renameChatOverride, - restoreChatOverride, - resumedThread, - runningAfterFrame, - runningBackgroundShells, - runningToolElapsedMillis, - seedChatSeen, - sessionActivity, - sessionActivityBadge, - sessionChipLabel, - sessionMeta, - sessionStatusLabel, - selectChatDirectory as selectChatDirectoryModel, - sessionTitle, - sessionWorkLabel, - settledThread, - shellCommandSummary, - shellOutputState, - shellsLoaded, - takeChatNoticeOffer as takeChatNoticeOfferModel, - formatToolDuration, - threadElapsedMillis, - threadPhase, - threadRunningTools, - threadToolElapsedMillis, - TURN_PHASE_WAITING, - toolCallCount, - toolCallRow, - toolCallsAnnouncement, - toolCallsLabel, - toolDetail, - toolFailed, - toolLabel, - toolLongRunning, - toolRunning, - toolsRunning, - transcriptRows, - turnElapsedMillis, - turnPhaseLabel, -} from "./chat.js"; -import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js"; + createChatView, + readChatScrollStore, + readChatDraftStore, + readChatOverridesStore, + readChatSeenStore, + readEphemeralChatIds, +} from "./views/chat.js"; +import { createSearchView } from "./views/search.js"; -/** - * The per-session chat scroll positions (C14). Persisted in localStorage, the - * browser analogue of the Android `ChatThread.scroll`: a position the operator - * deliberately left — including the very top — is restored, while an absent one - * opens the conversation at its newest message. - */ -const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1"; - -/** - * The per-chat composer drafts (C8). Mirrored into localStorage, the browser - * analogue of the Android store's per-device draft: a draft survives a reload, - * keyed by session id (attachments are memory-only — a File handle cannot be - * serialised). The in-memory `thread.draft` is the source of truth while the page - * is open; this is only the persistence beside it. - */ -const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1"; - -/** - * The operator's own chat changes (C13): local renames and hidden session ids, - * the web analogue of Android's `chat_overrides` preference. One JSON value: - * `{titles:{"":""},hidden:["<id>"]}`. A local title wins over the - * server's on every later list refresh; a hidden id only disappears here. - */ -const CHAT_OVERRIDES_STORAGE_KEY = "pipelines.web.chatOverrides.v1"; - -/** - * What the operator has already seen of the session list (C13), the web analogue - * of Android's `chat_seen` preference. One JSON value: - * `{seenAt:{"<id>":<updated_at ms>},unseen:["<id>"]}`. The watermark is advanced - * only by opening a chat (or first-sight seeding), never by a stale list. - */ -const CHAT_SEEN_STORAGE_KEY = "pipelines.web.chatSeen.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"; @@ -702,38 +320,6 @@ let listNow = Date.now(); // an open stage pane is not torn down), exactly as the runs list does. let detailClock = null; let detailNow = Date.now(); - -// The chat running indicator's own live clock (C5): it ticks once a second only -// while the open conversation has a turn in flight, updating just the indicator -// in place (never a full re-render), so the transcript's scroll is not disturbed. -let chatClock = null; -let chatNow = Date.now(); - -// --------------------------------------------------------------------------- -// DOM helpers -// --------------------------------------------------------------------------- - -function h(tag, props = {}, ...children) { - const node = document.createElement(tag); - for (const [key, value] of Object.entries(props)) { - if (value == null || value === false) continue; - if (key === "class") node.className = value; - else if (key === "text") node.textContent = value; - else if (key.startsWith("on") && typeof value === "function") { - node.addEventListener(key.slice(2).toLowerCase(), value); - } else node.setAttribute(key, value === true ? "" : String(value)); - } - for (const child of children.flat()) { - if (child == null || child === false) continue; - node.append(child instanceof Node ? child : document.createTextNode(String(child))); - } - return node; -} - -function isExecuting(run) { - return Boolean(run && run.executing); -} - /** Await one delay; used only by the bounded resync retry backoff. */ function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); @@ -757,10 +343,6 @@ const content = h("main", { id: "content" }); 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() { @@ -787,7 +369,7 @@ function setServerUrlDraft(value, sourceId) { // the same draft state too: a corrected URL can never leave the field announced // as invalid (or keep the stale "That is not a valid URL." message) just because // the correction happened in the header field. - if (document.getElementById("settingsServerUrl")) refreshServerUrlError(); + if (document.getElementById("settingsServerUrl")) views.settings.refreshServerUrlError(); } /** @@ -901,67 +483,6 @@ function searchHeaderControls() { }), ]; } - -/** - * 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 @@ -987,230 +508,6 @@ function connectionLabel() { 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(); - } -} - -/** - * Fold one pushed `run_event` frame into the notification ledger (L5). It does - * not touch the runs list (R10's fold is separate); it only decides whether this - * transition raises exactly one notification. A run already failed/waiting when - * seeded, a duplicate frame, a non-qualifying status and a key the operator - * dismissed all produce nothing. - */ -function onRunAlertFrame(frame) { - const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed }); - if (!alert || !notificationsAllowed()) return; - try { - const notification = new Notification(alert.title, { body: alert.body, tag: alert.key }); - notification.onclick = () => { - window.focus(); - state.view = "runs"; - render(); - selectRun(alert.runId); - }; - } catch { - // Some browsers can throw even with permission granted; the in-page Needs - // you surface remains the only honest channel and nothing is faked. - } -} - -/** True only when a real browser notification can be constructed right now. */ -function notificationsAllowed() { - return ( - typeof globalThis.Notification === "function" && - globalThis.isSecureContext === true && - globalThis.Notification.permission === "granted" - ); -} - -/** Persist only the asked flag; never a permission claim, endpoint or credential. */ -function persistNotifyAsked(asked) { - state.notifyAsked = Boolean(asked); - try { - localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked })); - } catch { - // Storage disabled or full: the in-memory flag still applies for this session. - } -} - -/** The asked flag from storage at boot; anything unreadable means never asked. */ -function loadNotifyAsked() { - try { - return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked; - } catch { - return false; - } -} - /** * The run-event watch for this connected epoch (R10) is established by * `startRunWatch`; it also seeds L5's notification ledger (the authoritative @@ -1313,6123 +610,6 @@ function tabButton(view, label) { }); } -// --- Settings (L1) --------------------------------------------------------- - -/** - * The Settings destination: the app's three sections (Connection, Workspace, - * Templates) in one pane. It is wiring only — every string, the workspace - * validation and the connection card's lines come from the pure `settings.js`, - * and the connection controls drive the page's existing single client through - * the same handlers the header uses (no second socket or path). Every - * server-derived string is set with textContent. - */ -function renderSettingsView() { - const pane = h("div", { class: "settings" }); - pane.append( - renderSettingsConnection(), - renderSettingsWorkspace(), - renderSettingsNotifications(), - renderSettingsTemplates(), - ); - return pane; -} - -function renderSettingsConnection() { - const section = h("section", { class: "settings-section" }); - section.append(h("h2", { class: "settings-title", text: "Connection" })); - - section.append( - h( - "label", - { class: "settings-field", for: "settingsServerUrl" }, - h("span", { class: "settings-field-label", text: "Server URL" }), - h("input", { - id: "settingsServerUrl", - type: "text", - placeholder: SERVER_URL_PLACEHOLDER, - value: state.url, - spellcheck: "false", - autocomplete: "off", - "aria-describedby": "settingsUrlHelper", - "aria-invalid": state.urlError ? "true" : null, - oninput: (event) => { - setServerUrlDraft(event.target.value, "settingsServerUrl"); - }, - }), - ), - ); - // Android's `urlError ?: helper` supporting text. The error clears on the next - // edit (AppViewModel.updateServerUrlDraft) and is announced as the field's own - // invalid state rather than as a page-level banner. - section.append( - h( - "p", - { - id: "settingsUrlHelper", - class: `settings-helper${state.urlError ? " settings-helper-error" : ""}`, - role: state.urlError ? "alert" : null, - }, - serverUrlSupportingText(), - ), - ); - - const actions = connectionActions(state.connection); - section.append( - h( - "div", - { class: "settings-actions" }, - h("button", { - id: "settingsPrimary", - class: "primary", - type: "button", - text: actions.primary, - onclick: () => runConnectionAction(actions.primary), - }), - h("button", { - id: "settingsSecondary", - class: "ghost", - type: "button", - text: actions.secondary, - onclick: () => runConnectionAction(actions.secondary), - }), - ), - ); - - const tone = bannerState(state.connection, { hasEndpoint: endpointConfigured() }).tone; - const card = h("div", { class: `settings-status status-${tone}` }); - const lines = connectionCard(state.connection, { - version: state.serverBuild?.version, - commit: state.serverBuild?.commit, - serverTime: state.serverTime, - }); - lines.forEach((line, index) => { - // Android's Connecting card leads its one line with a CircularProgressIndicator; - // the shared spinner is drawn only for that state, inline with the text, so the - // other three stay plain text. - if (index === 0 && state.connection.kind === "connecting") { - const row = h("div", { class: "settings-status-head" }); - row.append(h("span", { class: "spinner settings-status-spinner", "aria-hidden": "true" })); - row.append(h("p", { class: "settings-status-line", text: line })); - card.append(row); - return; - } - card.append(h("p", { class: "settings-status-line", text: line })); - }); - section.append(card, renderTrustWarning()); - return section; -} - -/** - * The Notifications section (L5). The Android rationale is shown verbatim; the - * status line is the pure permission view for this page's real browser facts. - * Only the explicit control asks for permission, never page load. When the API - * is unavailable, the page is insecure or permission is denied, the wording says - * plainly that the in-app Needs you surface is the only channel — no fake - * notification is ever drawn. - */ -function renderSettingsNotifications() { - const view = notificationPermissionState({ - ...notificationEnvironment(), - asked: state.notifyAsked, - }); - const section = h("section", { class: "settings-section", id: "settingsNotifications" }); - section.append(h("h2", { class: "settings-title", text: "Notifications" })); - section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE })); - section.append( - h("p", { - id: "settingsNotificationState", - class: `settings-notify-state settings-notify-${view.state}`, - role: "status", - text: view.body, - }), - ); - if (view.canRequest) { - section.append( - h( - "div", - { class: "settings-actions" }, - h("button", { - id: "settingsEnableNotifications", - class: "primary", - type: "button", - text: view.actionLabel, - onclick: requestNotifications, - }), - ), - ); - } - return section; -} - -/** - * Ask for notification permission from the operator's explicit click. The asked - * flag is persisted first and the page re-renders from the browser's real answer; - * a refused/dismissed prompt leaves the honest default/denied wording in place. - */ -function requestNotifications() { - persistNotifyAsked(true); - const ctor = globalThis.Notification; - if (typeof ctor !== "function" || !globalThis.isSecureContext) { - renderContent(); - return; - } - try { - const result = ctor.requestPermission(); - if (result && typeof result.then === "function") { - result.then( - () => renderContent(), - () => renderContent(), - ); - return; - } - } catch { - // A browser that refuses the request keeps the honest fallback wording. - } - renderContent(); -} - -/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */ -function renderTrustWarning() { - return h( - "div", - { class: "settings-warning" }, - h("p", { class: "settings-warning-title", text: TRUST_TITLE }), - h("p", { class: "settings-warning-body", text: TRUST_BODY }), - ); -} - -/** - * Route a Settings connection control through the page's existing single client, - * mirroring AppViewModel: Disconnect closes the shared socket, Connect is - * connect-only (validate + persist + open — never the header's toggle), and - * Reconnect re-opens the same validated endpoint now. Nothing here opens a second - * connection. - */ -function runConnectionAction(label) { - const kind = connectionActionKind(label); - if (kind === "disconnect") { - repo.disconnect(); - return; - } - if (kind === "reconnect") { - onReconnectClicked(); - return; - } - // The `Connect` label must never fall through to the header's toggle: while - // connected that would tear the live socket down (Android's connect() is - // connect-only). - openConfiguredEndpoint(); -} - -/** Android's `urlError ?: helper` supporting text for the Server URL field. */ -function serverUrlSupportingText() { - return state.urlError || SERVER_URL_HELPER; -} - -/** - * Update the Server URL field's own error state in place (supporting text, - * aria-invalid and the error tint) so an invalid Connect never needs a full - * re-render and the field being typed in is never rebuilt. - */ -function refreshServerUrlError() { - const field = document.getElementById("settingsServerUrl"); - const helper = document.getElementById("settingsUrlHelper"); - if (field) { - if (state.urlError) field.setAttribute("aria-invalid", "true"); - else field.removeAttribute("aria-invalid"); - } - if (helper) { - helper.textContent = serverUrlSupportingText(); - helper.classList.toggle("settings-helper-error", Boolean(state.urlError)); - if (state.urlError) helper.setAttribute("role", "alert"); - else helper.removeAttribute("role"); - } -} - -function renderSettingsWorkspace() { - const section = h("section", { class: "settings-section" }); - section.append(h("h2", { class: "settings-title", text: "Workspace" })); - section.append( - h( - "label", - { class: "settings-field", for: "settingsWorkspace" }, - h("span", { class: "settings-field-label", text: "Workspace path (on the server)" }), - h("input", { - id: "settingsWorkspace", - type: "text", - placeholder: WORKSPACE_PLACEHOLDER, - value: state.workspaceDraft, - spellcheck: "false", - autocomplete: "off", - "aria-describedby": "workspaceHelper", - "aria-invalid": workspaceErrorText(state.workspaceDraft) ? "true" : null, - oninput: (event) => { - state.workspaceDraft = event.target.value; - refreshWorkspaceControls(); - }, - }), - ), - ); - section.append( - h( - "p", - { - id: "workspaceHelper", - class: `settings-helper${workspaceErrorText(state.workspaceDraft) ? " settings-helper-error" : ""}`, - }, - workspaceSupportingText(), - ), - ); - section.append( - h("button", { - id: "saveWorkspace", - class: "primary settings-save", - type: "button", - text: "Save workspace", - disabled: !canSaveWorkspace(state.workspaceDraft), - onclick: saveWorkspace, - }), - ); - section.append(h("p", { id: "savedWorkspace", class: "settings-saved", text: savedWorkspaceLine(state.workspace) })); - return section; -} - -/** Android's `workspaceError ?: helper` supporting text for the workspace field. */ -function workspaceSupportingText() { - return workspaceErrorText(state.workspaceDraft) || WORKSPACE_HELPER; -} - -/** - * Update the workspace field's dependent controls in place (the helper/error line - * and the Save button's enabled state) so typing never re-renders — and so never - * blurs — the field being typed in. - */ -function refreshWorkspaceControls() { - const helper = document.getElementById("workspaceHelper"); - const invalid = Boolean(workspaceErrorText(state.workspaceDraft)); - if (helper) { - helper.textContent = workspaceSupportingText(); - helper.classList.toggle("settings-helper-error", invalid); - } - const field = document.getElementById("settingsWorkspace"); - if (field) { - if (invalid) field.setAttribute("aria-invalid", "true"); - else field.removeAttribute("aria-invalid"); - } - const save = document.getElementById("saveWorkspace"); - if (save) save.disabled = !canSaveWorkspace(state.workspaceDraft); -} - -/** Persist the workspace (trimmed) and update the `Saved workspace:` line. */ -function saveWorkspace() { - if (!canSaveWorkspace(state.workspaceDraft)) return; - state.workspace = writeWorkspace(localStorage, state.workspaceDraft); - state.workspaceDraft = state.workspace; - // Show the trimmed value that was actually stored, in the field as well as the - // saved line (both updated in place so the keyboard focus is not disturbed). - const field = document.getElementById("settingsWorkspace"); - if (field) field.value = state.workspace; - const saved = document.getElementById("savedWorkspace"); - if (saved) saved.textContent = savedWorkspaceLine(state.workspace); -} - -/** - * Reset the template detail/create state that belongs to a selection. Shared by - * selecting a template and opening the gallery from Settings, so the two lists of - * fields can never drift. - */ -function resetTemplateCreateState() { - state.templateTab = "summary"; - // A different template reseeds the create dialog, so a name typed for one - // template can never be submitted against another. - state.templateCreateOpen = false; - state.templateCreateName = ""; - state.templateCreateSending = false; - state.templateCreateError = ""; - state.templateCreateCreated = null; -} - -/** Clear the selection and everything that belongs to it. */ -function resetTemplateSelection() { - state.selectedTemplateKey = null; - resetTemplateCreateState(); -} - -/** - * Open the existing Templates gallery (L1's one card): switch the view, clear any - * selection/detail left from a previous visit and render. The gallery itself is - * unchanged — this is the same destination the Templates tab opens. - */ -function openTemplatesFromSettings() { - const route = { kind: "templates" }; - pushRoute(route); - applyRoute(route); -} - -function renderSettingsTemplates() { - const section = h("section", { class: "settings-section" }); - section.append(h("h2", { class: "settings-title", text: "Templates" })); - const card = h( - "button", - { - id: "browseTemplates", - class: "card settings-card", - type: "button", - onclick: openTemplatesFromSettings, - }, - // SettingsScreen.kt's row idiom: a leading glyph, the label and secondary - // line, then a forward chevron. - h("span", { class: "settings-card-glyph", "aria-hidden": "true", text: "\u25a4" }), - h( - "span", - { class: "settings-card-text" }, - h("span", { class: "card-name", text: TEMPLATES_CARD_LABEL }), - h("span", { class: "card-desc", text: TEMPLATES_CARD_SECONDARY }), - ), - h("span", { class: "settings-card-chevron", "aria-hidden": "true", text: "\u203a" }), - ); - section.append(card); - return section; -} - -function renderPipelineList() { - const list = h("div", { class: "list" }); - list.append(renderPipelineControls()); - const rows = h("div", { id: "pipelineRows" }); - fillPipelineRows(rows); - list.append(rows); - return list; -} - -/** - * The list's filter + sort toolbar and (when open) the matching menu panel. The - * rows themselves live in the separate `#pipelineRows` container so a keystroke - * in the name filter can refresh just the rows without rebuilding (and so - * blurring) the input the operator is typing in. - */ -function renderPipelineControls() { - const filters = state.pipelineFilters; - const count = pipelineFilterCount(filters); - const panel = state.pipelineMenu; - const controls = h( - "div", - { class: "list-controls" }, - h( - "div", - { class: "list-toolbar" }, - h( - "button", - { - id: "filterToggle", - class: `control${panel === "filter" ? " active" : ""}`, - onclick: () => { - state.pipelineMenu = panel === "filter" ? null : "filter"; - renderContent(); - }, - }, - h("span", { text: "Filter" }), - h("span", { id: "filterCount", class: "count", text: count ? ` (${count})` : "" }), - ), - h("button", { - id: "sortToggle", - class: `control${panel === "sort" ? " active" : ""}`, - text: `Sort: ${pipelineSortLabel(state.pipelineSort)}`, - onclick: () => { - state.pipelineMenu = panel === "sort" ? null : "sort"; - renderContent(); - }, - }), - h("button", { - id: "clearFilters", - class: "ghost clear", - text: "Clear filters", - hidden: count === 0, - onclick: clearPipelineFilters, - }), - ), - ); - if (panel === "filter") controls.append(renderFilterPanel()); - if (panel === "sort") controls.append(renderSortPanel()); - return controls; -} - -function renderFilterPanel() { - const filters = state.pipelineFilters; - const panel = h("div", { class: "menu-panel filter-panel" }); - panel.append(h("div", { class: "filter-section", text: "Name" })); - panel.append( - h( - "label", - { class: "filter-field" }, - h("span", { class: "filter-field-label", text: "Pipeline name contains" }), - h("input", { - id: "pipelineNameFilter", - type: "text", - value: filters.name, - spellcheck: "false", - oninput: (e) => { - state.pipelineFilters = { ...state.pipelineFilters, name: e.target.value }; - // Targeted refresh: the input keeps focus and its value while the - // list narrows behind it. - refreshPipelineRows(); - }, - }), - ), - ); - panel.append(h("div", { class: "filter-section", text: "Runs" })); - for (const presence of RUN_PRESENCES) { - panel.append( - h( - "label", - { class: "filter-item" }, - h("input", { - type: "radio", - name: "runPresence", - checked: filters.presence === presence.key, - onchange: () => { - state.pipelineFilters = { ...state.pipelineFilters, presence: presence.key }; - renderContent(); - }, - }), - h("span", { text: presence.label }), - ), - ); - } - panel.append(h("div", { class: "filter-section", text: "Last run status" })); - for (const status of RUN_STATUS_FILTERS) { - panel.append( - h( - "label", - { class: "filter-item" }, - h("input", { - id: `status-${status}`, - type: "checkbox", - checked: filters.lastRunStatuses.includes(status), - onchange: (e) => { - const next = e.target.checked - ? [...state.pipelineFilters.lastRunStatuses, status] - : state.pipelineFilters.lastRunStatuses.filter((s) => s !== status); - state.pipelineFilters = { ...state.pipelineFilters, lastRunStatuses: next }; - renderContent(); - }, - }), - h("span", { text: status }), - ), - ); - } - panel.append( - h("div", { class: "filter-actions" }, h("button", { class: "ghost", text: "Clear filters", onclick: clearPipelineFilters })), - ); - return panel; -} - -function renderSortPanel() { - const panel = h("div", { class: "menu-panel sort-panel" }); - for (const option of PIPELINE_SORTS) { - panel.append( - h("button", { - class: `sort-option${state.pipelineSort === option.key ? " active" : ""}`, - text: option.label, - onclick: () => { - state.pipelineSort = option.key; - state.pipelineMenu = null; - renderContent(); - }, - }), - ); - } - panel.append( - h( - "div", - { class: "filter-actions" }, - h("button", { - class: "ghost", - text: "Reset", - onclick: () => { - state.pipelineSort = "server_order"; - state.pipelineMenu = null; - renderContent(); - }, - }), - ), - ); - return panel; -} - -/** Re-renders the rows and the toolbar's active-filter badge after a filter change. */ -function refreshPipelineRows() { - const rows = document.getElementById("pipelineRows"); - if (rows) fillPipelineRows(rows); - const count = pipelineFilterCount(state.pipelineFilters); - const badge = document.getElementById("filterCount"); - if (badge) badge.textContent = count ? ` (${count})` : ""; - const clear = document.getElementById("clearFilters"); - if (clear) clear.hidden = count === 0; -} - -/** Sorts, filters and renders the pipeline rows (or the matching empty state) into `rowsEl`. */ -function fillPipelineRows(rowsEl) { - const latestRuns = latestRunByPipeline(state.runs); - const runsKnown = state.runsLoaded; - const now = Date.now(); - const nodes = []; - if (state.loading && !state.pipelines.length) { - nodes.push(h("div", { class: "muted pad", text: "Loading pipelines…" })); - } else if (!state.pipelinesLoaded) { - nodes.push(h("div", { class: "muted pad", text: "Connect to the server to load pipelines." })); - } else { - const sorted = sortPipelines(state.pipelines, state.pipelineSort, latestRuns); - const items = filterPipelines(sorted, state.pipelineFilters, latestRuns, runsKnown); - if (items.length) { - for (const pipeline of items) nodes.push(renderPipelineRow(pipeline, latestRuns, runsKnown, now)); - } else { - const empty = pipelineListEmptyState(state.pipelines, items, state.pipelineFilters); - const box = h("div", { class: "empty pad" }, h("div", { class: "muted", text: empty.message })); - if (empty.clearAction) { - box.append(h("button", { class: "ghost", text: empty.clearAction, onclick: clearPipelineFilters })); - } - nodes.push(box); - } - } - rowsEl.replaceChildren(...nodes); -} - -function renderPipelineRow(pipeline, latestRuns, runsKnown, now) { - const children = [ - h("span", { class: "row-title", text: pipeline.name || `pipeline ${pipeline.id}` }), - h("span", { class: "row-meta", text: pipelineSubtitle(pipeline) }), - ]; - const updated = pipelineUpdatedLine(pipeline); - if (updated) children.push(h("span", { class: "row-meta", text: updated })); - if (runsKnown) { - const run = latestRuns.get(pipeline.id); - if (!run) { - children.push(h("span", { class: "row-meta muted", text: "no runs recorded" })); - } else { - const badge = runBadge(run, now); - children.push( - h( - "span", - { class: "row-run" }, - h("span", { class: `chip chip-${badge.state}`, text: badge.state }), - h("span", { class: "row-meta", text: runBadgeMetaLine(badge) }), - ), - ); - } - } - return h( - "button", - { class: `row${state.selectedPipelineId === pipeline.id ? " selected" : ""}`, onclick: () => selectPipeline(pipeline) }, - ...children, - ); -} - -function renderPipelineDetail() { - const d = state.pipelineDetail; - const pane = h("div", { class: "detail" }); - if (!d) { - pane.append(h("div", { class: "muted pad", text: "Select a pipeline." })); - return pane; - } - pane.append(h("h2", { text: d.name || `pipeline ${d.id}` })); - pane.append( - h( - "div", - { class: "detail-tabs" }, - ...PIPELINE_DETAIL_TABS.map((tab) => - h("button", { - class: `detail-tab${state.pipelineTab === tab.key ? " active" : ""}`, - text: tab.label, - onclick: () => { - state.pipelineTab = tab.key; - renderContent(); - }, - }), - ), - ), - ); - if (state.pipelineTab === "graph") { - pane.append(h("p", { class: "graph-note muted", text: graphNote() })); - const stages = d.graph?.stages ?? []; - if (!stages.length) { - pane.append(h("div", { class: "muted pad", text: PIPELINE_GRAPH_EMPTY })); - return pane; - } - const host = h("div", { class: "graph-host" }); - pane.append(host); - state.pipelineGraph = mountGraph(host, d.graph, { - expanded: state.pipelineGraphExpanded, - selectedKey: state.pipelineGraphSelection, - onSelectionChange: (key) => { - // The graph has already opened or closed its own definition pane; record - // the destination in the URL without rebuilding the graph. - state.pipelineGraphSelection = key; - const id = state.selectedPipelineId; - if (!id) return; - const version = state.pipelineRequestedVersion ?? 0; - pushRoute( - key - ? { kind: "pipelineStage", id, version, stageKey: key } - : { kind: "pipeline", id, version }, - ); - }, - onExpandedChange: (value) => { - state.pipelineGraphExpanded = value; - }, - }); - return pane; - } - if (state.pipelineTab === "source") { - pane.append(h("pre", { class: "source-code" }, h("code", { text: d.source || "" }))); - return pane; - } - pane.append(h("div", { class: "detail-subtitle muted", text: pipelineSubtitle({ ...d, stages: d.graph?.stages?.length ?? d.stages }) })); - const rows = h("div", { class: "kv" }); - for (const field of summaryFields(d)) { - rows.append( - h( - "div", - { class: "kv-row" }, - h("span", { class: "kv-key", text: field.key }), - h("span", { class: `kv-val${field.monospace ? " monospace" : ""}`, text: field.value }), - ), - ); - } - pane.append(rows); - pane.append( - h( - "button", - { - class: "section-toggle", - onclick: () => { - state.versionsExpanded = !state.versionsExpanded; - renderContent(); - }, - }, - h("span", { class: "chevron", text: state.versionsExpanded ? "\u25be" : "\u25b8" }), - h("span", { text: "Versions" }), - ), - ); - if (state.versionsExpanded) { - const versions = d.versions ?? []; - const body = h("div", { class: "section-body versions-list" }); - if (!versions.length) { - body.append(h("div", { class: "muted", text: "No versions recorded." })); - } else { - for (const version of versions) { - const row = versionRow(version); - body.append( - h( - "div", - { class: "version-row" }, - h("span", { class: "version-title", text: row.versionLabel }), - h("span", { class: "muted", text: row.stagesText }), - row.createdText ? h("span", { class: "muted", text: row.createdText }) : null, - ), - ); - } - } - pane.append(body); - } - return pane; -} - -// --- Templates ------------------------------------------------------------- - -/** The cached parsed graph for a template key, or null when it did not parse. */ -function templateGraphFor(key) { - return state.templateGraphs.has(key) ? state.templateGraphs.get(key) : null; -} - -function renderTemplateGallery() { - const pane = h("div", { class: "list gallery" }); - pane.append( - h( - "div", - { class: "pane-head" }, - h("h2", { text: "Templates" }), - h("button", { class: "ghost", text: "Refresh templates", onclick: () => loadTemplates(true) }), - ), - ); - if (state.templateLoading && !state.templates.length) { - pane.append(h("div", { class: "muted pad", text: "Loading templates…" })); - return pane; - } - if (!state.templates.length) { - pane.append(h("div", { class: "muted pad", text: "No templates are available on this server." })); - return pane; - } - const cards = h("div", { class: "cards" }); - for (const entry of state.templates) { - const card = templateCard(entry, templateGraphFor(entry.key)); - cards.append( - h( - "button", - { - class: `card${state.selectedTemplateKey === entry.key ? " selected" : ""}`, - onclick: () => selectTemplate(entry.key), - }, - h("span", { class: "card-name", text: templateGalleryName(card.name) }), - h("span", { class: "card-desc", text: card.description }), - h("span", { class: "card-meta", text: templateStageCountLabel(card.stageCount) }), - ), - ); - } - pane.append(cards); - return pane; -} - -function renderTemplateDetail() { - const pane = h("div", { class: "detail" }); - const entry = state.templates.find((t) => t.key === state.selectedTemplateKey); - if (!entry) { - pane.append(h("div", { class: "muted pad", text: "Select a template." })); - return pane; - } - const graph = templateGraphFor(entry.key); - pane.append(renderTemplateDetailActions()); - pane.append( - h( - "div", - { class: "tabstrip" }, - templateTabButton("summary", "Summary"), - templateTabButton("graph", "Graph"), - templateTabButton("source", "Source"), - ), - ); - if (state.templateTab === "graph") pane.append(renderTemplateGraphTab(graph)); - else if (state.templateTab === "source") pane.append(renderTemplateSourceTab(entry, graph)); - else pane.append(renderTemplateSummaryTab(entry, graph)); - if (state.templateCreateOpen) pane.append(renderTemplateCreateDialog(entry)); - return pane; -} - -/** - * The template detail's action row: the one "Create pipeline from this - * template" action (P5), matching the app's top-bar add action. It opens the - * dialog; it never submits on its own. - */ -function renderTemplateDetailActions() { - return h( - "div", - { class: "detail-actions" }, - h("button", { - class: "ghost template-create-open", - type: "button", - text: CREATE_ACTION_LABEL, - onclick: () => openTemplateCreateDialog(), - }), - ); -} - -/** Open the create dialog with a fresh, empty name; nothing is sent until Create. */ -function openTemplateCreateDialog() { - state.templateCreateOpen = true; - state.templateCreateName = ""; - state.templateCreateSending = false; - state.templateCreateError = ""; - state.templateCreateCreated = null; - renderContent(); - document.querySelector(".template-create-name")?.focus(); -} - -/** Dismiss the create dialog (never while a validate+submit is in flight). */ -function closeTemplateCreateDialog() { - if (state.templateCreateSending) return; - state.templateCreateOpen = false; - state.templateCreateName = ""; - state.templateCreateError = ""; - state.templateCreateCreated = null; - renderContent(); -} - -/** - * The create dialog (P5): the title, the one required name field, the note, the - * server's refusal text or the success line, and Create/Cancel (Cancel reads - * Close after a success). Create is disabled while the name is blank or while - * sending; the field locks while sending and after a success. Every server - * string is set with textContent. - */ -function renderTemplateCreateDialog(entry) { - const title = createFormTitle(entry); - const overlay = h("div", { - class: "template-create-dialog", - role: "dialog", - "aria-modal": "true", - "aria-label": title, - }); - overlay.addEventListener("click", (event) => { - if (event.target === overlay) closeTemplateCreateDialog(); - }); - const panel = h("div", { class: "template-create-panel" }); - panel.append(h("h2", { class: "template-create-title", text: title })); - - const field = h("label", { class: "template-create-field" }); - field.append(h("span", { class: "template-create-label", text: CREATE_NAME_LABEL })); - field.append( - h("input", { - class: "template-create-name", - type: "text", - value: state.templateCreateName, - spellcheck: "false", - autocomplete: "off", - disabled: state.templateCreateSending || state.templateCreateCreated != null, - oninput: (event) => { - // Update in place (no re-render) so the field keeps focus and its caret; - // only the confirm button's enabled state depends on the name. - state.templateCreateName = event.target.value; - const confirm = overlay.querySelector(".template-create-confirm"); - if (confirm) { - confirm.disabled = !createFormValid(state.templateCreateName, { - sending: state.templateCreateSending, - created: state.templateCreateCreated, - }); - } - }, - }), - ); - panel.append(field); - panel.append(h("p", { class: "template-create-note muted", text: CREATE_NOTE })); - if (state.templateCreateError) { - panel.append(h("div", { class: "template-create-error bad", text: state.templateCreateError })); - } - if (state.templateCreateCreated != null) { - panel.append( - h("div", { - class: "template-create-success", - text: createSuccessMessage(state.templateCreateCreated), - }), - ); - } - - const actions = h("div", { class: "template-create-actions" }); - actions.append( - h("button", { - class: "ghost template-create-cancel", - type: "button", - text: createDismissLabel(state.templateCreateCreated), - disabled: state.templateCreateSending, - onclick: closeTemplateCreateDialog, - }), - ); - actions.append( - h("button", { - class: "template-create-confirm", - type: "button", - text: createConfirmLabel(state.templateCreateSending), - disabled: !createFormValid(state.templateCreateName, { - sending: state.templateCreateSending, - created: state.templateCreateCreated, - }), - onclick: () => createFromTemplate(entry), - }), - ); - panel.append(actions); - overlay.append(panel); - return overlay; -} - -/** - * The P5 submit flow, exactly the app's: validate the template's source first - * and, when the server refuses to parse it, show its own error in the dialog and - * send nothing; otherwise submit the source create-only with the chosen name. On - * success remember the created name, refresh the pipeline list so the new row is - * visible and leave the dialog open (Cancel now reads Close); on failure show - * the server's error without closing. - */ -async function createFromTemplate(entry) { - if ( - !createFormValid(state.templateCreateName, { - sending: state.templateCreateSending, - created: state.templateCreateCreated, - }) - ) { - return; - } - const name = state.templateCreateName; - state.templateCreateSending = true; - state.templateCreateError = ""; - renderContent(); - try { - await repo.validate(entry.source); - } catch (error) { - state.templateCreateSending = false; - state.templateCreateError = describeError(error); - renderContent(); - return; - } - try { - const detail = await repo.submit(name, entry.source); - state.templateCreateSending = false; - state.templateCreateCreated = createdPipelineName(detail, name); - await refreshPipelines(); - } catch (error) { - state.templateCreateSending = false; - state.templateCreateError = describeError(error); - } - renderContent(); -} - -/** - * Refresh just the pipeline summaries after a create so the new row appears when - * the operator returns to the Pipelines list. A failed refresh keeps the created - * name and is surfaced through the banner rather than discarded. - */ -async function refreshPipelines() { - try { - state.pipelines = await repo.listPipelines(); - state.pipelinesLoaded = true; - } catch (error) { - state.error = describeError(error); - } -} - -function templateTabButton(tab, label) { - return h("button", { - class: `minitab${state.templateTab === tab ? " active" : ""}`, - text: label, - onclick: () => { - state.templateTab = tab; - renderContent(); - }, - }); -} - -function renderTemplateSummaryTab(entry, graph) { - const wrap = h("div", { class: "tabbody" }); - wrap.append(h("h2", { text: templateDetailName(entry) })); - if ((entry.description ?? "").trim()) { - wrap.append(h("p", { class: "body", text: entry.description })); - } - wrap.append(h("div", { class: "kv" }, kvMono("Key", entry.key))); - wrap.append( - h("div", { class: "meta-line", text: templateStageCountLabel(graph?.stages?.length ?? null) }), - ); - if (entry.scheduled) wrap.append(h("div", { class: "meta-line", text: "Includes a schedule" })); - - const summary = templateStageSummary(graph); - if (summary.note) { - wrap.append(h("div", { class: "muted pad", text: summary.note })); - return wrap; - } - wrap.append(h("h3", { text: "Stages" })); - const ul = h("ul", { class: "stages" }); - for (const stage of summary.stages) { - ul.append( - h( - "li", - {}, - h("code", { text: stage.key }), - h("span", { class: "chip", text: effectiveStageType(stage.type) }), - ), - ); - } - wrap.append(ul); - return wrap; -} - -function renderTemplateGraphTab(graph) { - const wrap = h("div", { class: "tabbody" }); - wrap.append(h("p", { class: "muted", text: templateGraphNote(graph) })); - return wrap; -} - -function renderTemplateSourceTab(entry, graph) { - const wrap = h("div", { class: "tabbody" }); - if (graph == null) { - wrap.append(h("p", { class: "muted", text: TEMPLATE_UNPARSED_SOURCE_NOTE })); - } - wrap.append( - h( - "div", - { class: "codeblock" }, - h("div", { class: "codeblock-label", text: "Definition source" }), - h("pre", { class: "codeblock-body", text: entry.source ?? "" }), - ), - ); - return wrap; -} - -function pipelineSortLabel(key) { - return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label; -} - -function clearPipelineFilters() { - state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS }; - renderContent(); -} - -function renderRunList() { - const pane = h("div", { class: "list runs" }); - pane.append(renderRunToolbar()); - - const scroll = h("div", { class: "run-scroll" }); - if (state.loading && !state.runs.length) { - scroll.append(h("div", { class: "muted pad", text: "Loading…" })); - pane.append(scroll); - return pane; - } - - const filters = state.runFilters; - const today = localDayKey(new Date()); - const filtered = filterRuns(state.runs, filters, today); - const groups = groupRunsByDay(filtered, today, undefined, runComparator(state.runSort)); - const entries = runListEntries( - state.usage, - state.runs.length === 0, - filtered.length === 0 && state.runs.length > 0, - groups, - "", - ); - - for (const entry of entries) { - switch (entry.kind) { - case "usage": - scroll.append(renderUsage(entry.usage)); - break; - case "empty": - scroll.append(renderEmptyState(entry)); - break; - case "day": - scroll.append(h("div", { class: "day-header", text: entry.label })); - break; - case "run": - scroll.append(renderRunRow(entry.run)); - break; - case "error": - scroll.append(h("div", { class: "run-list-error", text: entry.message })); - break; - } - } - pane.append(scroll); - return pane; -} - -function renderUsage(usage) { - const metrics = h("div", { class: "metrics" }); - metrics.append(metric("Total", String(usage.total ?? 0), "total")); - if ((usage.average_seconds ?? 0) > 0) { - metrics.append(metric("Average", formatDuration(usage.average_seconds), "average")); - } - metrics.append(metric("Succeeded", String(usage.succeeded ?? 0), "succeeded")); - metrics.append(metric("Failed", String(usage.failed ?? 0), "failed")); - metrics.append(metric("Canceled", String(usage.canceled ?? 0), "canceled")); - metrics.append(metric("Interrupted", String(usage.interrupted ?? 0), "interrupted")); - metrics.append(metric("Active", String(usage.active ?? 0), "active")); - return metrics; -} - -function metric(label, value, cls) { - return h( - "div", - { class: `metric metric-${cls}` }, - h("span", { class: "metric-value", text: value }), - h("span", { class: "metric-label", text: label }), - ); -} - -function renderEmptyState(entry) { - const wrap = h("div", { class: "empty-state" }, h("span", { text: entry.message })); - if (entry.actionLabel) { - wrap.append(h("button", { class: "ghost", text: entry.actionLabel, onclick: clearRunFilters })); - } - return wrap; -} - -/** - * One run row, in the app's exact hierarchy: status chip (+ spinner while - * executing); primary line = stored title else pipeline name, carrying the - * version chip when there is no title; the pipeline name + version chip on a - * second line only when a title exists; the progress line; the meta line; and - * the diagnostic line, in the error colour only on a failure. Every - * server-provided string is set with textContent. - */ -function renderRunRow(run) { - const status = runStateOf(run.status); - const identity = runIdentity(run.title, run.name); - const row = h("button", { - class: `row run-row${state.selectedRunId === run.id ? " selected" : ""}`, - onclick: () => selectRun(run.id), - }); - - const head = h("span", { class: "run-row-head" }); - head.append(h("span", { class: `chip chip-${status}`, text: status })); - if (run.executing) head.append(h("span", { class: "spinner", "aria-hidden": "true" })); - head.append(h("span", { class: "run-row-title", text: identity.label })); - if (identity.pipeline == null) head.append(versionChip(run.version)); - row.append(head); - - if (identity.pipeline != null) { - row.append( - h( - "span", - { class: "run-row-pipeline" }, - h("span", { class: "run-row-pipeline-name", text: identity.pipeline }), - versionChip(run.version), - ), - ); - } - - row.append(h("span", { class: "run-row-progress", text: progressText(run) })); - row.append( - h("span", { - class: "run-row-meta", - "data-run-id": String(run.id), - text: metaText(run, listNow), - }), - ); - if (String(run.diagnostic ?? "").trim()) { - row.append( - h("span", { - class: `run-row-diag${status === "failed" ? " error" : ""}`, - text: run.diagnostic, - }), - ); - } - return row; -} - -function versionChip(version) { - return h("span", { class: "version-chip", text: versionLabel(version) }); -} - -function renderRunToolbar() { - const activeCount = runFiltersActiveCount(state.runFilters); - const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter"; - const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label; - - const toolbar = h("div", { class: "run-toolbar" }); - toolbar.append( - h( - "div", - { class: "menu-anchor" }, - h("button", { - id: "runFilterBtn", - class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`, - title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs", - text: filterLabel, - "data-active-count": String(activeCount), - onclick: () => toggleMenu("filter"), - }), - state.openMenu === "filter" ? renderFilterMenu() : null, - ), - h( - "div", - { class: "menu-anchor" }, - h("button", { - id: "runSortBtn", - class: "ghost sort-btn", - title: "Sort runs", - text: `Sort: ${sortLabel}`, - onclick: () => toggleMenu("sort"), - }), - state.openMenu === "sort" ? renderSortMenu() : null, - ), - h("span", { class: "spacer" }), - renderLiveBadge(liveBadgeState(state.runStream)), - ); - return toolbar; -} - -/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */ -function renderLiveBadge(info) { - return h( - "span", - { class: `live-badge live-${info.tone}`, title: info.title ?? "Live run stream" }, - h("span", { class: "live-dot", "aria-hidden": "true" }), - h("span", { class: "live-word", text: info.label }), - ); -} - -function renderFilterMenu() { - const filters = state.runFilters; - const menu = h("div", { class: "menu filter-menu", id: "runFilterMenu" }); - menu.append(h("div", { class: "menu-section", text: "Status" })); - for (const status of RUN_STATES) { - menu.append( - filterCheck(status, filters.statuses.has(status), () => toggleStatusFilter(status), { - "data-status": status, - }), - ); - } - menu.append(h("div", { class: "menu-divider" })); - menu.append(h("div", { class: "menu-section", text: "Pipeline" })); - menu.append( - filterCheck("Any pipeline", filters.pipelineId == null, () => setPipelineFilter(null), { - "data-pipeline": "any", - }), - ); - for (const option of pipelineFilterOptions(state.runs)) { - menu.append( - filterCheck(option.name, filters.pipelineId === option.id, () => setPipelineFilter(option.id), { - "data-pipeline": String(option.id), - }), - ); - } - menu.append(h("div", { class: "menu-divider" })); - menu.append(h("div", { class: "menu-section", text: "Time range" })); - for (const range of RUN_TIME_RANGES) { - menu.append( - filterCheck(range.label, filters.timeRange === range.value, () => setTimeRangeFilter(range.value), { - "data-time": range.value, - }), - ); - } - menu.append( - h( - "div", - { class: "menu-actions" }, - h("button", { class: "ghost", text: "Clear filters", onclick: clearRunFilters }), - h("button", { class: "ghost", text: "Done", onclick: closeMenu }), - ), - ); - return menu; -} - -function filterCheck(label, checked, onclick, data = {}) { - return h( - "label", - { class: "filter-check" }, - h("input", { - type: "checkbox", - checked: checked ? "checked" : null, - onchange: onclick, - ...data, - }), - h("span", { text: label }), - ); -} - -function renderSortMenu() { - const menu = h("div", { class: "menu sort-menu", id: "runSortMenu" }); - for (const option of RUN_SORTS) { - menu.append( - h("button", { - class: `menu-item${state.runSort === option.value ? " selected" : ""}`, - text: option.label, - onclick: () => { - state.runSort = option.value; - closeMenu(); - }, - }), - ); - } - menu.append(h("div", { class: "menu-divider" })); - menu.append( - h("button", { - class: "menu-item", - text: "Reset", - onclick: () => { - state.runSort = DEFAULT_RUN_SORT; - closeMenu(); - }, - }), - ); - return menu; -} - -function toggleStatusFilter(status) { - const next = new Set(state.runFilters.statuses); - if (next.has(status)) next.delete(status); - else next.add(status); - state.runFilters = { ...state.runFilters, statuses: next }; - renderContent(); -} - -function setPipelineFilter(pipelineId) { - state.runFilters = { ...state.runFilters, pipelineId }; - closeMenu(); -} - -function setTimeRangeFilter(timeRange) { - state.runFilters = { ...state.runFilters, timeRange }; - closeMenu(); -} - -function clearRunFilters() { - state.runFilters = defaultRunFilters(); - closeMenu(); -} - -function toggleMenu(name) { - state.openMenu = state.openMenu === name ? null : name; - renderContent(); -} - -function closeMenu() { - state.openMenu = null; - renderContent(); -} - -/** - * The run detail: a tab strip (Summary / Graph / Input / Output / Timeline) over - * the selected tab's body, wired from the pure helpers in runDetail.js. Summary - * is the default and carries the run's identity, key/value rows and diagnostic; - * the Graph tab mounts the shared workflow graph in run mode; Input/Output are - * one collapsed section per recorded field; the Timeline is one compact row per - * visit that opens the stage pane. Every server string is set with textContent, - * never innerHTML. - */ -function renderRunDetail() { - const d = state.runDetail; - const pane = h("div", { class: "detail run-detail" }); - if (!d) { - pane.append(h("div", { class: "muted pad", text: "Select a run." })); - return pane; - } - // A run parked on a person surfaces its decision above the tabs, exactly where - // the Android run detail does, so opening the run is enough — no tab hunt. - const decision = pendingDecision(d); - if (decision) pane.append(renderDecisionCard(decision)); - const actions = renderRunActions(d); - if (actions) pane.append(actions); - pane.append( - h( - "div", - { class: "detail-tabs" }, - ...RENDERED_RUN_TABS.map((tab) => - h("button", { - class: `detail-tab${state.runTab === tab.key ? " active" : ""}`, - text: tab.label, - onclick: () => { - state.runTab = tab.key; - renderContent(); - }, - }), - ), - ), - ); - if (state.runTab === "graph") { - pane.append(renderRunGraphTab(d)); - } else if (state.runTab === "input") { - pane.append(renderRunFieldTab(d.input, "input", EMPTY_INPUT_MESSAGE)); - } else if (state.runTab === "output") { - pane.append(renderRunFieldTab(d.output, "output", EMPTY_OUTPUT_MESSAGE)); - } else if (state.runTab === "steps") { - pane.append(renderRunTimelineTab(d)); - } else { - pane.append(renderRunSummaryTab(d)); - } - if (state.runStagePane) pane.append(renderStagePane(d)); - if (state.decisionOpen && state.runDecision) pane.append(renderDecisionSheet(state.runDecision)); - const confirm = renderConfirmDialog(d); - if (confirm) pane.append(confirm); - if (state.actionError) pane.append(renderActionFailedDialog()); - return pane; -} - -/** - * The Graph tab (R5): the run's own guidance note plus the shared workflow graph - * mounted in run mode, or the app's exact missing-graph sentence when the server - * sent no stages. The active stage pulses with its elapsed time while the run - * executes; clicking a stage opens the existing visit pane at that stage's most - * recent visit. The mount handle is tracked in `state.runGraph` so a re-render - * (or a tab/run change) always unmounts the previous wheel/pointer/resize - * listeners and the elapsed timer. - */ -function renderRunGraphTab(d) { - const wrap = h("div", { class: "run-tab-body" }); - const stages = d.graph?.stages ?? []; - if (!stages.length) { - wrap.append(h("div", { class: "run-empty muted", text: RUN_GRAPH_MISSING })); - return wrap; - } - wrap.append(h("p", { class: "graph-note muted", text: RUN_GRAPH_NOTE })); - const host = h("div", { class: "graph-host" }); - wrap.append(host); - state.runGraph = mountGraph(host, d.graph, { - runState: runGraphState(d), - onStageTap: (key) => openStagePane(key, latestVisitIndex(d, key)), - }); - return wrap; -} - -/** - * The visit index the graph opens for a stage: its most recent recorded visit - * (`visits.size - 1`, never negative), exactly as RunGraphTab computes it. - */ -function latestVisitIndex(d, key) { - const visits = runTimeline(d.steps ?? []).visitsByStage.get(key) ?? []; - return Math.max(0, visits.length - 1); -} - -/** The Summary tab: identity, chip row, key/value rows, diagnostic and gallery. */ -function renderRunSummaryTab(d) { - const wrap = h("div", { class: "run-tab-body" }); - wrap.append(renderRunTitleRow(d)); - const status = runStateOf(d.status); - const chips = h("div", { class: "run-chip-row" }); - chips.append(h("span", { class: `chip chip-${status}`, text: d.status || status })); - if (String(d.outcome ?? "").trim()) chips.append(h("span", { class: "muted", text: `outcome ${d.outcome}` })); - if (d.executing) chips.append(h("span", { class: "muted", text: "executing" })); - chips.append(renderLiveBadge(liveBadgeState(state.runStream))); - wrap.append(chips); - wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) })); - - const rows = h("div", { class: "kv" }); - for (const row of summaryRows(d, detailNow)) { - if (row.kind === "wait") rows.append(h("div", { class: "run-wait", text: row.value })); - else if (row.kind === "duration") rows.append(renderDurationRow(d, row)); - else if (row.kind === "block") rows.append(renderCodeBlock(row.key, row.value)); - else rows.append(renderKvRow(row)); - } - wrap.append(rows); - - // The run-level artifacts gallery (parity R8), collapsed by default like the - // Android summary. Its header alone says what was captured until expanded. - wrap.append( - renderCollapsible("summary-artifacts", artifactsHeader(d.steps ?? [], isExecuting(d)), () => - renderArtifactGallery(d.steps ?? []), - ), - ); - - // The run-level Changes (parity R4), collapsed by default like the Android - // summary: the observed workspace diff. Its header alone states the file count - // and aggregate stat until expanded, and every file row opens the diff viewer. - const changes = runChanges(d.steps ?? []); - wrap.append( - renderCollapsible("summary-changes", runChangesHeader(changes), () => renderChangesBody(changes)), - ); - return wrap; -} - -/** The Duration row, tagged so the detail clock can update it in place. */ -function renderDurationRow(d, row) { - return h( - "div", - { class: "kv-row" }, - h("span", { class: "kv-key", text: row.key }), - h("span", { class: "kv-val run-duration", "data-run-id": String(d.id), text: row.value }), - ); -} - -/** One key/value row from a summary row model. */ -function renderKvRow(row) { - return h( - "div", - { class: "kv-row" }, - h("span", { class: "kv-key", text: row.key }), - h("span", { class: `kv-val${row.monospace ? " monospace" : ""}`, text: row.value }), - ); -} - -/** A themed monospace block with a label header. */ -function renderCodeBlock(label, text) { - return h( - "div", - { class: "codeblock" }, - h("div", { class: "codeblock-label", text: label }), - h("pre", { class: "codeblock-body", text }), - ); -} - -/** One stage-pane field as either the code card (blocks) or a key/value row. */ -function renderStageField(field) { - if (field.block) return renderCodeBlock(field.label, field.value); - return h( - "div", - { class: "kv-row" }, - h("span", { class: "kv-key", text: field.label }), - h("span", { class: `kv-val${field.mono ? " monospace" : ""}`, text: field.value }), - ); -} - -/** One collapsible input/output field section (expanded body is a code block). */ -function renderRunFieldTab(map, keyPrefix, emptyMessage) { - const wrap = h("div", { class: "run-tab-body" }); - const sections = fieldSections(map, keyPrefix); - if (!sections.length) { - wrap.append(h("div", { class: "run-empty muted", text: emptyMessage })); - return wrap; - } - for (const section of sections) { - const key = `${keyPrefix}-${section.key}`; - wrap.append( - renderCollapsible(key, section.title, () => - h("pre", { class: "field-block" }, h("code", { text: section.value })), - ), - ); - } - return wrap; -} - -/** - * One collapsible section of the run detail's field/summary body. Expanded state - * is keyed in `state.runSections`, so the operator's choices survive a re-render. - */ -function renderCollapsible(key, title, bodyFn) { - const expanded = state.runSections.has(key); - const wrap = h("div", { class: "collapsible" }); - wrap.append( - h( - "button", - { - class: "section-toggle", - type: "button", - "aria-expanded": expanded ? "true" : "false", - onclick: () => { - state.runSections = new Set(state.runSections); - if (state.runSections.has(key)) state.runSections.delete(key); - else state.runSections.add(key); - renderContent(); - }, - }, - h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), - h("span", { class: "section-title", text: title }), - ), - ); - if (expanded) wrap.append(h("div", { class: "section-body" }, bodyFn())); - return wrap; -} - -// --- Changes (parity R4) --------------------------------------------------- - -/** - * The Changes section body: the file-list summary line, the honest capture note - * (when the capture was not complete) and then either the no-change detail or - * one clickable row per changed file in first-seen order. Every server string is - * set as text, never as markup. - */ -function renderChangesBody(changes) { - const body = h("div", { class: "changes" }); - body.append(h("div", { class: "changes-summary", text: changesListSummary(changes) })); - const note = runChangesNote(changes); - if (note.trim() !== "") body.append(h("div", { class: "changes-note muted", text: note })); - if (changes.files.length === 0) { - body.append(h("div", { class: "changes-empty muted", text: noChangeDetail(changes) })); - return body; - } - const list = h("div", { class: "changes-list" }); - changes.files.forEach((entry, index) => list.append(renderChangeRow(entry, index, changes.files))); - body.append(list); - return body; -} - -/** The tone class for a file's kind: added green, deleted red, else neutral. */ -function changeKindTone(kind) { - if (kind === ChangeKind.Added) return "ok"; - if (kind === ChangeKind.Deleted) return "bad"; - return "muted"; -} - -/** - * One changed-file row: the kind word in its hue, the path in monospace, the - * `+N -M` stat and the `changed by …` meta line. Clicking (or Enter/Space) opens - * the diff viewer on this file, whose position there confirms which row it is. - */ -function renderChangeRow(entry, index, files) { - const open = () => openChangeViewer(files, index); - const row = h("div", { - class: "change-row", - role: "button", - tabindex: "0", - "data-change-index": String(index), - "aria-label": `Open ${entry.path}`, - }); - row.addEventListener("click", open); - row.addEventListener("keydown", (event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - open(); - } - }); - row.append(h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindLabel(entry.kind) })); - const main = h("div", { class: "change-main" }); - main.append(h("div", { class: "change-path monospace", text: entry.path })); - main.append(h("div", { class: "change-meta muted", text: changeRowMeta(entry) })); - row.append(main); - const stat = h("div", { class: "change-stat" }); - if (entry.added > 0) stat.append(h("span", { class: "stat-add", text: `+${entry.added}` })); - if (entry.removed > 0) stat.append(h("span", { class: "stat-del", text: `-${entry.removed}` })); - row.append(stat); - return row; -} - -let changeViewerOverlay = null; -let changeViewerKeydown = null; -let changeViewerIndex = null; - -/** Close the diff viewer, returning focus to the row that opened it. */ -function closeChangeViewer() { - if (changeViewerKeydown) { - document.removeEventListener("keydown", changeViewerKeydown); - changeViewerKeydown = null; - } - const index = changeViewerIndex; - changeViewerOverlay?.remove(); - changeViewerOverlay = null; - changeViewerIndex = null; - if (index != null) { - document.querySelector(`.change-row[data-change-index="${index}"]`)?.focus(); - } -} - -/** - * The full-screen diff viewer for one changed file. It pages through the run's - * changed files exactly as the artifact viewer pages through a gallery's media - * (one shared index, previous/next affordances, Escape/the close button/backdrop - * dismissing), and shows both forms the brief requires, switchable from one - * control row: the **Rendered** reading (each hunk's `@@` header, the shared - * diff line language and the old/new gutter numbers) and the **Raw patch** (the - * server's unified patch verbatim in monospace). A file the server could not - * give a patch for (binary, truncated, or a capture that recorded none) shows the - * honest reason in place of a diff rather than a fabricated one. - */ -function openChangeViewer(files, startIndex) { - closeChangeViewer(); - if (!files?.length) return; - let index = Math.min(Math.max(Number(startIndex) || 0, 0), files.length - 1); - let form = "rendered"; - const overlay = h("div", { - class: "change-viewer", - role: "dialog", - "aria-modal": "true", - "aria-label": "Diff viewer", - }); - overlay.addEventListener("click", (event) => { - if (event.target === overlay) closeChangeViewer(); - }); - - const renderViewer = () => { - const entry = files[index]; - changeViewerIndex = index; - const stat = changeStat(entry.added, entry.removed); - const hasPatch = entryHasPatch(entry); - - const titles = h("div", { class: "change-viewer-titles" }); - const titleRow = h("div", { class: "change-viewer-title-row" }); - titleRow.append( - h("span", { class: `change-kind ${changeKindTone(entry.kind)}`, text: changeKindTitle(entry.kind) }), - ); - if (stat !== "") titleRow.append(h("span", { class: "change-viewer-stat monospace", text: stat })); - titles.append(titleRow); - titles.append(h("div", { class: "change-viewer-path monospace", text: entry.path })); - titles.append( - h("div", { - class: "change-viewer-position muted", - text: `${changePositionLabel(index, files.length)} · changed by ${(entry.steps ?? []).join(" → ")}`, - }), - ); - const head = h( - "div", - { class: "change-viewer-head" }, - titles, - h("button", { - class: "change-viewer-copy", - type: "button", - text: "Copy raw patch", - disabled: !hasPatch, - onclick: () => copyText(entry.patch ?? ""), - }), - h("button", { - class: "change-viewer-close", - type: "button", - text: "Close diff", - onclick: closeChangeViewer, - }), - ); - - const controls = h( - "div", - { class: "change-viewer-controls" }, - h("button", { - class: `change-form${form === "rendered" ? " active" : ""}`, - type: "button", - "data-form": "rendered", - text: "Rendered", - disabled: form === "rendered", - onclick: () => { - form = "rendered"; - renderViewer(); - }, - }), - h("button", { - class: `change-form${form === "raw" ? " active" : ""}`, - type: "button", - "data-form": "raw", - text: "Raw patch", - disabled: !hasPatch, - onclick: () => { - form = "raw"; - renderViewer(); - }, - }), - h("div", { class: "change-viewer-spacer" }), - h("button", { - class: "change-page", - type: "button", - "data-page": "prev", - text: "Previous file", - disabled: index === 0, - onclick: () => { - index = Math.max(index - 1, 0); - form = "rendered"; - renderViewer(); - }, - }), - h("button", { - class: "change-page", - type: "button", - "data-page": "next", - text: "Next file", - disabled: index === files.length - 1, - onclick: () => { - index = Math.min(index + 1, files.length - 1); - form = "rendered"; - renderViewer(); - }, - }), - ); - - const body = h("div", { class: "change-viewer-body" }); - if (entry.binary || !hasPatch) { - body.append( - h("div", { - class: "change-honest muted", - text: entry.binary ? BINARY_DIFF_MESSAGE : patchUnavailableReason(entry), - }), - ); - } else if (form === "raw") { - body.append(h("pre", { class: "change-raw monospace", text: entry.patch ?? "" })); - } else { - body.append(renderRenderedDiff(entry)); - } - - overlay.replaceChildren(head, controls, body); - }; - - renderViewer(); - document.body.append(overlay); - changeViewerOverlay = overlay; - changeViewerKeydown = (event) => { - if (event.key === "Escape") closeChangeViewer(); - }; - document.addEventListener("keydown", changeViewerKeydown); -} - -/** The rendered reading: the stat line, an optional truncation note, each hunk. */ -function renderRenderedDiff(entry) { - const wrap = h("div", { class: "change-diff" }); - const parsed = parseUnifiedPatch(entry.patch); - const statLine = h("div", { class: "change-diff-stat" }); - if (parsed.added > 0) statLine.append(h("span", { class: "stat-add", text: `+${parsed.added}` })); - if (parsed.removed > 0) statLine.append(h("span", { class: "stat-del", text: `-${parsed.removed}` })); - if (parsed.added === 0 && parsed.removed === 0) { - statLine.append(h("span", { class: "muted", text: NO_LINE_CHANGES_MESSAGE })); - } - wrap.append(statLine); - if (entry.truncated) wrap.append(h("div", { class: "change-diff-note muted", text: TRUNCATED_PATCH_NOTE })); - for (const hunk of parsed.hunks) wrap.append(renderHunk(hunk)); - return wrap; -} - -/** - * One `@@` hunk: its header on a raised surface, then its lines in a - * horizontally scrollable container, each with its old/new gutter numbers (blank - * on the absent side and on a `\ No newline` marker) and the shared - * `{symbol} {text}` coloured by kind. - */ -function renderHunk(hunk) { - const width = gutterWidth(hunk); - const wrap = h("div", { class: "change-hunk" }); - wrap.append(h("div", { class: "change-hunk-head", text: hunk.header })); - const lines = h("div", { class: "change-hunk-lines" }); - for (const line of hunk.lines) { - const gutter = line.noNewlineMarker - ? " ".repeat(width * 2 + 1) - : `${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}`; - lines.append( - h( - "div", - { class: "change-line" }, - h("span", { class: "change-gutter", text: gutter }), - h("span", { class: `change-text ${diffLineClass(line.kind)}`, text: `${diffLineSymbol(line.kind)} ${line.text}` }), - ), - ); - } - wrap.append(lines); - return wrap; -} - -/** Copy arbitrary text (the raw patch) to the clipboard, best effort. */ -async function copyText(text) { - if (!text || !canCopyLink()) return; - try { - await navigator.clipboard.writeText(text); - } catch { - // Clipboard permission may be denied; the patch is still readable. - } -} - -/** The Timeline tab: one compact row per visit, in step order. */ -function renderRunTimelineTab(d) { - const wrap = h("div", { class: "run-tab-body" }); - const timeline = runTimeline(d.steps ?? []); - if (!timeline.entries.length) { - wrap.append(h("div", { class: "run-empty muted", text: EMPTY_TIMELINE_MESSAGE })); - return wrap; - } - const list = h("div", { class: "timeline" }); - for (const entry of timeline.entries) list.append(renderTimelineRow(entry)); - wrap.append(list); - return wrap; -} - -/** - * One timeline row: a stage-outcome glyph, the `{stage} · visit {n}` line with - * the outcome chip, a paperclip when the visit recorded artifacts, the duration, - * and the one-line description. Clicking (or Enter/Space) opens the stage pane. - */ -function renderTimelineRow(entry) { - const state_ = runStateOf(entry.outcomeLabel); - const chipLabel = entry.outcomeLabel || state_.label; - const tone = outcomeClass(entry.step.outcome, entry.step.status); - const open = () => openStagePane(entry.stageKey, entry.visitIndex); - const row = h("div", { - class: "timeline-row", - role: "button", - tabindex: "0", - "data-stage-key": entry.stageKey, - "data-visit-index": String(entry.visitIndex), - }); - row.addEventListener("click", open); - row.addEventListener("keydown", (event) => { - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - open(); - } - }); - row.append(h("span", { class: `timeline-glyph ${tone}`, text: stateGlyph(state_) })); - const head = h("div", { class: "timeline-head" }); - head.append(h("span", { class: "timeline-title", text: `${entry.stageKey} · visit ${entry.visit}` })); - head.append(h("span", { class: `outcome-chip ${tone}`, text: chipLabel })); - if (entry.hasArtifacts) { - head.append( - h("span", { class: "timeline-paperclip", title: "Recorded artifacts", "aria-label": "has recorded artifacts", text: "\u{1F4CE}" }), - ); - } - if (entry.duration) head.append(h("span", { class: "timeline-duration muted", text: entry.duration })); - const body = h("div", { class: "timeline-main" }, head); - if (entry.description) body.append(h("span", { class: "timeline-desc muted", text: entry.description })); - row.append(body); - return row; -} - -/** A CSS class naming a stage-outcome colour (status palette, else flow). */ -function outcomeClass(outcome, status) { - const [kind, value] = outcomeColorToken(outcome, status).split(" "); - return `outcome-${kind}-${value}`; -} - -// --- Stage pane ------------------------------------------------------------ - -/** - * The stage pane: a closable dialog for one visit, opened from a timeline row. - * It leads with the verdict block (when the server recorded one), then the - * always-visible headline rows, then the visit's collapsible sections in the - * Android order (Artifacts, Session, Output, Input, This run, Stage definition). - * Escape, the Back button and a backdrop click close it. - */ -function renderStagePane(d) { - const stageKey = state.runStagePane.stageKey; - const timeline = runTimeline(d.steps ?? []); - const runSteps = timeline.visitsByStage.get(stageKey) ?? []; - const visitIndex = clampVisitIndex(state.runStagePane.visitIndex, runSteps.length); - const step = runSteps[visitIndex] ?? null; - const graph = d.graph ?? { stages: [] }; - const specs = stageSectionSpecs(stageKey, graph, runSteps, visitIndex, true); - const fields = step ? runStepFields(step) : []; - const headline = headlineFields(fields); - - const overlay = h("div", { - class: "stage-pane", - role: "dialog", - "aria-modal": "true", - "aria-label": nodeLabel(stageKey), - }); - overlay.addEventListener("click", (event) => { - if (event.target === overlay) closeStagePane(); - }); - const bar = h( - "div", - { class: "stage-pane-bar" }, - h("button", { - class: "stage-pane-back", - type: "button", - "aria-label": "Back", - text: "\u2190 Back", - onclick: closeStagePane, - }), - h( - "div", - { class: "stage-pane-titles" }, - h("span", { class: "stage-pane-title", text: nodeLabel(stageKey) }), - h("span", { class: "stage-pane-run muted", text: runLabelFor(d) }), - ), - ); - - const body = h("div", { class: "stage-pane-body" }); - if (step) { - const verdict = renderVerdictBlock(step); - if (verdict) body.append(verdict); - } - for (const field of headline) body.append(renderStageField(field)); - if (headline.length === 0 && specs.length === 0) { - body.append(h("div", { class: "run-empty muted", text: NO_STAGE_DETAILS_MESSAGE })); - } - for (const spec of specs) body.append(renderStageSection(spec, step)); - overlay.append(h("div", { class: "stage-pane-sheet" }, bar, body)); - return overlay; -} - -/** One stage-pane section, using the pane's own expansion state. */ -function renderStageSection(spec, step) { - const expanded = state.runStageSections.has(spec.key); - const wrap = h("div", { class: "collapsible stage-section" }); - wrap.append( - h( - "button", - { - class: "section-toggle", - type: "button", - "aria-expanded": expanded ? "true" : "false", - onclick: () => { - state.runStageSections = new Set(state.runStageSections); - if (state.runStageSections.has(spec.key)) state.runStageSections.delete(spec.key); - else state.runStageSections.add(spec.key); - renderContent(); - }, - }, - h("span", { class: "chevron", text: expanded ? "\u25be" : "\u25b8" }), - h("span", { class: "section-title", text: spec.title }), - ), - ); - if (!expanded) return wrap; - const body = h("div", { class: "section-body" }); - if (spec.artifacts && step) body.append(renderVisitArtifacts(step)); - else if (spec.session && step) body.append(renderSessionExport(step)); - else for (const field of spec.fields) body.append(renderStageField(field)); - wrap.append(body); - return wrap; -} - -/** - * The verdict block: heading "Verdict", the option as an outcome-coloured chip, - * the reason as body text with inline artifact links, and the referenced - * artifacts as compact chips. Nothing renders when the server recorded no - * option and no reason. - */ -function renderVerdictBlock(step) { - const verdict = step.verdict; - if (!verdict) return null; - const option = String(verdict.option ?? ""); - const reason = String(verdict.reason ?? ""); - if (option.trim() === "" && reason.trim() === "") return null; - - const wrap = h("div", { class: "verdict" }); - const head = h("div", { class: "verdict-head" }, h("span", { class: "verdict-title", text: "Verdict" })); - if (option.trim() !== "") { - head.append(h("span", { class: `outcome-chip ${outcomeClass(step.outcome, step.status)}`, text: option })); - } - wrap.append(head); - - const references = referencedVerdictArtifacts(verdict, presentedArtifacts(step)); - if (reason.trim() !== "") { - const body = h("p", { class: "verdict-reason" }); - for (const segment of verdictReasonSegments(reason, references)) { - if (!segment.artifact) body.append(document.createTextNode(segment.text)); - else body.append(renderVerdictLink(segment.text, segment.artifact, step)); - } - wrap.append(body); - } - if (references.length) { - const refs = h("div", { class: "verdict-refs" }); - for (const artifact of references) refs.append(renderVerdictRef(artifact, step)); - wrap.append(refs); - } - return wrap; -} - -/** One inline artifact reference in a verdict reason (media opens the viewer). */ -function renderVerdictLink(text, artifact, step) { - const resolved = resolvedArtifactUrl(artifact, state.url); - if (!resolved) return h("span", { class: "verdict-link disabled", text }); - const link = h("a", { class: "verdict-link", href: resolved, target: "_blank", rel: "noreferrer", text }); - link.addEventListener("click", (event) => { - event.preventDefault(); - openArtifactFromVerdict(artifact, step, resolved); - }); - return link; -} - -/** One compact chip naming a referenced artifact. */ -function renderVerdictRef(artifact, step) { - const resolved = resolvedArtifactUrl(artifact, state.url); - const chip = h("button", { - class: "verdict-ref", - type: "button", - text: artifact.name || "(unnamed artifact)", - }); - chip.addEventListener("click", () => openArtifactFromVerdict(artifact, step, resolved)); - return chip; -} - -/** Open a referenced artifact: media in the viewer, everything else externally. */ -function openArtifactFromVerdict(artifact, step, resolved) { - if (!resolved) return; - const group = { stageKey: step.stage, visit: displayVisit(step, 0), artifacts: presentedArtifacts(step) }; - const viewable = pagedArtifacts([group]); - const viewerIndexOf = viewerIndexByUrl([group]); - const at = viewerIndexOf.get(artifact.url); - const kind = artifactKind(artifact.content_type, artifact.name); - const media = kind === ArtifactKind.Image || kind === ArtifactKind.Video; - if (media && at != null) openArtifactViewer(viewable, at); - else window.open(resolved, "_blank", "noopener,noreferrer"); -} - -/** Open the stage pane for one visit of a stage and move focus into it. */ -function openStagePane(stageKey, visitIndex, { updateRoute = true } = {}) { - state.runStagePane = { stageKey, visitIndex }; - state.runStageSections = new Set(); - if (updateRoute && state.selectedRunId) { - pushRoute({ - kind: "runStage", - id: state.selectedRunId, - stageKey, - visit: Number.isSafeInteger(visitIndex) && visitIndex >= 0 ? visitIndex : null, - }); - } - renderContent(); - document.querySelector(".stage-pane-back")?.focus(); -} - -/** Close the stage pane, returning focus to the timeline row that opened it. */ -function closeStagePane({ updateRoute = true } = {}) { - const closing = state.runStagePane; - if (!closing) return; - state.runStagePane = null; - state.runStageSections = new Set(); - if (updateRoute && state.selectedRunId) { - pushRoute({ kind: "run", id: state.selectedRunId }); - } - 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 persisted per-chat drafts, or an empty map when unreadable. */ -function readChatDraftStore() { - try { - const parsed = JSON.parse(localStorage.getItem(CHAT_DRAFT_STORAGE_KEY) ?? "{}"); - return parsed && typeof parsed === "object" ? parsed : {}; - } catch { - return {}; - } -} - -/** - * Mirror one conversation's draft into localStorage. A blank draft clears its - * entry so the store cannot grow without bound; the in-memory `thread.draft` - * stays the source of truth, this is only the persistence beside it. - */ -function saveChatDraft(sessionId, text) { - if (!sessionId) return; - try { - const store = readChatDraftStore(); - if (String(text ?? "") === "") delete store[sessionId]; - else store[sessionId] = String(text); - localStorage.setItem(CHAT_DRAFT_STORAGE_KEY, JSON.stringify(store)); - } catch { - // storage may be full or disabled; the in-memory draft still holds - } -} - -/** The persisted draft for one conversation, or "" when there is none. */ -function readChatDraft(sessionId) { - const value = readChatDraftStore()[sessionId]; - return typeof value === "string" ? value : ""; -} - -/** The persisted local chat overrides; unreadable storage means no overrides. */ -function readChatOverridesStore() { - try { - return decodeChatOverrides(localStorage.getItem(CHAT_OVERRIDES_STORAGE_KEY)); - } catch { - return emptyChatOverrides(); - } -} - -/** Persist the current local overrides; storage failure leaves memory authoritative. */ -function saveChatOverrides() { - try { - localStorage.setItem(CHAT_OVERRIDES_STORAGE_KEY, encodeChatOverrides(state.chatOverrides)); - } catch { - // storage may be full or disabled; the in-memory overrides still hold - } -} - -/** The persisted seen state; unreadable storage means nothing seen. */ -function readChatSeenStore() { - try { - return decodeChatSeen(localStorage.getItem(CHAT_SEEN_STORAGE_KEY)); - } catch { - return emptyChatSeen(); - } -} - -/** - * Persist the seen state only when it actually changed. Every frame and refresh - * would otherwise rewrite localStorage for no reason. - */ -function saveChatSeen(next) { - if (next === state.chatSeen) return; - state.chatSeen = next; - try { - localStorage.setItem(CHAT_SEEN_STORAGE_KEY, encodeChatSeen(state.chatSeen)); - } catch { - // storage may be full or disabled; the in-memory state 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 { - const listed = await repo.chatSessions(); - // Keep this page's own verification chats, which the server intentionally - // never returns, at the head of the in-memory list (memory-only; see - // chatEphemeralIds). Everything else is the server's list, in its order. - const held = state.chatSessions.filter( - (session) => - state.chatEphemeralIds.has(session.id) && !listed.some((entry) => entry.id === session.id), - ); - state.chatSessions = [...held, ...listed]; - state.chatLoaded = true; - // Fold this device's seen state in: the active chat has been read, and every - // session seen for the first time gets a baseline so pre-existing chats are - // not all reported as new. - saveChatSeen(seedChatSeen(state.chatSeen, state.chatSessions, state.chatActiveId)); - } catch (error) { - state.chatError = describeError(error); - } - state.chatLoading = false; - renderContent(); -} - -// --------------------------------------------------------------------------- -// The create flow (C2, ChatCreatePane.kt) -// --------------------------------------------------------------------------- - -/** - * Open the create pane with a fresh operation id. The id is minted once per - * intent, so a retry after a refusal reuses it and the server can dedupe the - * create rather than starting a second session. - */ -function startNewChat() { - state.chatCreate = newChatCreateState(newChatOperationId()); - state.chatDirectoriesError = ""; - renderContent(); - loadChatDirectories(); -} - -/** - * Fetch `chat_directories` for the open picker. A failure keeps the reason for the - * pane's error state; blank entries are dropped here as well as in the pure model - * so a malformed reply can never produce an empty row. An already-loaded list is - * reused unless [force] (the error state's Retry) asks again. - */ -async function loadChatDirectories(force = false) { - if (!state.chatCreate || state.chatDirectoriesLoading) return; - if (state.chatDirectoriesLoaded && !force) return; - state.chatDirectoriesLoading = true; - state.chatDirectoriesError = ""; - renderContent(); - try { - const directories = await repo.chatDirectories(); - state.chatDirectories = (directories ?? []).filter((entry) => String(entry ?? "").trim() !== ""); - state.chatDirectoriesLoaded = true; - } catch (error) { - state.chatDirectoriesError = describeError(error); - } - state.chatDirectoriesLoading = false; - renderContent(); -} - -/** Select one directory row (the value is what chat_create will send). */ -function selectChatDirectory(value) { - if (!state.chatCreate) return; - state.chatCreate = selectChatDirectoryModel(state.chatCreate, value); - renderContent(); -} - -/** Leave the create flow without creating anything. */ -function cancelNewChat() { - state.chatCreate = null; - renderContent(); -} - -/** - * Create the chat in the chosen directory. Guarded against a double submit: the - * guard reads the held state, so a second click while the request is in flight - * sends nothing. On success the pane closes, the created session goes to the head - * of the list, becomes the open conversation and loads its (empty) history; on - * failure the server's own reason stays in the pane, which does not close. - */ -async function createNewChat() { - const create = state.chatCreate; - if (!create || create.creating) return; - state.chatCreate = { ...create, creating: true, error: "" }; - renderContent(); - try { - // Not ephemeral: this is the operator's own create path (the UI smoke uses the - // same path for its one real session and closes it afterwards). - const created = await repo.chatCreate("New chat", create.directory, create.operationId); - state.chatCreate = null; - state.chatSessions = chatCreateSucceeded(state.chatSessions, created); - await openChatSession(created.id); - await loadChatSessions(); - } catch (error) { - if (!state.chatCreate) return; - state.chatCreate = chatCreateFailed(state.chatCreate, describeError(error)); - 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.chatMenu = null; - state.chatPlaced = null; - state.chatFollowing = true; - state.chatReasoning = new Set(); - state.chatToolPanels = new Set(); - state.chatToolRows = new Set(); - // Opening reads the conversation: advance the watermark to its current recency - // and clear the explicit unseen mark (a row that is absent has no recency). - const session = state.chatSessions.find((candidate) => candidate.id === id) ?? null; - saveChatSeen(readChatSeen(state.chatSeen, id, session?.updated_at ?? 0)); - const existing = state.chatThreads.get(id); - state.chatThreads.set(id, { - ...newChatThread(id), - ...(existing ?? {}), - // The composer's own per-chat state (C8/C9) survives a switch; the draft is - // seeded from localStorage on the first open (the per-device analogue). The - // live-stream fields (C5) come from `newChatThread`. - draft: existing ? existing.draft ?? "" : readChatDraft(id), - attachments: existing?.attachments ?? [], - notices: existing?.notices ?? [], - 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); - // Load the session's background shells (C11) so the bar appears on open, not - // only after the next pushed shell frame. - loadChatShells(id); - await loadChatHistory(id); -} - -/** Replace one conversation's fields, keeping every other field intact. */ -function setThread(sessionId, patch) { - const current = state.chatThreads.get(sessionId); - if (!current) return; - state.chatThreads.set(sessionId, { ...current, ...patch }); -} - -/** - * 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, and drop its observed shells. 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; a shell's exit may - * have been swallowed by the same gap, so the retained shells are forgotten and - * re-learned from `chat_shells` on reconnect (mirrors ChatStore.streamResumed). - */ -function settleChatThreads() { - for (const [id, thread] of state.chatThreads) { - const hasShells = (thread?.shells ?? []).length > 0; - if (thread?.running || thread?.queued || hasShells) { - state.chatThreads.set(id, resumedThread(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; - markBackgroundChatUnseen(sessionId); - const thread = state.chatThreads.get(sessionId); - state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now())); - renderContent(); -} - -/** - * A frame for a conversation that is not on screen marks it explicitly unseen, - * so its live activity is visible in the list even though a pushed stream carries - * no wall-clock recency to compare. The active chat is read as it arrives and is - * never marked. - */ -function markBackgroundChatUnseen(sessionId) { - if (!sessionId || sessionId === state.chatActiveId) return; - saveChatSeen(markChatUnseen(state.chatSeen, sessionId)); -} - -/** - * Fold one pushed `chat_permission` frame into its conversation (C10). Only a - * conversation this client has open is folded — the server only pushes a - * permission frame for sessions this connection is subscribed to, but the guard - * keeps a frame for a session nobody opened from creating a thread. The card is - * derived from the stored frame plus the local answer, so a resolved re-push - * always clears the controls. - */ -function onChatPermission(frame) { - const sessionId = String(frame?.session_id ?? "").trim(); - if (!sessionId || !state.chatThreads.has(sessionId)) return; - const thread = state.chatThreads.get(sessionId); - const next = applyChatPermission(thread, frame); - // A different request replaces the card, so the previous refusal's reason (and - // the error line it owns) no longer describes what is on screen. - const replaced = - String(thread?.permission?.request_id ?? "") !== String(next.permission?.request_id ?? ""); - if (replaced && thread?.permissionError) { - next.error = thread.error === thread.permissionError ? "" : next.error; - next.permissionError = ""; - } - state.chatThreads.set(sessionId, next); - if (sessionId === state.chatActiveId) renderContent(); -} - -/** - * Answer the pending permission request (C10): settle the matching card - * optimistically so the buttons are never left offering a decision already made, - * then send `chat_reply`. A refused reply reopens the same request (the local - * answer is cleared) and surfaces the server's reason through the thread's own - * error line, so an unaccepted decision is never shown as accepted. A refusal - * that arrives after a different request replaced the card is ignored. - */ -async function answerPermission(sessionId, requestId, decision) { - const thread = state.chatThreads.get(sessionId); - const permission = thread?.permission; - if (!thread || String(permission?.request_id ?? "") !== requestId) return; - setThread(sessionId, { permissionAnswer: decision }); - renderContent(); - try { - await repo.chatReply(sessionId, requestId, decision); - // A retried answer the server accepted clears the reason a previous refusal - // left on the thread's error line — and only that reason, never an unrelated - // error the conversation is carrying. - const settled = state.chatThreads.get(sessionId); - if (settled?.permissionError && settled.error === settled.permissionError) { - setThread(sessionId, { error: "", permissionError: "" }); - renderContent(); - } - } catch (error) { - const current = state.chatThreads.get(sessionId); - if (!current || String(current.permission?.request_id ?? "") !== requestId) return; - const reason = describeError(error); - setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason }); - 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. - * Fetch a session's currently verified shells (C11) and retain only the exits - * this client itself observed, so an exited task never reappears as running and a - * shell the server no longer lists drops out. Called when the conversation opens - * and on every stream reconnect (a gap may have swallowed an exit). A failure is - * non-fatal: the transcript stays usable and the bar keeps its last known state. - */ -async function loadChatShells(id) { - if (!id || state.connection.kind !== "connected") return; - try { - const running = await repo.chatShells(id); - const thread = state.chatThreads.get(id); - if (!thread) return; - state.chatThreads.set(id, { ...thread, shells: shellsLoaded(thread.shells, running) }); - renderContent(); - } catch { - // The shell list is a background convenience; leave the thread untouched. - } -} - -/** - * Toggle a running task's detail pane (C11). Selecting a shell fetches its - * bounded output page; selecting the selected one again closes it. Mirrors - * ChatStore.selectShell: an id that is not a known shell is ignored. - */ -function selectChatShell(shellId) { - const sessionId = state.chatActiveId; - const thread = sessionId ? state.chatThreads.get(sessionId) : null; - if (!thread) return; - const closing = thread.selectedShellId === shellId; - if (!closing && !(thread.shells ?? []).some((shell) => shell.id === shellId)) return; - const next = closing ? null : shellId; - state.chatThreads.set(sessionId, { ...thread, selectedShellId: next, shellOutput: null }); - renderContent(); - if (next) refreshChatShellOutput(next); -} - -/** - * Reread a selected task's bounded output page (C11) from the page's start. The - * cursor is always 0 and the limit is the server's 64 KiB bound, so the client - * never grows output unbounded and a Refresh never appends. A reply for a shell - * that is no longer selected is ignored, exactly like ChatStore.shellOutput*. - */ -async function refreshChatShellOutput(shellId) { - const sessionId = state.chatActiveId; - if (!sessionId || !shellId) return; - shellOutputLoading(sessionId, shellId); - renderContent(); - try { - const page = await repo.chatShellOutput(sessionId, shellId, { cursor: 0, limit: SHELL_OUTPUT_LIMIT }); - shellOutputLoaded(sessionId, shellId, page); - } catch (error) { - shellOutputFailed(sessionId, shellId, describeError(error)); - } - renderContent(); -} - -/** Mark a selected task's output pane loading (ignored for a stale selection). */ -function shellOutputLoading(sessionId, shellId) { - const thread = state.chatThreads.get(sessionId); - if (!thread || thread.selectedShellId !== shellId) return; - state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: true, error: "", page: null } }); -} - -/** - * Apply a loaded output page, merging a shell the page reports back into the - * retained list (keeping the command already learned when the page omits it). - */ -function shellOutputLoaded(sessionId, shellId, page) { - const thread = state.chatThreads.get(sessionId); - if (!thread || thread.selectedShellId !== shellId) return; - const reported = page?.shell; - const shells = reported && String(reported.id ?? "").trim() !== "" - ? mergeShellFrame(thread.shells, reported) - : thread.shells ?? []; - state.chatThreads.set(sessionId, { ...thread, shells, shellOutput: { loading: false, error: "", page } }); -} - -/** Report a failed output read against the still-selected task (Retry is offered). */ -function shellOutputFailed(sessionId, shellId, message) { - const thread = state.chatThreads.get(sessionId); - if (!thread || thread.selectedShellId !== shellId) return; - state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: false, error: message, page: null } }); -} - -/** - * The reconnect repair (C5/C11): re-attach the open chat's stream, replace its - * conversation with the newest history page wholesale and re-learn its shells. - * Everything the gap could have missed is repaired; a turn that was in flight is - * settled and the retained shells are dropped before the fresh snapshot arrives. - * 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, resumedThread(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. - } - await loadChatShells(id); - 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); - // The merged page replaces only the history fields; spreading it over the - // held thread keeps the composer's draft, attachments and flags intact (a - // draft typed while the page was loading is not lost). - setThread(id, mergeHistoryPage(previous, page, { older: false })); - } catch (error) { - setThread(id, { 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; - setThread(id, mergeHistoryPage(current, page, { older: true })); - } catch (error) { - setThread(id, { loading: false, error: describeError(error) }); - } - renderContent(); -} - -/** Open the Close chat? confirm for [session] (the mutation only on confirm). */ -function openChatClose(session) { - state.chatMenu = null; - 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); - } - // Closing also finishes the session for this client: the conversation leaves - // the pane, back to the list (mirrors Android's `finishSession` calling - // `chatStore.close`). A rejection above leaves the conversation exactly as it - // was; `settledThread` has already cleared the running/queued bits. - if (state.chatActiveId === session.id) { - state.chatActiveId = null; - } - } 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; - state.chatMenu = null; - 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, - ); -} - -// --------------------------------------------------------------------------- -// This device's chat changes (C13): local rename, hide + undo, row menu -// --------------------------------------------------------------------------- - -const EPHEMERAL_CHATS_KEY = "pipelines.web.ephemeralChats.v1"; - -/** This tab's verification-chat ids (never listed), or an empty set. */ -function readEphemeralChatIds() { - try { - const raw = sessionStorage.getItem(EPHEMERAL_CHATS_KEY); - const ids = raw ? JSON.parse(raw) : []; - return Array.isArray(ids) ? ids.filter((id) => typeof id === "string" && id.trim() !== "") : []; - } catch { - return []; - } -} - -/** Persist this tab's verification-chat ids for a reload of the same tab. */ -function writeEphemeralChatIds(ids) { - try { - sessionStorage.setItem(EPHEMERAL_CHATS_KEY, JSON.stringify([...ids])); - } catch { - // Storage may be unavailable; the in-memory set still covers this page. - } -} - -/** The server row with this device's local title applied (for the open pane). */ -function effectiveChatSession(session) { - if (!session) return null; - return applyChatOverrides([session], state.chatOverrides)[0] ?? session; -} - -/** Open one row's Chat actions menu, closing any other. */ -function openChatMenu(sessionId) { - state.chatMenu = state.chatMenu === sessionId ? null : sessionId; - renderContent(); - if (state.chatMenu) { - // The panel hangs below its button. Near the bottom of the window that would - // put the items off-screen (a real hit-test failure, not just clipping), so - // flip the panel above the row when it does not fit below. - const row = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"]`); - const panel = row?.querySelector(".chat-menu-panel"); - if (panel && panel.getBoundingClientRect().bottom > window.innerHeight - 8) { - panel.style.top = "auto"; - panel.style.bottom = "calc(100% + 4px)"; - } - // The re-render replaced the focused button; move focus into the panel so a - // keyboard operator can walk the items without hunting for the next Tab stop. - const first = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"] .chat-menu-item`); - first?.focus(); - } -} - -/** Open the Rename chat dialog for [session] (its current effective title). */ -function openChatRename(session) { - state.chatMenu = null; - state.chatRename = session; - renderContent(); - // Same re-render note as the menu: put the cursor in the Name field. - document.getElementById("chatRenameInput")?.focus(); -} - -function dismissChatRename() { - state.chatRename = null; - renderContent(); -} - -/** - * Record a local rename, persist it and reflect it at once: the row shows the - * local title on the next render (and every later refresh), and an open - * conversation's own title follows. Nothing is sent to the server — the - * brokered protocol has no chat rename. - */ -function applyLocalChatRename(sessionId, title) { - const next = renameChatOverride(state.chatOverrides, sessionId, title); - if (next === state.chatOverrides) return false; - state.chatOverrides = next; - saveChatOverrides(); - const local = next.titles[String(sessionId)]; - if (local != null) setThread(sessionId, { title: local }); - return true; -} - -/** - * The dialog's Save: trim, record the override, close the dialog and re-render. - * A blank title is ignored (Save is already disabled while trimmed-blank). - */ -function acceptChatRename(session, title) { - const trimmed = String(title ?? "").trim(); - if (trimmed === "") return; - applyLocalChatRename(session.id, trimmed); - state.chatRename = null; - renderContent(); -} - -/** - * Hide a session on this device only. The server is not asked to delete - * anything: the row disappears from this list, its conversation closes, and the - * one snackbar says exactly that with an Undo. A new hide replaces the previous - * report (one snackbar slot), never queues behind it. - */ -function hideChatLocally(sessionId) { - const id = String(sessionId ?? ""); - if (!id) return; - const next = hideChatOverride(state.chatOverrides, id); - if (next === state.chatOverrides) return; - state.chatOverrides = next; - saveChatOverrides(); - state.chatMenu = null; - state.chatRename = null; - // Hiding closes the conversation, exactly as Android's remove does: the thread - // is dropped, the active id cleared and the subscription forgotten. - state.chatThreads.delete(id); - if (state.chatActiveId === id) { - state.chatActiveId = null; - state.chatPlaced = null; - } - if (state.chatSubscriptions.has(id)) { - state.chatSubscriptions = new Set(state.chatSubscriptions); - state.chatSubscriptions.delete(id); - } - installChatSnackbar(id); - renderContent(); -} - -/** Replace the one in-flight hide report and (re)start its auto-dismiss timer. */ -function installChatSnackbar(sessionId) { - if (state.chatSnackbarTimer != null) clearTimeout(state.chatSnackbarTimer); - state.chatSnackbarSeq += 1; - const id = state.chatSnackbarSeq; - state.chatSnackbar = { id, sessionId }; - state.chatSnackbarTimer = setTimeout(() => { - state.chatSnackbarTimer = null; - if (state.chatSnackbar?.id !== id) return; - state.chatSnackbar = null; - renderContent(); - }, 6000); -} - -/** Undo the last hide: restore its row and clear the report (nothing server-side). */ -function undoHideChat() { - const sessionId = state.chatSnackbar?.sessionId; - if (!sessionId) return; - const next = restoreChatOverride(state.chatOverrides, sessionId); - if (next !== state.chatOverrides) { - state.chatOverrides = next; - saveChatOverrides(); - } - clearChatSnackbar(); - renderContent(); -} - -/** Drop the hide report and its timer (Undo, expiry, or leaving the list). */ -function clearChatSnackbar() { - if (state.chatSnackbarTimer != null) { - clearTimeout(state.chatSnackbarTimer); - state.chatSnackbarTimer = null; - } - state.chatSnackbar = null; -} - -// --------------------------------------------------------------------------- -// The composer and its slash commands (C8 · C9) -// --------------------------------------------------------------------------- - -// The per-conversation attachment and notice ids. An id is unique across the -// page, so a chip or a command line is unambiguously removable after a re-render. -let chatAttachmentSeq = 0; -let chatNoticeSeq = 0; - -/** Revoke an attachment's image object URL, if it created one. */ -function releaseAttachment(attachment) { - if (attachment?.thumbUrl) { - try { - URL.revokeObjectURL(attachment.thumbUrl); - } catch { - // already gone - } - } -} - -/** Revoke every attachment's object URL (used once the message is sent/gone). */ -function releaseAttachments(attachments) { - for (const attachment of attachments ?? []) releaseAttachment(attachment); -} - -/** - * Fold one server push into its session's thread: any frame for the session - * clears the queued notice (the turn it waited behind moved on), and a settled - * step clears the running bit the Stop control reads. The live transcript owns - * the rest of the frame fold; this only keeps the composer honest while C5 is - * still to land. - */ -function onChatFrame(message) { - const frame = message?.chat_event; - if (!frame || !frame.session_id) return; - const sessionId = frame.session_id; - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - const queued = queuedAfterFrame(thread.queued, frame); - const running = runningAfterFrame(thread.running, frame); - if (queued === thread.queued && running === thread.running) return; - setThread(sessionId, { queued, running }); - if (sessionId === state.chatActiveId) renderContent(); -} - -/** Add one local command line to a conversation's transcript. */ -function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - chatNoticeSeq += 1; - const notice = makeChatNotice(`notice-${chatNoticeSeq}`, text, { failed, offer }); - setThread(sessionId, { notices: appendChatNotice(thread.notices, notice) }); -} - -/** Remove one local command line (the operator cancelled or dismissed it). */ -function dismissChatNotice(sessionId, noticeId) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - setThread(sessionId, { notices: dismissChatNoticeModel(thread.notices, noticeId) }); - renderContent(); -} - -/** - * Take an unknown-command offer's draft, removing the notice first so a stale - * tap can neither send the same draft twice nor send anything at all. - */ -function takeChatNoticeOffer(sessionId, noticeId) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return null; - const taken = takeChatNoticeOfferModel(thread.notices, noticeId); - if (taken.offer == null) return null; - setThread(sessionId, { notices: taken.notices }); - return taken.offer; -} - -/** - * The composer's draft field, updated in place on every keystroke: the draft is - * mirrored into localStorage, the textarea grows to fit (1–6 rows), and the - * palette and the send/stop control are refreshed without rebuilding the DOM (so - * the operator keeps focus and caret). - */ -function onComposerInput(event, sessionId, session, controls) { - const value = event.target.value; - setThread(sessionId, { draft: value }); - saveChatDraft(sessionId, value); - growComposerTextarea(event.target); - refreshComposerControls(sessionId, session, controls); -} - -/** - * The composer's key handling. While the offer list is showing, Up/Down move the - * highlight and Enter runs the highlighted command (mirrors ChatComposer's - * preview handler). Enter otherwise submits — which is inert while a turn is - * running unless the palette or a slash draft is present (see composerSubmit); - * Shift+Enter is left to insert a newline. - */ -function onComposerKeydown(event, sessionId, session, controls) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - const suggestions = chatCommandSuggestions(thread.draft); - if (suggestions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) { - event.preventDefault(); - const step = event.key === "ArrowDown" ? 1 : -1; - controls.selected = (controls.selected + step + suggestions.length) % suggestions.length; - refreshComposerControls(sessionId, session, controls); - return; - } - if (event.key === "Enter" && !event.shiftKey) { - event.preventDefault(); - submitChatComposer(sessionId, session, controls); - } -} - -/** - * Grow the composer's textarea between one and six rows to fit its content. The - * element is `box-sizing: border-box` with vertical padding, so the cap and the - * measured height both include the padding and the border: a six-row field is - * six full text lines, not five-and-a-bit, and the first row is not clipped. - */ -function growComposerTextarea(el) { - if (!el) return; - const style = getComputedStyle(el); - const line = parseFloat(style.lineHeight) || 20; - const border = el.offsetHeight - el.clientHeight; - const padding = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.paddingBottom) || 0); - const maxRows = 6; - const max = line * maxRows + padding + border; - el.style.height = "auto"; - const wanted = el.scrollHeight + border; - el.style.height = `${Math.min(wanted, max)}px`; - el.style.overflowY = wanted > max ? "auto" : "hidden"; -} - -/** - * Refresh the composer's derived parts (the offer list, the send/stop control) - * after a keystroke, without rebuilding the textarea. The highlighted row moves - * only through the palette itself, so it is preserved here. - */ -function refreshComposerControls(sessionId, session, controls) { - const thread = state.chatThreads.get(sessionId); - if (!thread || !controls) return; - const suggestions = chatCommandSuggestions(thread.draft); - if (controls.selected >= suggestions.length) controls.selected = 0; - fillCommandPalette(controls.palette, suggestions, controls.selected, (index) => { - const command = suggestions[index]; - if (command) runChatCommand(sessionId, session, `/${command.name}`); - }); - fillComposerPrimary(controls.primary, thread, { - onSend: () => submitChatComposer(sessionId, session, controls), - onStop: () => stopChatTurn(sessionId), - }); -} - -/** Run the composer's submit (Enter): a command runs, else the draft sends. */ -function submitChatComposer(sessionId, session, controls) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - const action = composerSubmit(thread, controls?.selected ?? 0); - if (action.kind === "command") { - runChatCommand(sessionId, session, action.text); - } else if (action.kind === "send") { - sendChatPrompt(sessionId, session); - } -} - -/** - * Run one slash command against a conversation (C9). The draft is always consumed - * here — a slash draft is never handed to the prompt path — so only an explicit - * "Send as message" from an unknown-command offer reaches the agent. Every - * outcome is a local transcript line. - */ -function runChatCommand(sessionId, session, text) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - setThread(sessionId, { draft: "" }); - saveChatDraft(sessionId, ""); - const view = { ...thread, draft: "", directory: session?.directory ?? "", running: thread.running === true }; - const effect = chatCommandEffect(parseChatInput(text), view); - if (effect == null) return; - applyChatCommandEffect(sessionId, session, effect); - renderContent(); -} - -/** - * Perform one command effect. `/new` creates a session in the current directory - * and opens it (the create request is C2's; until C2 lands the browser sends - * `chat_create` directly); `/close` reuses the C3 confirm; `/rename` writes to - * C13's durable device-local store; `/stop` interrupts; `/help` shows the - * command list. - */ -function applyChatCommandEffect(sessionId, session, effect) { - switch (effect.kind) { - case "start-session": - startChatSession(effect.directory); - break; - case "finish-session": - if (session) openChatClose(session); - break; - case "rename-session": - renameChatSessionLocally(sessionId, effect.title); - break; - case "stop-turn": - stopChatTurn(sessionId); - break; - case "show-help": - addChatNotice(sessionId, chatCommandHelp()); - break; - case "report": - addChatNotice(sessionId, effect.text, { failed: true, offer: effect.offer ?? null }); - break; - default: - break; - } -} - -/** `/new`: create a session titled "New chat" in [directory] and open it. */ -async function startChatSession(directory) { - const from = state.chatActiveId; - try { - // An automated check (the UI smoke) can mark its throwaway chat ephemeral, so - // creating one for verification never adds a stray "New chat" to the - // operator's list. Set only by test tooling; a normal page leaves it unset. - const ephemeral = globalThis.__pipelinesEphemeralChat === true; - const created = await repo.chatCreate("New chat", directory, undefined, { ephemeral }); - if (ephemeral) { - state.chatEphemeralIds = new Set(state.chatEphemeralIds).add(created.id); - writeEphemeralChatIds(state.chatEphemeralIds); - } - // The list is the server's; insert the created session so the row is present - // before the conversation opens, then refresh from the server. - state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)]; - state.chatThreads.set(created.id, { - draft: "", - attachments: [], - notices: [], - queued: false, - running: false, - messages: [], - nextCursor: "", - hasMore: false, - loaded: false, - loading: true, - error: "", - }); - const title = String(created.title ?? "").trim() || "New chat"; - addChatNotice(created.id, `Started a new session “${title}” in ${directory}.`); - await openChatSession(created.id); - // An ephemeral (verification) create is intentionally absent from the server's - // list, so a refresh here would replace the just-opened conversation and drop - // its local notice. The row is already spliced above and is kept by - // loadChatSessions via chatEphemeralIds, so a listed create still refreshes. - if (!ephemeral) await loadChatSessions(); - } catch (error) { - if (from) addChatNotice(from, `Couldn't start a new session in ${directory}: ${describeError(error)}`, { failed: true }); - state.actionError = describeError(error); - renderContent(); - } -} - -/** - * `/rename`: rename the session on this device only, through the same durable - * store the row's Rename chat dialog uses (C13). The local title wins over the - * server's on every later refresh; nothing is sent to the server. - */ -function renameChatSessionLocally(sessionId, title) { - const trimmed = String(title ?? "").trim(); - if (trimmed === "") return; - applyLocalChatRename(sessionId, trimmed); - addChatNotice(sessionId, `Renamed this session to “${trimmed}” on this device only; the server's title is unchanged.`); -} - -/** The composer's Stop control: interrupt the session's running turn. */ -async function stopChatTurn(sessionId) { - try { - await repo.chatInterrupt(sessionId); - addChatNotice(sessionId, "Stopping the running turn…"); - } catch (error) { - state.actionError = describeError(error); - } - renderContent(); -} - -/** - * Send the composer's draft with its attachments (mirrors - * `AppViewModel.sendChatPrompt`): the draft is trimmed, the compose state is - * cleared at once, and a rejected prompt restores the draft and the attachments - * with the server's own message. - */ -async function sendChatPrompt(sessionId, session) { - const thread = state.chatThreads.get(sessionId); - if (!thread || !composerCanSend(thread)) return; - const text = String(thread.draft).trim(); - if (text === "") return; - const attachments = thread.attachments ?? []; - releaseAttachments(attachments); - setThread(sessionId, { draft: "", attachments: [] }); - saveChatDraft(sessionId, ""); - renderContent(); - await postChatPrompt(sessionId, text, attachments); -} - -/** - * One prompt, from the composer or an unknown-command offer. Flags the chat - * running, posts it, and takes the attachments back out flagged with the - * server's reason if it is rejected. The live transcript item (C5) owns the - * optimistic bubble; this only drives the composer and its request. - */ -async function postChatPrompt(sessionId, text, attachments) { - const body = String(text).trim(); - if (body === "") return; - setThread(sessionId, { running: true }); - renderContent(); - try { - const queued = await repo.chatPrompt(sessionId, body, attachmentFiles(attachments)); - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - // Prompting a closed session reopens it on the server; clear the local mark - // too so the list agrees without a re-fetch. - applyChatSessionUpdate(sessionId, null, false); - setThread(sessionId, { queued, running: true }); - renderContent(); - } catch (error) { - const message = describeError(error); - const restored = (attachments ?? []).map((attachment) => { - releaseAttachment(attachment); - return { ...attachment, thumbUrl: null, error: message }; - }); - setThread(sessionId, { - running: false, - queued: false, - error: message, - draft: body, - attachments: restored, - }); - saveChatDraft(sessionId, body); - state.actionError = message; - renderContent(); - } -} - -/** Send an unknown-command offer's draft through the ordinary prompt path. */ -function sendChatCommandOffer(sessionId, noticeId) { - const offer = takeChatNoticeOffer(sessionId, noticeId); - if (offer == null) return; - renderContent(); - postChatPrompt(sessionId, offer, []); -} - -/** - * Resolve the files the operator picked into composer attachments. Only the - * metadata is read here (nothing is transmitted until the message is sent): the - * browser has no `content://` reference, so the file's own name is carried as the - * best-effort reference string. A file over the limit is returned with its error - * set rather than dropped. - */ -function onChatFilesPicked(sessionId, session, fileList) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - const picked = []; - for (const file of fileList ?? []) { - chatAttachmentSeq += 1; - const name = String(file?.name ?? ""); - const mime = String(file?.type ?? ""); - const size = Number(file?.size) || 0; - picked.push({ - id: `att-${chatAttachmentSeq}`, - name, - uri: name, - mime, - size, - error: attachmentError(name, size, true), - thumbUrl: mime.startsWith("image/") ? createThumbUrl(file) : null, - file, - }); - } - if (picked.length === 0) return; - setThread(sessionId, { attachments: [...(thread.attachments ?? []), ...picked] }); - renderContent(); -} - -/** An object URL for a local image preview, or null when the browser refuses one. */ -function createThumbUrl(file) { - try { - return URL.createObjectURL(file); - } catch { - return null; - } -} - -/** Remove one attachment from the next message and release its preview URL. */ -function removeChatAttachment(sessionId, attachmentId) { - const thread = state.chatThreads.get(sessionId); - if (!thread) return; - const attachment = (thread.attachments ?? []).find((entry) => entry.id === attachmentId); - releaseAttachment(attachment); - setThread(sessionId, { - attachments: (thread.attachments ?? []).filter((entry) => entry.id !== attachmentId), - }); - renderContent(); -} - -function renderChatList() { - // The open menu must not be clipped by the list's rounded-corner overflow; the - // class is present only while a menu is open, so the normal list stays clipped. - const list = h("div", { class: `list chat-list${state.chatMenu ? " menu-open" : ""}` }); - 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); - }, - }), - // C2: the create path stays one tap away while the list is narrowed, the same - // trailing action the app keeps beside its search control. - h("button", { - class: "ghost chat-new", - type: "button", - text: CHAT_NEW_ACTION, - onclick: startNewChat, - }), - ); - 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 visible = applyChatOverrides(state.chatSessions, state.chatOverrides); - const filtered = filterSessions(visible, 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) { - const empty = chatEmpty(CHAT_EMPTY); - empty.append( - h("button", { - class: "ghost chat-new", - type: "button", - text: CHAT_NEW_ACTION, - onclick: startNewChat, - }), - ); - 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 unseen = - !session.closed && - isChatSessionUnseen(session, { - activeId: state.chatActiveId, - seen: state.chatSeen, - opened: state.chatThreads.has(session.id), - }); - const activity = sessionActivity(thread?.running === true, unseen); - 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; the Chat actions menu 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)), - }), - ); - row.append(renderChatActionsMenu(session)); - return row; -} - -/** - * The create pane (C2): the app's NewChatPane. A back control leaves without - * creating, then the directory error / loading / picker states in the app's own - * order, the model note and the footer naming the value that will be sent. Every - * server string is set with textContent. - */ -function renderChatCreate() { - const create = state.chatCreate; - const pane = h("div", { class: "detail chat-detail chat-create" }); - - const bar = h("div", { class: "chat-bar chat-create-bar" }); - bar.append( - h( - "button", - { - class: "ghost chat-create-back", - type: "button", - "aria-label": CHAT_CREATE_BACK_LABEL, - title: CHAT_CREATE_BACK_LABEL, - onclick: cancelNewChat, - }, - h("span", { class: "chat-create-back-glyph", "aria-hidden": "true", text: "←" }), - ), - h("h2", { class: "chat-bar-title chat-create-title", text: CHAT_CREATE_TITLE }), - ); - pane.append(bar); - - if (state.chatDirectoriesError && !state.chatDirectoriesLoaded) { - const empty = chatEmpty(state.chatDirectoriesError); - empty.classList.add("chat-create-directories-error"); - empty.append( - h("button", { - class: "ghost chat-create-retry", - type: "button", - text: "Retry", - onclick: () => loadChatDirectories(true), - }), - ); - pane.append(empty); - } else if (!state.chatDirectoriesLoaded) { - pane.append(h("div", { class: "chat-create-loading muted", text: CHAT_CREATE_LOADING })); - } else { - pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT })); - - const choices = directoryChoices(state.chatDirectories); - const selected = - choices.find((choice) => choice.createDirectory === create.directory) ?? - defaultDirectoryChoice(choices); - const list = h("div", { - class: "chat-create-choices", - role: "listbox", - "aria-label": CHAT_CREATE_PROMPT, - }); - for (const choice of choices) { - const active = choice.createDirectory === selected?.createDirectory; - const row = h("button", { - class: `row chat-create-choice${active ? " selected" : ""}`, - type: "button", - role: "option", - "aria-selected": active ? "true" : "false", - "data-directory": choice.createDirectory, - onclick: () => selectChatDirectory(choice.createDirectory), - }); - row.append(h("span", { class: "row-title chat-create-choice-label", text: choice.label })); - if (choice.secondary) { - row.append(h("span", { class: "row-meta chat-create-choice-path", text: choice.secondary })); - } - list.append(row); - } - pane.append(list); - - // A refresh that failed after a successful first load keeps the choices and - // says why the list may be stale (the app's own bodySmall error line). - if (state.chatDirectoriesError) { - pane.append(h("div", { class: "chat-create-directories-error", text: state.chatDirectoriesError })); - } - if (create.error) { - pane.append(h("div", { class: "chat-create-error", text: create.error })); - } - pane.append(h("p", { class: "chat-create-model-note muted", text: CHAT_CREATE_MODEL_NOTE })); - - const directory = selected?.createDirectory ?? create.directory; - const footer = h("div", { class: "chat-create-footer" }); - footer.append(h("span", { class: "chat-create-start", text: chatStartInLabel(directory) })); - footer.append( - h("button", { - class: "ghost chat-create-cancel", - type: "button", - text: CHAT_CREATE_CANCEL, - disabled: create.creating, - onclick: cancelNewChat, - }), - ); - const confirm = h("button", { - class: "chat-create-confirm", - type: "button", - "aria-label": CHAT_CREATE_CONFIRM, - disabled: create.creating, - onclick: createNewChat, - }); - if (create.creating) { - confirm.append(h("span", { class: "spinner chat-create-spinner", "aria-hidden": "true" })); - } else { - confirm.append(document.createTextNode(CHAT_CREATE_CONFIRM)); - } - footer.append(confirm); - pane.append(footer); - } - - appendChatDialogs(pane); - return pane; -} - -/** - * One row's Chat actions menu, with Android's items in its order: Rename…, then - * Close chat… (open) or Reopen (closed), then Hide on this device. Closing is the - * shared, server-side finish; hiding only affects this device and says so. - */ -function renderChatActionsMenu(session) { - const wrap = h("div", { class: "chat-row-actions chat-menu-wrap" }); - const expanded = state.chatMenu === session.id; - wrap.append( - h("button", { - class: "ghost chat-menu-button", - type: "button", - text: "⋯", - "aria-label": CHAT_ACTIONS_LABEL, - "aria-haspopup": "menu", - "aria-expanded": expanded ? "true" : "false", - title: CHAT_ACTIONS_LABEL, - onclick: (event) => { - event.stopPropagation(); - openChatMenu(session.id); - }, - }), - ); - if (expanded) { - const menu = h("div", { class: "chat-menu-panel", role: "menu", "aria-label": CHAT_ACTIONS_LABEL }); - menu.addEventListener("click", (event) => event.stopPropagation()); - menu.append( - h("button", { - class: "ghost chat-menu-item chat-menu-rename", - type: "button", - role: "menuitem", - text: CHAT_RENAME_ACTION, - onclick: () => openChatRename(session), - }), - ); - if (session.closed) { - menu.append( - h("button", { - class: "ghost chat-menu-item chat-menu-reopen", - type: "button", - role: "menuitem", - text: REOPEN_ACTION, - disabled: state.chatBusy, - onclick: () => reopenChatSession(session.id), - }), - ); - } else { - menu.append( - h("button", { - class: "ghost chat-menu-item chat-menu-close", - type: "button", - role: "menuitem", - text: CLOSE_CHAT_ACTION, - disabled: state.chatBusy, - onclick: () => openChatClose(session), - }), - ); - } - menu.append( - h("button", { - class: "ghost chat-menu-item chat-menu-hide", - type: "button", - role: "menuitem", - text: CHAT_HIDE_ACTION, - onclick: () => hideChatLocally(session.id), - }), - ); - wrap.append(menu); - } - return wrap; -} - -/** 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 effective = effectiveChatSession(session); - const thread = state.chatThreads.get(state.chatActiveId) ?? null; - const title = effective ? sessionTitle(effective) : state.chatActiveId.slice(0, 18); - // The pending approval card (C10), derived from the stored frame plus the local - // answer. While it is actionable the top bar offers a jump control and the - // running indicator stands down (a turn blocked on a decision is not generating). - const approval = approvalCard(thread?.permission, thread?.permissionAnswer); - const awaiting = approval?.actionable === true; - - 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), - }), - ); - } - // The approval jump control appears only while a request is actionable, and - // brings its card (the transcript's last item) into view — the one scroll path, - // so a pending request is reached the same way new content is. - if (awaiting) bar.append(approvalJumpButton()); - 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); - - // The background-tasks bar (C11) sits above the transcript, outside the - // scroller so the C14 scroll positions are untouched. It is present only while - // a shell is still running and disappears with the last exit. - const backgroundTasks = renderBackgroundTasks(thread); - if (backgroundTasks) pane.append(backgroundTasks); - - const notices = thread?.notices ?? []; - 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 ?? []); - // The running indicator stands down while an approval is pending (C10): a turn - // blocked on a decision is not generating, so neither the spinner nor its clock - // shows. The composer's Stop control stays governed by thread.running. - const running = thread?.running === true && !awaiting; - if (rows.length === 0 && notices.length === 0 && !running && !approval) { - pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY })); - } else { - pane.append( - renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now(), approval }), - ); - } - if (thread?.error && thread?.loaded) { - pane.append(h("div", { class: "chat-transcript-error", text: thread.error })); - } - } - - // The composer sits at the foot of the conversation, always available while a - // chat is open (the transcript may still be loading). - pane.append(renderChatComposer(thread, session, state.chatActiveId)); - - 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.chatRename) pane.append(renderChatRenameDialog(state.chatRename)); - if (state.chatSnackbar) pane.append(renderChatSnackbar()); - if (state.actionError) pane.append(renderActionFailedDialog()); -} - -/** - * The one hide report (C13): the exact Android message and an `Undo` action. It - * is a fixed overlay (so a re-render or the transcript's height never moves it) - * and it is replaced, never queued, by a newer hide. - */ -function renderChatSnackbar() { - const bar = h("div", { class: "chat-snackbar", role: "status" }); - bar.append(h("span", { class: "chat-snackbar-message", text: CHAT_REMOVED_MESSAGE })); - bar.append( - h("button", { - class: "ghost chat-snackbar-undo", - type: "button", - text: CHAT_UNDO_ACTION, - onclick: () => undoHideChat(), - }), - ); - return bar; -} - -/** - * The Rename chat dialog (C13): a locally-kept name, with the helper that says so - * plainly. Save is disabled while the trimmed value is blank; typing toggles that - * state directly, so the transcript's scroll is never disturbed by a re-render. - * Nothing is sent to the server — there is no chat rename on the wire. - */ -function renderChatRenameDialog(session) { - const effective = effectiveChatSession(session) ?? session; - const overlay = h("div", { - class: "confirm-dialog confirm-chat-rename", - role: "dialog", - "aria-modal": "true", - "aria-label": CHAT_RENAME_TITLE, - }); - overlay.addEventListener("click", (event) => { - if (event.target === overlay) dismissChatRename(); - }); - const panel = h("div", { class: "confirm-panel" }); - panel.append(h("h2", { class: "confirm-title", text: CHAT_RENAME_TITLE })); - const field = h("div", { class: "chat-rename-field" }); - field.append(h("label", { class: "chat-rename-label", for: "chatRenameInput", text: CHAT_RENAME_FIELD_LABEL })); - const input = h("input", { - id: "chatRenameInput", - class: "rename-input chat-rename-input", - type: "text", - value: sessionTitle(effective), - spellcheck: "false", - autocomplete: "off", - }); - field.append(input); - panel.append(field); - panel.append(h("p", { class: "chat-rename-helper", text: CHAT_RENAME_HELPER })); - const actions = h("div", { class: "confirm-actions" }); - actions.append( - h("button", { - class: "ghost confirm-dismiss chat-rename-cancel", - type: "button", - text: CHAT_RENAME_DISMISS, - onclick: dismissChatRename, - }), - ); - const save = h("button", { - class: "confirm-accept chat-rename-save", - type: "button", - text: CHAT_RENAME_SAVE, - disabled: input.value.trim() === "", - onclick: () => acceptChatRename(session, input.value), - }); - // Toggle Save in place on input: no renderContent, so the transcript's scroll - // position (C14) is untouched while the operator types. - input.addEventListener("input", () => { - save.disabled = input.value.trim() === ""; - }); - actions.append(save); - panel.append(actions); - overlay.append(panel); - return overlay; -} - -/** - * The background-tasks bar (C11): the running shells this conversation still - * owns. It returns null (renders nothing) unless at least one shell is running, - * so it disappears the moment the last task exits. Heading `Background tasks` + - * `{n} running`; the list shows at most BACKGROUND_TASK_VISIBLE_ROWS rows and - * scrolls beyond; a selected row reveals its bounded, read-only output pane. - * Every server string is set with textContent (never innerHTML). - */ -function renderBackgroundTasks(thread) { - const running = runningBackgroundShells(thread?.shells ?? []); - if (running.length === 0) return null; - const wrap = h("section", { class: "chat-bg-tasks", id: "chatBackgroundTasks" }); - const head = h("div", { class: "chat-bg-tasks-head" }); - head.append(h("span", { class: "chat-bg-tasks-title", text: BACKGROUND_TASKS_TITLE })); - head.append( - h("span", { class: "chat-bg-tasks-count muted", text: backgroundTasksRunningLabel(running.length) }), - ); - wrap.append(head); - const list = h("div", { class: "chat-bg-tasks-list" }); - const selectedId = thread?.selectedShellId ?? null; - running.forEach((shell) => list.append(renderBackgroundTaskRow(shell, shell.id === selectedId))); - wrap.append(list); - const selected = running.find((shell) => shell.id === selectedId) ?? null; - if (selected) wrap.append(renderBackgroundTaskDetail(thread, selected)); - return wrap; -} - -/** One running shell task; tapping it toggles its detail pane. */ -function renderBackgroundTaskRow(shell, selected) { - const row = h("button", { - class: `chat-bg-task${selected ? " selected" : ""}`, - type: "button", - "data-shell": shell.id, - "aria-pressed": selected ? "true" : "false", - onclick: () => selectChatShell(shell.id), - }); - // A CSS play glyph, decorative only (the row's own text names the task). - row.append(h("span", { class: "chat-bg-task-glyph", "aria-hidden": "true" })); - row.append(h("span", { class: "chat-bg-task-status", text: SHELL_ROW_LABEL })); - row.append( - h("span", { - class: "chat-bg-task-command", - text: shellCommandSummary(shell.command), - title: String(shell.command ?? ""), - }), - ); - if (selected) row.append(h("span", { class: "chat-bg-task-details muted", text: SHELL_DETAILS_LABEL })); - return row; -} - -/** - * The selected task's read-only detail: its command, its identity in monospace - * and `Status: running`, then the output area — the exact label order and wording - * of ChatTranscript.BackgroundProcessDetail. Reload is always a bounded reread - * from the page's start (`Refresh`; `Retry` after a failure). - */ -function renderBackgroundTaskDetail(thread, shell) { - const labels = SHELL_OUTPUT_LABELS; - const pane = h("div", { class: "chat-bg-task-detail" }); - pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.COMMAND })); - const command = String(shell.command ?? "").trim(); - pane.append( - h("div", { - class: "chat-bg-task-command-full", - text: command === "" ? labels.UNAVAILABLE : shell.command, - }), - ); - pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.TASK_IDENTITY })); - pane.append(h("div", { class: "chat-bg-task-id monospace", text: String(shell.id ?? "") })); - pane.append(h("div", { class: "chat-bg-task-status-line", text: labels.STATUS_RUNNING })); - - const output = thread?.shellOutput ?? null; - switch (shellOutputState(output)) { - case SHELL_OUTPUT_LOADING: - pane.append(h("span", { class: "spinner chat-bg-task-spinner", "aria-hidden": "true" })); - break; - case SHELL_OUTPUT_ERROR: { - const row = h("div", { class: "chat-bg-task-error-row" }); - row.append(h("span", { class: "chat-bg-task-error", text: output.error })); - row.append( - h("button", { - class: "ghost chat-bg-task-retry", - type: "button", - text: labels.RETRY, - onclick: () => refreshChatShellOutput(shell.id), - }), - ); - pane.append(row); - break; - } - case SHELL_OUTPUT_UNAVAILABLE: - pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_UNAVAILABLE })); - break; - case SHELL_OUTPUT_EMPTY: - pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.NO_OUTPUT })); - break; - case SHELL_OUTPUT_READY: { - const page = output.page; - pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.OUTPUT })); - // Untrusted shell text: set as textContent, never parsed as markup. - pane.append(h("pre", { class: "chat-bg-task-output", text: String(page.output ?? "") })); - if (page.truncated) { - pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_BOUNDED })); - } - pane.append( - h("button", { - class: "ghost chat-bg-task-refresh", - type: "button", - text: labels.REFRESH, - onclick: () => refreshChatShellOutput(shell.id), - }), - ); - break; - } - default: - break; - } - return pane; -} - -/** - * 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, - { notices = [], running = false, now = Date.now(), approval = null } = {}, -) { - 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)); - // The conversation's local command lines sit after the turns, full width and - // deliberately unlike a message bubble (see ChatCommandNoticeItem). - for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice)); - // The approval card is the transcript's last item (C10) — after the notices and - // after the running indicator when it is shown — so the top bar's jump control - // and a fresh card both land at the end. - if (approval) transcript.append(renderChatApproval(sessionId, approval)); - 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 top bar's approval jump control (C10), naming the pending request. */ -function approvalJumpButton() { - return h("button", { - class: "ghost chat-approval-jump", - type: "button", - text: WAITING_FOR_APPROVAL_LABEL, - onclick: () => { - // The card is the transcript's last item, so the transcript's own end is the - // card; the one scroll path shared with jump-to-latest. - const el = document.getElementById("chatTranscript"); - if (!el) return; - state.chatFollowing = true; - el.scrollTop = el.scrollHeight; - updateChatJump(el); - }, - }); -} - -/** - * One approval request as a card (C10), the browser's port of - * `ui/chat/ChatApprovalCard.kt`: a shield and the headline, the status line, the - * request's resources newline-joined in monospace (blank entries dropped, at most - * six lines), the amber `RISK REVIEW` panel only while the app shows it, and the - * once/always/reject controls only while the request is actionable. Every server - * string is set with textContent and every node is built by hand. - */ -function renderChatApproval(sessionId, card) { - const node = h("div", { - class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`, - id: "chatApproval", - "data-request-id": card.requestId, - }); - const head = h("div", { class: "chat-approval-head" }); - head.append(shieldIcon("chat-approval-shield")); - const titles = h("div", { class: "chat-approval-titles" }); - titles.append(h("div", { class: "chat-approval-headline", text: card.headline })); - titles.append(h("div", { class: "chat-approval-status muted", text: card.statusLine })); - head.append(titles); - node.append(head); - if (card.resourceText !== "") { - // The padded frame around a padding-free clamp block: clamping the padded - // element itself lets the seventh line paint into its bottom padding. - const box = h("div", { class: "chat-approval-resources" }); - box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText })); - node.append(box); - } - if (card.showRisk && card.risk.trim() !== "") { - const risk = h("div", { class: "chat-approval-risk" }); - const riskHead = h("div", { class: "chat-approval-risk-head" }); - riskHead.append(shieldIcon("chat-approval-risk-shield")); - riskHead.append(h("span", { class: "chat-approval-risk-label", text: RISK_REVIEW_LABEL })); - risk.append(riskHead); - risk.append(h("div", { class: "chat-approval-risk-text", text: card.risk })); - node.append(risk); - } - if (card.actionable) { - const controls = h("div", { class: "chat-approval-controls" }); - controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary")); - controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId)); - controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId)); - node.append(controls); - } - return node; -} - -/** - * The app's amber outlined Shield (`Icons.Outlined.Shield`): an inline SVG stroked - * with `currentColor` so the palette's warn hue actually tints it, unlike the - * colour emoji it replaces. Decorative — the headline carries the meaning. - */ -function shieldIcon(className) { - const NS = "http://www.w3.org/2000/svg"; - const svg = document.createElementNS(NS, "svg"); - svg.setAttribute("class", className); - svg.setAttribute("viewBox", "0 0 24 24"); - svg.setAttribute("aria-hidden", "true"); - svg.setAttribute("focusable", "false"); - const path = document.createElementNS(NS, "path"); - path.setAttribute("d", "M12 3 5 6v5.5c0 4.2 2.8 8.1 7 9.5 4.2-1.4 7-5.3 7-9.5V6l-7-3z"); - path.setAttribute("fill", "none"); - path.setAttribute("stroke", "currentColor"); - path.setAttribute("stroke-width", "1.8"); - path.setAttribute("stroke-linejoin", "round"); - svg.append(path); - return svg; -} - -function approvalControl(label, decision, sessionId, requestId, extraClass = "") { - return h("button", { - class: `chat-approval-control${extraClass ? ` ${extraClass}` : ""}`, - type: "button", - text: label, - onclick: () => answerPermission(sessionId, requestId, decision), - }); -} - -/** - * 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 ?? "")); - }); -} - -/** One local command line in the transcript (see ChatCommandNoticeItem). */ -function renderChatCommandNotice(sessionId, notice) { - const failed = notice?.failed === true; - const row = h("div", { - class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`, - role: "note", - "data-notice-id": notice?.id ?? "", - }); - const head = h("div", { class: "chat-command-notice-head" }); - head.append( - h("span", { - class: "chat-command-notice-glyph", - "aria-hidden": "true", - // The app draws `Icons.Default.Terminal` for both states and only changes - // the tint, so both notices share the one terminal glyph. - text: CHAT_COMMAND_GLYPH, - }), - ); - head.append( - h("span", { class: "chat-command-notice-label", text: chatNoticeLabel(failed) }), - ); - row.append(head); - row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" })); - if (notice?.offer != null) { - const actions = h("div", { class: "chat-command-notice-actions" }); - actions.append( - h("button", { - class: "ghost chat-command-send-as-message", - type: "button", - text: "Send as message", - onclick: () => sendChatCommandOffer(sessionId, notice.id), - }), - ); - actions.append( - h("button", { - class: "ghost chat-command-cancel", - type: "button", - text: "Cancel", - onclick: () => dismissChatNotice(sessionId, notice.id), - }), - ); - row.append(actions); - } else { - // Android only offers the Send/Cancel pair on an offer-bearing notice, so a - // `/help` or `/new` line cannot be dismissed there. The browser item requires - // each notice to be individually dismissible; the wording and the offer pair - // still match the app verbatim, and this extra control is stated in PARITY. - const actions = h("div", { class: "chat-command-notice-actions" }); - actions.append( - h("button", { - class: "ghost chat-command-dismiss", - type: "button", - text: "Dismiss", - "aria-label": CHAT_COMMAND_DISMISS_LABEL, - onclick: () => dismissChatNotice(sessionId, notice.id), - }), - ); - row.append(actions); - } - return row; -} - -/** - * The composer at the foot of an open conversation: the queued notice, the - * attachment chips, the slash-command offer list, the attach control, the growing - * multiline field and the single send/stop control. All state is derived from the - * thread and its session; every server/model string is set with textContent. - */ -function renderChatComposer(thread, session, sessionId) { - const composer = h("div", { class: "chat-composer", id: "chatComposer" }); - if (!thread) return composer; - const controls = { selected: 0, palette: null, primary: null }; - - if (thread.queued) { - composer.append(h("div", { class: "chat-queued", id: "chatQueued", text: CHAT_QUEUED_NOTICE })); - } - - const strip = renderChatAttachmentStrip(sessionId, thread); - if (strip) composer.append(strip); - - const palette = h("div", { - class: "chat-command-palette", - id: "chatPalette", - role: "listbox", - "aria-label": "Command suggestions", - hidden: true, - }); - controls.palette = palette; - composer.append(palette); - - const row = h("div", { class: "chat-composer-row" }); - const fileInput = h("input", { - id: "chatFileInput", - class: "chat-file-input", - type: "file", - multiple: true, - tabindex: "-1", - "aria-hidden": "true", - onchange: (event) => { - onChatFilesPicked(sessionId, session, event.target.files); - event.target.value = ""; - }, - }); - row.append( - h( - "button", - { - class: "ghost chat-attach", - id: "chatAttach", - type: "button", - "aria-label": CHAT_ATTACH_LABEL, - title: CHAT_ATTACH_LABEL, - onclick: () => fileInput.click(), - }, - "\u{1F4CE}", - ), - ); - row.append(fileInput); - - const input = h("textarea", { - id: "chatInput", - class: "chat-composer-input", - rows: "1", - placeholder: CHAT_COMPOSER_PLACEHOLDER, - "aria-label": CHAT_COMPOSER_PLACEHOLDER, - spellcheck: "false", - }); - input.value = thread.draft ?? ""; - input.addEventListener("input", (event) => onComposerInput(event, sessionId, session, controls)); - input.addEventListener("keydown", (event) => onComposerKeydown(event, sessionId, session, controls)); - row.append(input); - - const primary = h("span", { class: "chat-composer-primary" }); - controls.primary = primary; - row.append(primary); - composer.append(row); - - const suggestions = chatCommandSuggestions(thread.draft); - fillCommandPalette(palette, suggestions, controls.selected, (index) => { - const command = suggestions[index]; - if (command) runChatCommand(sessionId, session, `/${command.name}`); - }); - fillComposerPrimary(primary, thread, { - onSend: () => submitChatComposer(sessionId, session, controls), - onStop: () => stopChatTurn(sessionId), - }); - - if (typeof requestAnimationFrame === "function") { - requestAnimationFrame(() => growComposerTextarea(input)); - } - return composer; -} - -/** The offer list above the composer: `/name` and the summary per row. */ -function fillCommandPalette(palette, suggestions, selected, onPick) { - if (!palette) return; - palette.replaceChildren(); - if (!suggestions || suggestions.length === 0) { - palette.hidden = true; - return; - } - palette.hidden = false; - suggestions.forEach((command, index) => { - palette.append( - h( - "div", - { - class: `chat-command-row${index === selected ? " selected" : ""}`, - role: "option", - "aria-selected": index === selected ? "true" : "false", - tabindex: "-1", - onclick: () => onPick(index), - }, - h("span", { class: "chat-command-name", text: `/${command.name}` }), - h("span", { class: "chat-command-summary", text: command.summary }), - ), - ); - }); -} - -/** - * The composer's single primary control: Stop while a turn is in flight (error - * tint), else Send, disabled unless the draft is sendable (or a slash draft). - * Stop routes to [onStop] (`chat_interrupt`), never to the submit path — the - * control must interrupt the running turn, as Android's `onStop` does. - */ -function fillComposerPrimary(primary, thread, { onSend, onStop } = {}) { - if (!primary) return; - primary.replaceChildren(); - if (composerAction(thread) === COMPOSER_STOP) { - primary.append( - h( - "button", - { - class: "chat-stop", - id: "chatStop", - type: "button", - "aria-label": CHAT_STOP_LABEL, - title: CHAT_STOP_LABEL, - onclick: onStop, - }, - "■", - ), - ); - return; - } - primary.append( - h( - "button", - { - class: "chat-send", - id: "chatSend", - type: "button", - "aria-label": CHAT_SEND_LABEL, - title: CHAT_SEND_LABEL, - disabled: !composerSendEnabled(thread), - onclick: onSend, - }, - "➤", - ), - ); -} - -/** The removable chips for the files attached to the next message. */ -function renderChatAttachmentStrip(sessionId, thread) { - const attachments = thread?.attachments ?? []; - if (attachments.length === 0) return null; - const strip = h("div", { class: "chat-attachment-strip", id: "chatAttachments" }); - for (const attachment of attachments) { - strip.append(renderChatAttachmentChip(sessionId, attachment)); - } - return strip; -} - -/** One attachment chip: its preview, its name, its size or error, and remove. */ -function renderChatAttachmentChip(sessionId, attachment) { - const failed = attachment?.error != null; - const display = attachmentDisplayName(attachment?.name, attachment?.uri); - const chip = h("div", { - class: `chat-attachment-chip${failed ? " chat-attachment-chip-failed" : ""}`, - }); - chip.append(renderAttachmentThumb(attachment, display)); - const body = h("div", { class: "chat-attachment-body" }); - body.append(h("span", { class: "chat-attachment-name", text: display })); - if (failed) { - body.append(h("span", { class: "chat-attachment-meta chat-attachment-error", text: attachment.error })); - } else if (Number(attachment?.size) > 0) { - body.append(h("span", { class: "chat-attachment-meta", text: humanBytes(attachment.size) })); - } - chip.append(body); - chip.append( - h( - "button", - { - class: "ghost chat-attachment-remove", - type: "button", - "aria-label": `Remove ${display}`, - title: `Remove ${display}`, - onclick: () => removeChatAttachment(sessionId, attachment.id), - }, - "✕", - ), - ); - return chip; -} - -/** The chip's square preview: the decoded thumbnail for an image, else a glyph. */ -function renderAttachmentThumb(attachment, display) { - if (attachment?.thumbUrl) { - return h("img", { - class: "chat-attachment-thumb", - src: attachment.thumbUrl, - alt: display, - "aria-hidden": "true", - }); - } - const image = String(attachment?.mime ?? "").startsWith("image/"); - return h("span", { - class: "chat-attachment-glyph", - "aria-hidden": "true", - text: image ? "🖼" : "📄", - }); -} - -/** 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 @@ -8183,46 +1363,6 @@ function applyRunEvent(frame) { // not in hand, the resync above covers the new row. } -/** - * 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) { - if (key) pushRoute({ kind: "template", key }); - else pushRoute({ kind: "templates" }); - state.selectedTemplateKey = key || null; - resetTemplateCreateState(); - renderContent(); -} /** * The run/pipeline detail reset a different selection needs: no stale pane, @@ -8451,53 +1591,99 @@ function stopDetailClock() { } } -/** - * (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; - const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true; - if (state.view === "chat" && thread?.running && !awaiting) { - chatClock = setInterval(() => { - chatNow = Date.now(); - updateChatIndicator(chatNow); - }, 1000); - } -} -function stopChatClock() { - if (chatClock) { - clearInterval(chatClock); - chatClock = null; - } -} +// --------------------------------------------------------------------------- +// View modules +// --------------------------------------------------------------------------- + +// The view modules receive the page shell through one runtime object rather than +// importing app.js, so the dependency direction stays app -> views (no cycle). +const runtime = { + state, + client, + repo, + runAlerts, + attentionLayer, + searchHost, + render, + renderContent, + renderHeader, + renderBanner, + endpointConfigured, + setServerUrlDraft, + pushRoute, + applyRoute, + openConfiguredEndpoint, + onReconnectClicked, + selectPipeline, + selectRun, + setError, + loadCurrentView, +}; + +const views = { + attention: createAttentionView(runtime), + settings: createSettingsView(runtime), + pipelines: createPipelinesView(runtime), + templates: createTemplatesView(runtime), + runs: createRunsView(runtime), + dialogs: createDialogsView(runtime), + runDetail: createRunDetailView(runtime), + chat: createChatView(runtime), + search: createSearchView(runtime), +}; +runtime.views = views; + +const { + renderAttentionBell, + refreshAttentionBell, + renderAttentionSheet, + closeAttentionSheet, + onRunAlertFrame, +} = views.attention; +const { renderSettingsView, refreshServerUrlError } = views.settings; +const { renderPipelineList, renderPipelineDetail } = views.pipelines; +const { renderTemplateGallery, renderTemplateDetail, loadTemplates, selectTemplate, resetTemplateCreateState, resetTemplateSelection, closeTemplateCreateDialog } = + views.templates; +const renderRunList = () => views.runs.renderRunList(listNow); +const renderRunDetail = () => views.runDetail.renderRunDetail(detailNow); +const { + renderChatList, + renderChatCreate, + renderChatConversation, + afterChatRender, + captureChatPosition, + refreshChatClock, + stopChatClock, + loadChatSessions, + loadChatDirectories, + startNewChat, + openChatSession, + subscribeChatSession, + clearChatSubscriptions, + settleChatThreads, + resyncOpenChat, + onChatEvent, + onChatPermission, + onChatFrame, + dismissChatClose, + dismissChatRename, +} = views.chat; +const { + openSearch, + closeSearch, + renderSearch, + onSearchInput, + sendSearchNow, +} = views.search; +const { openDecisionSheet, closeDecisionSheet, dismissConfirm, dismissActionError } = views.dialogs; +const { closeStagePane } = views.runDetail; + +// Kept as named exports for the UI smoke's page-rendered markdown/tool samples. +export const renderToolCallRow = views.chat.renderToolCallRow; +export const renderToolDiff = views.chat.renderToolDiff; +export const renderMarkdown = views.chat.renderMarkdown; -/** 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 @@ -8698,4 +1884,4 @@ window.addEventListener("popstate", () => { applyRoute(parseRoute(location.pathname, location.search)); }); -render(); +render(); \ No newline at end of file diff --git a/web/src/chat.js b/web/src/chat.js index e42a635a..efe62b1a 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -2153,7 +2153,7 @@ export function approvalResources(permission) { * non-blank resources joined by newlines and capped at * [MAX_APPROVAL_RESOURCE_LINES] lines, an embedded newline counting as a line, * with an ellipsis on the last kept line when the rest was dropped. The rendered - * box clamps to the same six lines (styles.css), so a single long resource that + * box clamps to the same six lines (chat.css), so a single long resource that * wraps is elided too rather than spilling onto a seventh line. */ export function approvalResourceText(permission) { diff --git a/web/src/dom.js b/web/src/dom.js new file mode 100644 index 00000000..a547db8f --- /dev/null +++ b/web/src/dom.js @@ -0,0 +1,77 @@ +// Shared DOM construction and small browser helpers. The page builds every +// node with these functions; server-derived text is always assigned through +// textContent, never innerHTML. + +export 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; +} + +/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */ +export 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 }), + ); +} + +/** Whether the Clipboard API can be used for a copy control. */ +export function canCopyLink() { + return typeof navigator !== "undefined" && Boolean(navigator.clipboard?.writeText); +} + +/** Whether the Web Share API can be used for a share control. */ +export function canShare() { + return typeof navigator !== "undefined" && typeof navigator.share === "function"; +} + +export 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. + } +} + +export 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. + } +} + +export async function shareArtifact(resolved) { + if (!resolved || !canShare()) return; + try { + await navigator.share({ url: resolved }); + } catch { + // The share chooser may be dismissed. + } +} + +/** A key/value row whose value is monospace (a key, an id) rather than prose. */ +export 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 })), + ); +} diff --git a/web/src/format.js b/web/src/format.js new file mode 100644 index 00000000..47e5fce6 --- /dev/null +++ b/web/src/format.js @@ -0,0 +1,19 @@ +// Shared display formatting and small status helpers used by the view modules. +// The date, duration and size formatters themselves live in their pure modules +// (runs.js, artifacts.js); this module owns the DOM-facing status mapping. + +import { ChangeKind } from "./changes.js"; + +export function isExecuting(run) { + return Boolean(run && run.executing); +} + +export function changeKindTone(kind) { + if (kind === ChangeKind.Added) return "ok"; + if (kind === ChangeKind.Deleted) return "bad"; + return "muted"; +} + +export function describeError(error) { + return error?.message || String(error); +} diff --git a/web/src/views/attention.js b/web/src/views/attention.js new file mode 100644 index 00000000..054b51e2 --- /dev/null +++ b/web/src/views/attention.js @@ -0,0 +1,326 @@ +// The header attention bell and the "Needs you" sheet, plus the notification +// ledger's frame observer. Pure ordering/labels live in attention.js; this module +// owns only the DOM and the page's dismissal state. + +import { h } from "../dom.js"; +import { + ATTENTION_STORAGE_KEY, + AttentionKind, + attentionBadgeLabel, + attentionDismiss, + attentionDismissAll, + attentionDismissalSnapshot, + attentionEntries, + attentionRowDescription, + decodeAttentionDismissals, + encodeAttentionDismissals, +} from "../attention.js"; +import { NOTIFY_STORAGE_KEY, decodeNotificationSettings, encodeNotificationSettings } from "../notify.js"; +import { stateGlyph } from "../runDetail.js"; + +/** The dismissed identities from storage at boot; anything unreadable is empty. */ +export function loadAttentionDismissed() { + try { + return decodeAttentionDismissals(localStorage.getItem(ATTENTION_STORAGE_KEY)); + } catch { + return new Set(); + } +} + +/** The asked flag from storage at boot; anything unreadable means never asked. */ +export function loadNotifyAsked() { + try { + return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked; + } catch { + return false; + } +} + +export function createAttentionView(rt) { + const { state, attentionLayer, runAlerts } = rt; + const render = (...args) => rt.render(...args); + const selectRun = (...args) => rt.selectRun(...args); + + +/** + * 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(); + } +} + +// --- 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. + } +} + +/** + * Fold one pushed `run_event` frame into the notification ledger (L5). It does + * not touch the runs list (R10's fold is separate); it only decides whether this + * transition raises exactly one notification. A run already failed/waiting when + * seeded, a duplicate frame, a non-qualifying status and a key the operator + * dismissed all produce nothing. + */ +function onRunAlertFrame(frame) { + const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed }); + if (!alert || !notificationsAllowed()) return; + try { + const notification = new Notification(alert.title, { body: alert.body, tag: alert.key }); + notification.onclick = () => { + window.focus(); + state.view = "runs"; + render(); + selectRun(alert.runId); + }; + } catch { + // Some browsers can throw even with permission granted; the in-page Needs + // you surface remains the only honest channel and nothing is faked. + } +} + +/** True only when a real browser notification can be constructed right now. */ +function notificationsAllowed() { + return ( + typeof globalThis.Notification === "function" && + globalThis.isSecureContext === true && + globalThis.Notification.permission === "granted" + ); +} + +/** Persist only the asked flag; never a permission claim, endpoint or credential. */ +function persistNotifyAsked(asked) { + state.notifyAsked = Boolean(asked); + try { + localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked })); + } catch { + // Storage disabled or full: the in-memory flag still applies for this session. + } +} + + return { + renderAttentionBell, + attentionCount, + refreshAttentionBell, + renderAttentionSheet, + openAttentionSheet, + closeAttentionSheet, + dismissAttentionEntries, + clearAttentionSheet, + activateAttentionEntry, + persistAttentionDismissed, + persistNotifyAsked, + onRunAlertFrame, + notificationsAllowed, + }; +} diff --git a/web/src/views/chat.js b/web/src/views/chat.js new file mode 100644 index 00000000..62158253 --- /dev/null +++ b/web/src/views/chat.js @@ -0,0 +1,3203 @@ +// The Chat destination: the session list and create pane, the live transcript, +// reasoning/tool panels, markdown, approval cards, background tasks, composer, +// slash commands, notices and the local rename/hide/seen store. Pure models live +// in chat.js and markdown.js; this module owns the DOM and the chat wire wiring. + +import { h, renderLiveBadge } from "../dom.js"; +import { describeError } from "../format.js"; +import { SHELL_OUTPUT_LIMIT, newChatOperationId } from "../repository.js"; +import { codeBlockLabel, parseInline, parseMarkdown } from "../markdown.js"; +import { formatDuration } from "../runs.js"; +import { humanBytes } from "../artifacts.js"; +import { changeStat, diffLineClass, diffLineSymbol } from "../changes.js"; +import { + BACKGROUND_TASKS_TITLE, + CHAT_ACTIONS_LABEL, + CHAT_ATTACH_LABEL, + CHAT_COMMAND_DISMISS_LABEL, + CHAT_COMMAND_GLYPH, + CHAT_COMPOSER_PLACEHOLDER, + CHAT_CREATE_BACK_LABEL, + CHAT_CREATE_CANCEL, + CHAT_CREATE_CONFIRM, + CHAT_CREATE_LOADING, + CHAT_CREATE_MODEL_NOTE, + CHAT_CREATE_PROMPT, + CHAT_CREATE_TITLE, + CHAT_EMPTY, + CHAT_FOLLOW_THRESHOLD_PX, + CHAT_HIDE_ACTION, + CHAT_LOADING, + CHAT_NEW_ACTION, + CHAT_NO_MATCH_ACTION, + CHAT_QUEUED_NOTICE, + CHAT_REMOVED_MESSAGE, + CHAT_RENAME_ACTION, + CHAT_RENAME_DISMISS, + CHAT_RENAME_FIELD_LABEL, + CHAT_RENAME_HELPER, + CHAT_RENAME_SAVE, + CHAT_RENAME_TITLE, + CHAT_SEARCH_LABEL, + CHAT_SEND_LABEL, + CHAT_STOP_LABEL, + CHAT_TAB_TITLE, + CHAT_UNDO_ACTION, + CLOSED_CHIP_LABEL, + CLOSED_SECTION_LABEL, + CLOSE_CHAT_ACTION, + CLOSE_CHAT_CONFIRM, + CLOSE_CHAT_DISMISS, + CLOSE_CHAT_TITLE, + COMPOSER_SEND, + COMPOSER_STOP, + CONVERSATION_EMPTY, + CONVERSATION_LOADING, + LOAD_OLDER_ACTION, + REOPEN_ACTION, + SELECT_CHAT_HINT, + APPROVAL_CONTROL_ALWAYS, + APPROVAL_CONTROL_ONCE, + APPROVAL_CONTROL_REJECT, + DECISION_ALWAYS, + DECISION_ONCE, + DECISION_REJECT, + RISK_REVIEW_LABEL, + WAITING_FOR_APPROVAL_LABEL, + SHELL_DETAILS_LABEL, + SHELL_OUTPUT_EMPTY, + SHELL_OUTPUT_ERROR, + SHELL_OUTPUT_LABELS, + SHELL_OUTPUT_LOADING, + SHELL_OUTPUT_READY, + SHELL_OUTPUT_UNAVAILABLE, + SHELL_ROW_LABEL, + applyChatEvent, + applyChatOverrides, + applyChatPermission, + appendChatNotice, + approvalCard, + attachmentDisplayName, + attachmentError, + attachmentFiles, + backgroundTasksRunningLabel, + chatBottomDistancePx, + chatCommandEffect, + chatCommandHelp, + chatCommandSuggestions, + chatCreateFailed, + chatCreateSucceeded, + chatFirstScroll, + chatFollowsAt, + chatHeaderMeta, + chatNoMatchMessage, + chatNoticeLabel, + chatOpensAtNewest, + chatShowJumpToLatest, + chatStartInLabel, + chatStreamState, + closeChatConfirmation, + composerAction, + composerCanSend, + composerSendEnabled, + composerSubmit, + decodeChatOverrides, + decodeChatSeen, + defaultDirectoryChoice, + directoryChoices, + directoryLabel, + dismissChatNotice as dismissChatNoticeModel, + emptyChatOverrides, + emptyChatSeen, + encodeChatOverrides, + encodeChatSeen, + filterSessions, + groupSessionsByDirectory, + hideChatOverride, + historyResync, + isChatSessionUnseen, + makeChatNotice, + markChatUnseen, + mergeHistoryPage, + mergeShellFrame, + newChatCreateState, + newChatThread, + parseChatInput, + queuedAfterFrame, + readChatSeen, + reasoningLabel, + renameChatOverride, + restoreChatOverride, + resumedThread, + runningAfterFrame, + runningBackgroundShells, + runningToolElapsedMillis, + seedChatSeen, + sessionActivity, + sessionActivityBadge, + sessionChipLabel, + sessionMeta, + sessionStatusLabel, + selectChatDirectory as selectChatDirectoryModel, + sessionTitle, + sessionWorkLabel, + settledThread, + shellCommandSummary, + shellOutputState, + shellsLoaded, + takeChatNoticeOffer as takeChatNoticeOfferModel, + formatToolDuration, + threadElapsedMillis, + threadPhase, + threadRunningTools, + threadToolElapsedMillis, + TURN_PHASE_WAITING, + toolCallCount, + toolCallRow, + toolCallsAnnouncement, + toolCallsLabel, + toolDetail, + toolFailed, + toolLabel, + toolLongRunning, + toolRunning, + toolsRunning, + transcriptRows, + turnElapsedMillis, + turnPhaseLabel, +} from "../chat.js"; + +const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1"; + +/** + * The per-chat composer drafts (C8). Mirrored into localStorage, the browser + * analogue of the Android store's per-device draft: a draft survives a reload, + * keyed by session id (attachments are memory-only — a File handle cannot be + * serialised). The in-memory `thread.draft` is the source of truth while the page + * is open; this is only the persistence beside it. + */ +const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1"; + +/** + * The operator's own chat changes (C13): local renames and hidden session ids, + * the web analogue of Android's `chat_overrides` preference. One JSON value: + * `{titles:{"<id>":"<title>"},hidden:["<id>"]}`. A local title wins over the + * server's on every later list refresh; a hidden id only disappears here. + */ +const CHAT_OVERRIDES_STORAGE_KEY = "pipelines.web.chatOverrides.v1"; + +/** + * What the operator has already seen of the session list (C13), the web analogue + * of Android's `chat_seen` preference. One JSON value: + * `{seenAt:{"<id>":<updated_at ms>},unseen:["<id>"]}`. The watermark is advanced + * only by opening a chat (or first-sight seeding), never by a stale list. + */ +const CHAT_SEEN_STORAGE_KEY = "pipelines.web.chatSeen.v1"; + +/** The sessionStorage key for this tab's verification-chat ids. */ +const EPHEMERAL_CHATS_KEY = "pipelines.web.ephemeralChats.v1"; + +/** This tab's verification-chat ids (never listed), or an empty set. */ +export function readEphemeralChatIds() { + try { + const raw = sessionStorage.getItem(EPHEMERAL_CHATS_KEY); + const ids = raw ? JSON.parse(raw) : []; + return Array.isArray(ids) ? ids.filter((id) => typeof id === "string" && id.trim() !== "") : []; + } catch { + return []; + } +} + +/** The persisted per-session scroll positions, or an empty map when unreadable. */ +export function readChatScrollStore() { + try { + const parsed = JSON.parse(localStorage.getItem(CHAT_SCROLL_STORAGE_KEY) ?? "{}"); + return parsed && typeof parsed === "object" ? parsed : {}; + } catch { + return {}; + } +} + + +/** The persisted per-chat drafts, or an empty map when unreadable. */ +export function readChatDraftStore() { + try { + const parsed = JSON.parse(localStorage.getItem(CHAT_DRAFT_STORAGE_KEY) ?? "{}"); + return parsed && typeof parsed === "object" ? parsed : {}; + } catch { + return {}; + } +} + +/** The persisted draft for one conversation, or "" when there is none. */ +export function readChatDraft(sessionId) { + const value = readChatDraftStore()[sessionId]; + return typeof value === "string" ? value : ""; +} + +/** The persisted local chat overrides; unreadable storage means no overrides. */ +export function readChatOverridesStore() { + try { + return decodeChatOverrides(localStorage.getItem(CHAT_OVERRIDES_STORAGE_KEY)); + } catch { + return emptyChatOverrides(); + } +} + +/** The persisted seen state; unreadable storage means nothing seen. */ +export function readChatSeenStore() { + try { + return decodeChatSeen(localStorage.getItem(CHAT_SEEN_STORAGE_KEY)); + } catch { + return emptyChatSeen(); + } +} + +export function createChatView(rt) { + const { state, repo } = rt; + let chatClock = null; + let chatNow = Date.now(); + const renderContent = (...args) => rt.renderContent(...args); + const renderActionFailedDialog = (...args) => rt.views.dialogs.renderActionFailedDialog(...args); + + /** 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 + } +} + + /** + * Mirror one conversation's draft into localStorage. A blank draft clears its + * entry so the store cannot grow without bound; the in-memory `thread.draft` + * stays the source of truth, this is only the persistence beside it. + */ +function saveChatDraft(sessionId, text) { + if (!sessionId) return; + try { + const store = readChatDraftStore(); + if (String(text ?? "") === "") delete store[sessionId]; + else store[sessionId] = String(text); + localStorage.setItem(CHAT_DRAFT_STORAGE_KEY, JSON.stringify(store)); + } catch { + // storage may be full or disabled; the in-memory draft still holds + } +} + + /** Persist the current local overrides; storage failure leaves memory authoritative. */ +function saveChatOverrides() { + try { + localStorage.setItem(CHAT_OVERRIDES_STORAGE_KEY, encodeChatOverrides(state.chatOverrides)); + } catch { + // storage may be full or disabled; the in-memory overrides still hold + } +} + + + /** + * Persist the seen state only when it actually changed. Every frame and refresh + * would otherwise rewrite localStorage for no reason. + */ +function saveChatSeen(next) { + if (next === state.chatSeen) return; + state.chatSeen = next; + try { + localStorage.setItem(CHAT_SEEN_STORAGE_KEY, encodeChatSeen(state.chatSeen)); + } catch { + // storage may be full or disabled; the in-memory state still holds + } +} + + +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 { + const listed = await repo.chatSessions(); + // Keep this page's own verification chats, which the server intentionally + // never returns, at the head of the in-memory list (memory-only; see + // chatEphemeralIds). Everything else is the server's list, in its order. + const held = state.chatSessions.filter( + (session) => + state.chatEphemeralIds.has(session.id) && !listed.some((entry) => entry.id === session.id), + ); + state.chatSessions = [...held, ...listed]; + state.chatLoaded = true; + // Fold this device's seen state in: the active chat has been read, and every + // session seen for the first time gets a baseline so pre-existing chats are + // not all reported as new. + saveChatSeen(seedChatSeen(state.chatSeen, state.chatSessions, state.chatActiveId)); + } catch (error) { + state.chatError = describeError(error); + } + state.chatLoading = false; + renderContent(); +} + +// --------------------------------------------------------------------------- +// The create flow (C2, ChatCreatePane.kt) +// --------------------------------------------------------------------------- + +/** + * Open the create pane with a fresh operation id. The id is minted once per + * intent, so a retry after a refusal reuses it and the server can dedupe the + * create rather than starting a second session. + */ +function startNewChat() { + state.chatCreate = newChatCreateState(newChatOperationId()); + state.chatDirectoriesError = ""; + renderContent(); + loadChatDirectories(); +} + +/** + * Fetch `chat_directories` for the open picker. A failure keeps the reason for the + * pane's error state; blank entries are dropped here as well as in the pure model + * so a malformed reply can never produce an empty row. An already-loaded list is + * reused unless [force] (the error state's Retry) asks again. + */ +async function loadChatDirectories(force = false) { + if (!state.chatCreate || state.chatDirectoriesLoading) return; + if (state.chatDirectoriesLoaded && !force) return; + state.chatDirectoriesLoading = true; + state.chatDirectoriesError = ""; + renderContent(); + try { + const directories = await repo.chatDirectories(); + state.chatDirectories = (directories ?? []).filter((entry) => String(entry ?? "").trim() !== ""); + state.chatDirectoriesLoaded = true; + } catch (error) { + state.chatDirectoriesError = describeError(error); + } + state.chatDirectoriesLoading = false; + renderContent(); +} + +/** Select one directory row (the value is what chat_create will send). */ +function selectChatDirectory(value) { + if (!state.chatCreate) return; + state.chatCreate = selectChatDirectoryModel(state.chatCreate, value); + renderContent(); +} + +/** Leave the create flow without creating anything. */ +function cancelNewChat() { + state.chatCreate = null; + renderContent(); +} + +/** + * Create the chat in the chosen directory. Guarded against a double submit: the + * guard reads the held state, so a second click while the request is in flight + * sends nothing. On success the pane closes, the created session goes to the head + * of the list, becomes the open conversation and loads its (empty) history; on + * failure the server's own reason stays in the pane, which does not close. + */ +async function createNewChat() { + const create = state.chatCreate; + if (!create || create.creating) return; + state.chatCreate = { ...create, creating: true, error: "" }; + renderContent(); + try { + // Not ephemeral: this is the operator's own create path (the UI smoke uses the + // same path for its one real session and closes it afterwards). + const created = await repo.chatCreate("New chat", create.directory, create.operationId); + state.chatCreate = null; + state.chatSessions = chatCreateSucceeded(state.chatSessions, created); + await openChatSession(created.id); + await loadChatSessions(); + } catch (error) { + if (!state.chatCreate) return; + state.chatCreate = chatCreateFailed(state.chatCreate, describeError(error)); + 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.chatMenu = null; + state.chatPlaced = null; + state.chatFollowing = true; + state.chatReasoning = new Set(); + state.chatToolPanels = new Set(); + state.chatToolRows = new Set(); + // Opening reads the conversation: advance the watermark to its current recency + // and clear the explicit unseen mark (a row that is absent has no recency). + const session = state.chatSessions.find((candidate) => candidate.id === id) ?? null; + saveChatSeen(readChatSeen(state.chatSeen, id, session?.updated_at ?? 0)); + const existing = state.chatThreads.get(id); + state.chatThreads.set(id, { + ...newChatThread(id), + ...(existing ?? {}), + // The composer's own per-chat state (C8/C9) survives a switch; the draft is + // seeded from localStorage on the first open (the per-device analogue). The + // live-stream fields (C5) come from `newChatThread`. + draft: existing ? existing.draft ?? "" : readChatDraft(id), + attachments: existing?.attachments ?? [], + notices: existing?.notices ?? [], + 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); + // Load the session's background shells (C11) so the bar appears on open, not + // only after the next pushed shell frame. + loadChatShells(id); + await loadChatHistory(id); +} + +/** Replace one conversation's fields, keeping every other field intact. */ +function setThread(sessionId, patch) { + const current = state.chatThreads.get(sessionId); + if (!current) return; + state.chatThreads.set(sessionId, { ...current, ...patch }); +} + +/** + * 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, and drop its observed shells. 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; a shell's exit may + * have been swallowed by the same gap, so the retained shells are forgotten and + * re-learned from `chat_shells` on reconnect (mirrors ChatStore.streamResumed). + */ +function settleChatThreads() { + for (const [id, thread] of state.chatThreads) { + const hasShells = (thread?.shells ?? []).length > 0; + if (thread?.running || thread?.queued || hasShells) { + state.chatThreads.set(id, resumedThread(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; + markBackgroundChatUnseen(sessionId); + const thread = state.chatThreads.get(sessionId); + state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now())); + renderContent(); +} + +/** + * A frame for a conversation that is not on screen marks it explicitly unseen, + * so its live activity is visible in the list even though a pushed stream carries + * no wall-clock recency to compare. The active chat is read as it arrives and is + * never marked. + */ +function markBackgroundChatUnseen(sessionId) { + if (!sessionId || sessionId === state.chatActiveId) return; + saveChatSeen(markChatUnseen(state.chatSeen, sessionId)); +} + +/** + * Fold one pushed `chat_permission` frame into its conversation (C10). Only a + * conversation this client has open is folded — the server only pushes a + * permission frame for sessions this connection is subscribed to, but the guard + * keeps a frame for a session nobody opened from creating a thread. The card is + * derived from the stored frame plus the local answer, so a resolved re-push + * always clears the controls. + */ +function onChatPermission(frame) { + const sessionId = String(frame?.session_id ?? "").trim(); + if (!sessionId || !state.chatThreads.has(sessionId)) return; + const thread = state.chatThreads.get(sessionId); + const next = applyChatPermission(thread, frame); + // A different request replaces the card, so the previous refusal's reason (and + // the error line it owns) no longer describes what is on screen. + const replaced = + String(thread?.permission?.request_id ?? "") !== String(next.permission?.request_id ?? ""); + if (replaced && thread?.permissionError) { + next.error = thread.error === thread.permissionError ? "" : next.error; + next.permissionError = ""; + } + state.chatThreads.set(sessionId, next); + if (sessionId === state.chatActiveId) renderContent(); +} + +/** + * Answer the pending permission request (C10): settle the matching card + * optimistically so the buttons are never left offering a decision already made, + * then send `chat_reply`. A refused reply reopens the same request (the local + * answer is cleared) and surfaces the server's reason through the thread's own + * error line, so an unaccepted decision is never shown as accepted. A refusal + * that arrives after a different request replaced the card is ignored. + */ +async function answerPermission(sessionId, requestId, decision) { + const thread = state.chatThreads.get(sessionId); + const permission = thread?.permission; + if (!thread || String(permission?.request_id ?? "") !== requestId) return; + setThread(sessionId, { permissionAnswer: decision }); + renderContent(); + try { + await repo.chatReply(sessionId, requestId, decision); + // A retried answer the server accepted clears the reason a previous refusal + // left on the thread's error line — and only that reason, never an unrelated + // error the conversation is carrying. + const settled = state.chatThreads.get(sessionId); + if (settled?.permissionError && settled.error === settled.permissionError) { + setThread(sessionId, { error: "", permissionError: "" }); + renderContent(); + } + } catch (error) { + const current = state.chatThreads.get(sessionId); + if (!current || String(current.permission?.request_id ?? "") !== requestId) return; + const reason = describeError(error); + setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason }); + 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. + * Fetch a session's currently verified shells (C11) and retain only the exits + * this client itself observed, so an exited task never reappears as running and a + * shell the server no longer lists drops out. Called when the conversation opens + * and on every stream reconnect (a gap may have swallowed an exit). A failure is + * non-fatal: the transcript stays usable and the bar keeps its last known state. + */ +async function loadChatShells(id) { + if (!id || state.connection.kind !== "connected") return; + try { + const running = await repo.chatShells(id); + const thread = state.chatThreads.get(id); + if (!thread) return; + state.chatThreads.set(id, { ...thread, shells: shellsLoaded(thread.shells, running) }); + renderContent(); + } catch { + // The shell list is a background convenience; leave the thread untouched. + } +} + +/** + * Toggle a running task's detail pane (C11). Selecting a shell fetches its + * bounded output page; selecting the selected one again closes it. Mirrors + * ChatStore.selectShell: an id that is not a known shell is ignored. + */ +function selectChatShell(shellId) { + const sessionId = state.chatActiveId; + const thread = sessionId ? state.chatThreads.get(sessionId) : null; + if (!thread) return; + const closing = thread.selectedShellId === shellId; + if (!closing && !(thread.shells ?? []).some((shell) => shell.id === shellId)) return; + const next = closing ? null : shellId; + state.chatThreads.set(sessionId, { ...thread, selectedShellId: next, shellOutput: null }); + renderContent(); + if (next) refreshChatShellOutput(next); +} + +/** + * Reread a selected task's bounded output page (C11) from the page's start. The + * cursor is always 0 and the limit is the server's 64 KiB bound, so the client + * never grows output unbounded and a Refresh never appends. A reply for a shell + * that is no longer selected is ignored, exactly like ChatStore.shellOutput*. + */ +async function refreshChatShellOutput(shellId) { + const sessionId = state.chatActiveId; + if (!sessionId || !shellId) return; + shellOutputLoading(sessionId, shellId); + renderContent(); + try { + const page = await repo.chatShellOutput(sessionId, shellId, { cursor: 0, limit: SHELL_OUTPUT_LIMIT }); + shellOutputLoaded(sessionId, shellId, page); + } catch (error) { + shellOutputFailed(sessionId, shellId, describeError(error)); + } + renderContent(); +} + +/** Mark a selected task's output pane loading (ignored for a stale selection). */ +function shellOutputLoading(sessionId, shellId) { + const thread = state.chatThreads.get(sessionId); + if (!thread || thread.selectedShellId !== shellId) return; + state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: true, error: "", page: null } }); +} + +/** + * Apply a loaded output page, merging a shell the page reports back into the + * retained list (keeping the command already learned when the page omits it). + */ +function shellOutputLoaded(sessionId, shellId, page) { + const thread = state.chatThreads.get(sessionId); + if (!thread || thread.selectedShellId !== shellId) return; + const reported = page?.shell; + const shells = reported && String(reported.id ?? "").trim() !== "" + ? mergeShellFrame(thread.shells, reported) + : thread.shells ?? []; + state.chatThreads.set(sessionId, { ...thread, shells, shellOutput: { loading: false, error: "", page } }); +} + +/** Report a failed output read against the still-selected task (Retry is offered). */ +function shellOutputFailed(sessionId, shellId, message) { + const thread = state.chatThreads.get(sessionId); + if (!thread || thread.selectedShellId !== shellId) return; + state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: false, error: message, page: null } }); +} + +/** + * The reconnect repair (C5/C11): re-attach the open chat's stream, replace its + * conversation with the newest history page wholesale and re-learn its shells. + * Everything the gap could have missed is repaired; a turn that was in flight is + * settled and the retained shells are dropped before the fresh snapshot arrives. + * 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, resumedThread(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. + } + await loadChatShells(id); + 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); + // The merged page replaces only the history fields; spreading it over the + // held thread keeps the composer's draft, attachments and flags intact (a + // draft typed while the page was loading is not lost). + setThread(id, mergeHistoryPage(previous, page, { older: false })); + } catch (error) { + setThread(id, { 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; + setThread(id, mergeHistoryPage(current, page, { older: true })); + } catch (error) { + setThread(id, { loading: false, error: describeError(error) }); + } + renderContent(); +} + +/** Open the Close chat? confirm for [session] (the mutation only on confirm). */ +function openChatClose(session) { + state.chatMenu = null; + 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); + } + // Closing also finishes the session for this client: the conversation leaves + // the pane, back to the list (mirrors Android's `finishSession` calling + // `chatStore.close`). A rejection above leaves the conversation exactly as it + // was; `settledThread` has already cleared the running/queued bits. + if (state.chatActiveId === session.id) { + state.chatActiveId = null; + } + } 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; + state.chatMenu = null; + 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, + ); +} + +// --------------------------------------------------------------------------- +// This device's chat changes (C13): local rename, hide + undo, row menu +// --------------------------------------------------------------------------- + + + /** Persist this tab's verification-chat ids for a reload of the same tab. */ +function writeEphemeralChatIds(ids) { + try { + sessionStorage.setItem(EPHEMERAL_CHATS_KEY, JSON.stringify([...ids])); + } catch { + // Storage may be unavailable; the in-memory set still covers this page. + } +} + +/** The server row with this device's local title applied (for the open pane). */ +function effectiveChatSession(session) { + if (!session) return null; + return applyChatOverrides([session], state.chatOverrides)[0] ?? session; +} + + +function openChatMenu(sessionId) { + state.chatMenu = state.chatMenu === sessionId ? null : sessionId; + renderContent(); + if (state.chatMenu) { + // The panel hangs below its button. Near the bottom of the window that would + // put the items off-screen (a real hit-test failure, not just clipping), so + // flip the panel above the row when it does not fit below. + const row = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"]`); + const panel = row?.querySelector(".chat-menu-panel"); + if (panel && panel.getBoundingClientRect().bottom > window.innerHeight - 8) { + panel.style.top = "auto"; + panel.style.bottom = "calc(100% + 4px)"; + } + // The re-render replaced the focused button; move focus into the panel so a + // keyboard operator can walk the items without hunting for the next Tab stop. + const first = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"] .chat-menu-item`); + first?.focus(); + } +} + +/** Open the Rename chat dialog for [session] (its current effective title). */ +function openChatRename(session) { + state.chatMenu = null; + state.chatRename = session; + renderContent(); + // Same re-render note as the menu: put the cursor in the Name field. + document.getElementById("chatRenameInput")?.focus(); +} + +function dismissChatRename() { + state.chatRename = null; + renderContent(); +} + +/** + * Record a local rename, persist it and reflect it at once: the row shows the + * local title on the next render (and every later refresh), and an open + * conversation's own title follows. Nothing is sent to the server — the + * brokered protocol has no chat rename. + */ +function applyLocalChatRename(sessionId, title) { + const next = renameChatOverride(state.chatOverrides, sessionId, title); + if (next === state.chatOverrides) return false; + state.chatOverrides = next; + saveChatOverrides(); + const local = next.titles[String(sessionId)]; + if (local != null) setThread(sessionId, { title: local }); + return true; +} + +/** + * The dialog's Save: trim, record the override, close the dialog and re-render. + * A blank title is ignored (Save is already disabled while trimmed-blank). + */ +function acceptChatRename(session, title) { + const trimmed = String(title ?? "").trim(); + if (trimmed === "") return; + applyLocalChatRename(session.id, trimmed); + state.chatRename = null; + renderContent(); +} + +/** + * Hide a session on this device only. The server is not asked to delete + * anything: the row disappears from this list, its conversation closes, and the + * one snackbar says exactly that with an Undo. A new hide replaces the previous + * report (one snackbar slot), never queues behind it. + */ +function hideChatLocally(sessionId) { + const id = String(sessionId ?? ""); + if (!id) return; + const next = hideChatOverride(state.chatOverrides, id); + if (next === state.chatOverrides) return; + state.chatOverrides = next; + saveChatOverrides(); + state.chatMenu = null; + state.chatRename = null; + // Hiding closes the conversation, exactly as Android's remove does: the thread + // is dropped, the active id cleared and the subscription forgotten. + state.chatThreads.delete(id); + if (state.chatActiveId === id) { + state.chatActiveId = null; + state.chatPlaced = null; + } + if (state.chatSubscriptions.has(id)) { + state.chatSubscriptions = new Set(state.chatSubscriptions); + state.chatSubscriptions.delete(id); + } + installChatSnackbar(id); + renderContent(); +} + +/** Replace the one in-flight hide report and (re)start its auto-dismiss timer. */ +function installChatSnackbar(sessionId) { + if (state.chatSnackbarTimer != null) clearTimeout(state.chatSnackbarTimer); + state.chatSnackbarSeq += 1; + const id = state.chatSnackbarSeq; + state.chatSnackbar = { id, sessionId }; + state.chatSnackbarTimer = setTimeout(() => { + state.chatSnackbarTimer = null; + if (state.chatSnackbar?.id !== id) return; + state.chatSnackbar = null; + renderContent(); + }, 6000); +} + +/** Undo the last hide: restore its row and clear the report (nothing server-side). */ +function undoHideChat() { + const sessionId = state.chatSnackbar?.sessionId; + if (!sessionId) return; + const next = restoreChatOverride(state.chatOverrides, sessionId); + if (next !== state.chatOverrides) { + state.chatOverrides = next; + saveChatOverrides(); + } + clearChatSnackbar(); + renderContent(); +} + +/** Drop the hide report and its timer (Undo, expiry, or leaving the list). */ +function clearChatSnackbar() { + if (state.chatSnackbarTimer != null) { + clearTimeout(state.chatSnackbarTimer); + state.chatSnackbarTimer = null; + } + state.chatSnackbar = null; +} + +// --------------------------------------------------------------------------- +// The composer and its slash commands (C8 · C9) +// --------------------------------------------------------------------------- + +// The per-conversation attachment and notice ids. An id is unique across the +// page, so a chip or a command line is unambiguously removable after a re-render. +let chatAttachmentSeq = 0; +let chatNoticeSeq = 0; + +/** Revoke an attachment's image object URL, if it created one. */ +function releaseAttachment(attachment) { + if (attachment?.thumbUrl) { + try { + URL.revokeObjectURL(attachment.thumbUrl); + } catch { + // already gone + } + } +} + +/** Revoke every attachment's object URL (used once the message is sent/gone). */ +function releaseAttachments(attachments) { + for (const attachment of attachments ?? []) releaseAttachment(attachment); +} + +/** + * Fold one server push into its session's thread: any frame for the session + * clears the queued notice (the turn it waited behind moved on), and a settled + * step clears the running bit the Stop control reads. The live transcript owns + * the rest of the frame fold; this only keeps the composer honest while C5 is + * still to land. + */ +function onChatFrame(message) { + const frame = message?.chat_event; + if (!frame || !frame.session_id) return; + const sessionId = frame.session_id; + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + const queued = queuedAfterFrame(thread.queued, frame); + const running = runningAfterFrame(thread.running, frame); + if (queued === thread.queued && running === thread.running) return; + setThread(sessionId, { queued, running }); + if (sessionId === state.chatActiveId) renderContent(); +} + +/** Add one local command line to a conversation's transcript. */ +function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + chatNoticeSeq += 1; + const notice = makeChatNotice(`notice-${chatNoticeSeq}`, text, { failed, offer }); + setThread(sessionId, { notices: appendChatNotice(thread.notices, notice) }); +} + +/** Remove one local command line (the operator cancelled or dismissed it). */ +function dismissChatNotice(sessionId, noticeId) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + setThread(sessionId, { notices: dismissChatNoticeModel(thread.notices, noticeId) }); + renderContent(); +} + +/** + * Take an unknown-command offer's draft, removing the notice first so a stale + * tap can neither send the same draft twice nor send anything at all. + */ +function takeChatNoticeOffer(sessionId, noticeId) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return null; + const taken = takeChatNoticeOfferModel(thread.notices, noticeId); + if (taken.offer == null) return null; + setThread(sessionId, { notices: taken.notices }); + return taken.offer; +} + +/** + * The composer's draft field, updated in place on every keystroke: the draft is + * mirrored into localStorage, the textarea grows to fit (1–6 rows), and the + * palette and the send/stop control are refreshed without rebuilding the DOM (so + * the operator keeps focus and caret). + */ +function onComposerInput(event, sessionId, session, controls) { + const value = event.target.value; + setThread(sessionId, { draft: value }); + saveChatDraft(sessionId, value); + growComposerTextarea(event.target); + refreshComposerControls(sessionId, session, controls); +} + +/** + * The composer's key handling. While the offer list is showing, Up/Down move the + * highlight and Enter runs the highlighted command (mirrors ChatComposer's + * preview handler). Enter otherwise submits — which is inert while a turn is + * running unless the palette or a slash draft is present (see composerSubmit); + * Shift+Enter is left to insert a newline. + */ +function onComposerKeydown(event, sessionId, session, controls) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + const suggestions = chatCommandSuggestions(thread.draft); + if (suggestions.length > 0 && (event.key === "ArrowDown" || event.key === "ArrowUp")) { + event.preventDefault(); + const step = event.key === "ArrowDown" ? 1 : -1; + controls.selected = (controls.selected + step + suggestions.length) % suggestions.length; + refreshComposerControls(sessionId, session, controls); + return; + } + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + submitChatComposer(sessionId, session, controls); + } +} + +/** + * Grow the composer's textarea between one and six rows to fit its content. The + * element is `box-sizing: border-box` with vertical padding, so the cap and the + * measured height both include the padding and the border: a six-row field is + * six full text lines, not five-and-a-bit, and the first row is not clipped. + */ +function growComposerTextarea(el) { + if (!el) return; + const style = getComputedStyle(el); + const line = parseFloat(style.lineHeight) || 20; + const border = el.offsetHeight - el.clientHeight; + const padding = (parseFloat(style.paddingTop) || 0) + (parseFloat(style.paddingBottom) || 0); + const maxRows = 6; + const max = line * maxRows + padding + border; + el.style.height = "auto"; + const wanted = el.scrollHeight + border; + el.style.height = `${Math.min(wanted, max)}px`; + el.style.overflowY = wanted > max ? "auto" : "hidden"; +} + +/** + * Refresh the composer's derived parts (the offer list, the send/stop control) + * after a keystroke, without rebuilding the textarea. The highlighted row moves + * only through the palette itself, so it is preserved here. + */ +function refreshComposerControls(sessionId, session, controls) { + const thread = state.chatThreads.get(sessionId); + if (!thread || !controls) return; + const suggestions = chatCommandSuggestions(thread.draft); + if (controls.selected >= suggestions.length) controls.selected = 0; + fillCommandPalette(controls.palette, suggestions, controls.selected, (index) => { + const command = suggestions[index]; + if (command) runChatCommand(sessionId, session, `/${command.name}`); + }); + fillComposerPrimary(controls.primary, thread, { + onSend: () => submitChatComposer(sessionId, session, controls), + onStop: () => stopChatTurn(sessionId), + }); +} + +/** Run the composer's submit (Enter): a command runs, else the draft sends. */ +function submitChatComposer(sessionId, session, controls) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + const action = composerSubmit(thread, controls?.selected ?? 0); + if (action.kind === "command") { + runChatCommand(sessionId, session, action.text); + } else if (action.kind === "send") { + sendChatPrompt(sessionId, session); + } +} + +/** + * Run one slash command against a conversation (C9). The draft is always consumed + * here — a slash draft is never handed to the prompt path — so only an explicit + * "Send as message" from an unknown-command offer reaches the agent. Every + * outcome is a local transcript line. + */ +function runChatCommand(sessionId, session, text) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + setThread(sessionId, { draft: "" }); + saveChatDraft(sessionId, ""); + const view = { ...thread, draft: "", directory: session?.directory ?? "", running: thread.running === true }; + const effect = chatCommandEffect(parseChatInput(text), view); + if (effect == null) return; + applyChatCommandEffect(sessionId, session, effect); + renderContent(); +} + +/** + * Perform one command effect. `/new` creates a session in the current directory + * and opens it (the create request is C2's; until C2 lands the browser sends + * `chat_create` directly); `/close` reuses the C3 confirm; `/rename` writes to + * C13's durable device-local store; `/stop` interrupts; `/help` shows the + * command list. + */ +function applyChatCommandEffect(sessionId, session, effect) { + switch (effect.kind) { + case "start-session": + startChatSession(effect.directory); + break; + case "finish-session": + if (session) openChatClose(session); + break; + case "rename-session": + renameChatSessionLocally(sessionId, effect.title); + break; + case "stop-turn": + stopChatTurn(sessionId); + break; + case "show-help": + addChatNotice(sessionId, chatCommandHelp()); + break; + case "report": + addChatNotice(sessionId, effect.text, { failed: true, offer: effect.offer ?? null }); + break; + default: + break; + } +} + +/** `/new`: create a session titled "New chat" in [directory] and open it. */ +async function startChatSession(directory) { + const from = state.chatActiveId; + try { + // An automated check (the UI smoke) can mark its throwaway chat ephemeral, so + // creating one for verification never adds a stray "New chat" to the + // operator's list. Set only by test tooling; a normal page leaves it unset. + const ephemeral = globalThis.__pipelinesEphemeralChat === true; + const created = await repo.chatCreate("New chat", directory, undefined, { ephemeral }); + if (ephemeral) { + state.chatEphemeralIds = new Set(state.chatEphemeralIds).add(created.id); + writeEphemeralChatIds(state.chatEphemeralIds); + } + // The list is the server's; insert the created session so the row is present + // before the conversation opens, then refresh from the server. + state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)]; + state.chatThreads.set(created.id, { + draft: "", + attachments: [], + notices: [], + queued: false, + running: false, + messages: [], + nextCursor: "", + hasMore: false, + loaded: false, + loading: true, + error: "", + }); + const title = String(created.title ?? "").trim() || "New chat"; + addChatNotice(created.id, `Started a new session “${title}” in ${directory}.`); + await openChatSession(created.id); + // An ephemeral (verification) create is intentionally absent from the server's + // list, so a refresh here would replace the just-opened conversation and drop + // its local notice. The row is already spliced above and is kept by + // loadChatSessions via chatEphemeralIds, so a listed create still refreshes. + if (!ephemeral) await loadChatSessions(); + } catch (error) { + if (from) addChatNotice(from, `Couldn't start a new session in ${directory}: ${describeError(error)}`, { failed: true }); + state.actionError = describeError(error); + renderContent(); + } +} + +/** + * `/rename`: rename the session on this device only, through the same durable + * store the row's Rename chat dialog uses (C13). The local title wins over the + * server's on every later refresh; nothing is sent to the server. + */ +function renameChatSessionLocally(sessionId, title) { + const trimmed = String(title ?? "").trim(); + if (trimmed === "") return; + applyLocalChatRename(sessionId, trimmed); + addChatNotice(sessionId, `Renamed this session to “${trimmed}” on this device only; the server's title is unchanged.`); +} + +/** The composer's Stop control: interrupt the session's running turn. */ +async function stopChatTurn(sessionId) { + try { + await repo.chatInterrupt(sessionId); + addChatNotice(sessionId, "Stopping the running turn…"); + } catch (error) { + state.actionError = describeError(error); + } + renderContent(); +} + +/** + * Send the composer's draft with its attachments (mirrors + * `AppViewModel.sendChatPrompt`): the draft is trimmed, the compose state is + * cleared at once, and a rejected prompt restores the draft and the attachments + * with the server's own message. + */ +async function sendChatPrompt(sessionId, session) { + const thread = state.chatThreads.get(sessionId); + if (!thread || !composerCanSend(thread)) return; + const text = String(thread.draft).trim(); + if (text === "") return; + const attachments = thread.attachments ?? []; + releaseAttachments(attachments); + setThread(sessionId, { draft: "", attachments: [] }); + saveChatDraft(sessionId, ""); + renderContent(); + await postChatPrompt(sessionId, text, attachments); +} + +/** + * One prompt, from the composer or an unknown-command offer. Flags the chat + * running, posts it, and takes the attachments back out flagged with the + * server's reason if it is rejected. The live transcript item (C5) owns the + * optimistic bubble; this only drives the composer and its request. + */ +async function postChatPrompt(sessionId, text, attachments) { + const body = String(text).trim(); + if (body === "") return; + setThread(sessionId, { running: true }); + renderContent(); + try { + const queued = await repo.chatPrompt(sessionId, body, attachmentFiles(attachments)); + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + // Prompting a closed session reopens it on the server; clear the local mark + // too so the list agrees without a re-fetch. + applyChatSessionUpdate(sessionId, null, false); + setThread(sessionId, { queued, running: true }); + renderContent(); + } catch (error) { + const message = describeError(error); + const restored = (attachments ?? []).map((attachment) => { + releaseAttachment(attachment); + return { ...attachment, thumbUrl: null, error: message }; + }); + setThread(sessionId, { + running: false, + queued: false, + error: message, + draft: body, + attachments: restored, + }); + saveChatDraft(sessionId, body); + state.actionError = message; + renderContent(); + } +} + +/** Send an unknown-command offer's draft through the ordinary prompt path. */ +function sendChatCommandOffer(sessionId, noticeId) { + const offer = takeChatNoticeOffer(sessionId, noticeId); + if (offer == null) return; + renderContent(); + postChatPrompt(sessionId, offer, []); +} + +/** + * Resolve the files the operator picked into composer attachments. Only the + * metadata is read here (nothing is transmitted until the message is sent): the + * browser has no `content://` reference, so the file's own name is carried as the + * best-effort reference string. A file over the limit is returned with its error + * set rather than dropped. + */ +function onChatFilesPicked(sessionId, session, fileList) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + const picked = []; + for (const file of fileList ?? []) { + chatAttachmentSeq += 1; + const name = String(file?.name ?? ""); + const mime = String(file?.type ?? ""); + const size = Number(file?.size) || 0; + picked.push({ + id: `att-${chatAttachmentSeq}`, + name, + uri: name, + mime, + size, + error: attachmentError(name, size, true), + thumbUrl: mime.startsWith("image/") ? createThumbUrl(file) : null, + file, + }); + } + if (picked.length === 0) return; + setThread(sessionId, { attachments: [...(thread.attachments ?? []), ...picked] }); + renderContent(); +} + +/** An object URL for a local image preview, or null when the browser refuses one. */ +function createThumbUrl(file) { + try { + return URL.createObjectURL(file); + } catch { + return null; + } +} + +/** Remove one attachment from the next message and release its preview URL. */ +function removeChatAttachment(sessionId, attachmentId) { + const thread = state.chatThreads.get(sessionId); + if (!thread) return; + const attachment = (thread.attachments ?? []).find((entry) => entry.id === attachmentId); + releaseAttachment(attachment); + setThread(sessionId, { + attachments: (thread.attachments ?? []).filter((entry) => entry.id !== attachmentId), + }); + renderContent(); +} + +function renderChatList() { + // The open menu must not be clipped by the list's rounded-corner overflow; the + // class is present only while a menu is open, so the normal list stays clipped. + const list = h("div", { class: `list chat-list${state.chatMenu ? " menu-open" : ""}` }); + 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); + }, + }), + // C2: the create path stays one tap away while the list is narrowed, the same + // trailing action the app keeps beside its search control. + h("button", { + class: "ghost chat-new", + type: "button", + text: CHAT_NEW_ACTION, + onclick: startNewChat, + }), + ); + 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 visible = applyChatOverrides(state.chatSessions, state.chatOverrides); + const filtered = filterSessions(visible, 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) { + const empty = chatEmpty(CHAT_EMPTY); + empty.append( + h("button", { + class: "ghost chat-new", + type: "button", + text: CHAT_NEW_ACTION, + onclick: startNewChat, + }), + ); + 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 unseen = + !session.closed && + isChatSessionUnseen(session, { + activeId: state.chatActiveId, + seen: state.chatSeen, + opened: state.chatThreads.has(session.id), + }); + const activity = sessionActivity(thread?.running === true, unseen); + 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; the Chat actions menu 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)), + }), + ); + row.append(renderChatActionsMenu(session)); + return row; +} + +/** + * The create pane (C2): the app's NewChatPane. A back control leaves without + * creating, then the directory error / loading / picker states in the app's own + * order, the model note and the footer naming the value that will be sent. Every + * server string is set with textContent. + */ +function renderChatCreate() { + const create = state.chatCreate; + const pane = h("div", { class: "detail chat-detail chat-create" }); + + const bar = h("div", { class: "chat-bar chat-create-bar" }); + bar.append( + h( + "button", + { + class: "ghost chat-create-back", + type: "button", + "aria-label": CHAT_CREATE_BACK_LABEL, + title: CHAT_CREATE_BACK_LABEL, + onclick: cancelNewChat, + }, + h("span", { class: "chat-create-back-glyph", "aria-hidden": "true", text: "←" }), + ), + h("h2", { class: "chat-bar-title chat-create-title", text: CHAT_CREATE_TITLE }), + ); + pane.append(bar); + + if (state.chatDirectoriesError && !state.chatDirectoriesLoaded) { + const empty = chatEmpty(state.chatDirectoriesError); + empty.classList.add("chat-create-directories-error"); + empty.append( + h("button", { + class: "ghost chat-create-retry", + type: "button", + text: "Retry", + onclick: () => loadChatDirectories(true), + }), + ); + pane.append(empty); + } else if (!state.chatDirectoriesLoaded) { + pane.append(h("div", { class: "chat-create-loading muted", text: CHAT_CREATE_LOADING })); + } else { + pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT })); + + const choices = directoryChoices(state.chatDirectories); + const selected = + choices.find((choice) => choice.createDirectory === create.directory) ?? + defaultDirectoryChoice(choices); + const list = h("div", { + class: "chat-create-choices", + role: "listbox", + "aria-label": CHAT_CREATE_PROMPT, + }); + for (const choice of choices) { + const active = choice.createDirectory === selected?.createDirectory; + const row = h("button", { + class: `row chat-create-choice${active ? " selected" : ""}`, + type: "button", + role: "option", + "aria-selected": active ? "true" : "false", + "data-directory": choice.createDirectory, + onclick: () => selectChatDirectory(choice.createDirectory), + }); + row.append(h("span", { class: "row-title chat-create-choice-label", text: choice.label })); + if (choice.secondary) { + row.append(h("span", { class: "row-meta chat-create-choice-path", text: choice.secondary })); + } + list.append(row); + } + pane.append(list); + + // A refresh that failed after a successful first load keeps the choices and + // says why the list may be stale (the app's own bodySmall error line). + if (state.chatDirectoriesError) { + pane.append(h("div", { class: "chat-create-directories-error", text: state.chatDirectoriesError })); + } + if (create.error) { + pane.append(h("div", { class: "chat-create-error", text: create.error })); + } + pane.append(h("p", { class: "chat-create-model-note muted", text: CHAT_CREATE_MODEL_NOTE })); + + const directory = selected?.createDirectory ?? create.directory; + const footer = h("div", { class: "chat-create-footer" }); + footer.append(h("span", { class: "chat-create-start", text: chatStartInLabel(directory) })); + footer.append( + h("button", { + class: "ghost chat-create-cancel", + type: "button", + text: CHAT_CREATE_CANCEL, + disabled: create.creating, + onclick: cancelNewChat, + }), + ); + const confirm = h("button", { + class: "chat-create-confirm", + type: "button", + "aria-label": CHAT_CREATE_CONFIRM, + disabled: create.creating, + onclick: createNewChat, + }); + if (create.creating) { + confirm.append(h("span", { class: "spinner chat-create-spinner", "aria-hidden": "true" })); + } else { + confirm.append(document.createTextNode(CHAT_CREATE_CONFIRM)); + } + footer.append(confirm); + pane.append(footer); + } + + appendChatDialogs(pane); + return pane; +} + +/** + * One row's Chat actions menu, with Android's items in its order: Rename…, then + * Close chat… (open) or Reopen (closed), then Hide on this device. Closing is the + * shared, server-side finish; hiding only affects this device and says so. + */ +function renderChatActionsMenu(session) { + const wrap = h("div", { class: "chat-row-actions chat-menu-wrap" }); + const expanded = state.chatMenu === session.id; + wrap.append( + h("button", { + class: "ghost chat-menu-button", + type: "button", + text: "⋯", + "aria-label": CHAT_ACTIONS_LABEL, + "aria-haspopup": "menu", + "aria-expanded": expanded ? "true" : "false", + title: CHAT_ACTIONS_LABEL, + onclick: (event) => { + event.stopPropagation(); + openChatMenu(session.id); + }, + }), + ); + if (expanded) { + const menu = h("div", { class: "chat-menu-panel", role: "menu", "aria-label": CHAT_ACTIONS_LABEL }); + menu.addEventListener("click", (event) => event.stopPropagation()); + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-rename", + type: "button", + role: "menuitem", + text: CHAT_RENAME_ACTION, + onclick: () => openChatRename(session), + }), + ); + if (session.closed) { + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-reopen", + type: "button", + role: "menuitem", + text: REOPEN_ACTION, + disabled: state.chatBusy, + onclick: () => reopenChatSession(session.id), + }), + ); + } else { + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-close", + type: "button", + role: "menuitem", + text: CLOSE_CHAT_ACTION, + disabled: state.chatBusy, + onclick: () => openChatClose(session), + }), + ); + } + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-hide", + type: "button", + role: "menuitem", + text: CHAT_HIDE_ACTION, + onclick: () => hideChatLocally(session.id), + }), + ); + wrap.append(menu); + } + return wrap; +} + +/** 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 effective = effectiveChatSession(session); + const thread = state.chatThreads.get(state.chatActiveId) ?? null; + const title = effective ? sessionTitle(effective) : state.chatActiveId.slice(0, 18); + // The pending approval card (C10), derived from the stored frame plus the local + // answer. While it is actionable the top bar offers a jump control and the + // running indicator stands down (a turn blocked on a decision is not generating). + const approval = approvalCard(thread?.permission, thread?.permissionAnswer); + const awaiting = approval?.actionable === true; + + 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), + }), + ); + } + // The approval jump control appears only while a request is actionable, and + // brings its card (the transcript's last item) into view — the one scroll path, + // so a pending request is reached the same way new content is. + if (awaiting) bar.append(approvalJumpButton()); + 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); + + // The background-tasks bar (C11) sits above the transcript, outside the + // scroller so the C14 scroll positions are untouched. It is present only while + // a shell is still running and disappears with the last exit. + const backgroundTasks = renderBackgroundTasks(thread); + if (backgroundTasks) pane.append(backgroundTasks); + + const notices = thread?.notices ?? []; + 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 ?? []); + // The running indicator stands down while an approval is pending (C10): a turn + // blocked on a decision is not generating, so neither the spinner nor its clock + // shows. The composer's Stop control stays governed by thread.running. + const running = thread?.running === true && !awaiting; + if (rows.length === 0 && notices.length === 0 && !running && !approval) { + pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY })); + } else { + pane.append( + renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now(), approval }), + ); + } + if (thread?.error && thread?.loaded) { + pane.append(h("div", { class: "chat-transcript-error", text: thread.error })); + } + } + + // The composer sits at the foot of the conversation, always available while a + // chat is open (the transcript may still be loading). + pane.append(renderChatComposer(thread, session, state.chatActiveId)); + + 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.chatRename) pane.append(renderChatRenameDialog(state.chatRename)); + if (state.chatSnackbar) pane.append(renderChatSnackbar()); + if (state.actionError) pane.append(renderActionFailedDialog()); +} + +/** + * The one hide report (C13): the exact Android message and an `Undo` action. It + * is a fixed overlay (so a re-render or the transcript's height never moves it) + * and it is replaced, never queued, by a newer hide. + */ +function renderChatSnackbar() { + const bar = h("div", { class: "chat-snackbar", role: "status" }); + bar.append(h("span", { class: "chat-snackbar-message", text: CHAT_REMOVED_MESSAGE })); + bar.append( + h("button", { + class: "ghost chat-snackbar-undo", + type: "button", + text: CHAT_UNDO_ACTION, + onclick: () => undoHideChat(), + }), + ); + return bar; +} + +/** + * The Rename chat dialog (C13): a locally-kept name, with the helper that says so + * plainly. Save is disabled while the trimmed value is blank; typing toggles that + * state directly, so the transcript's scroll is never disturbed by a re-render. + * Nothing is sent to the server — there is no chat rename on the wire. + */ +function renderChatRenameDialog(session) { + const effective = effectiveChatSession(session) ?? session; + const overlay = h("div", { + class: "confirm-dialog confirm-chat-rename", + role: "dialog", + "aria-modal": "true", + "aria-label": CHAT_RENAME_TITLE, + }); + overlay.addEventListener("click", (event) => { + if (event.target === overlay) dismissChatRename(); + }); + const panel = h("div", { class: "confirm-panel" }); + panel.append(h("h2", { class: "confirm-title", text: CHAT_RENAME_TITLE })); + const field = h("div", { class: "chat-rename-field" }); + field.append(h("label", { class: "chat-rename-label", for: "chatRenameInput", text: CHAT_RENAME_FIELD_LABEL })); + const input = h("input", { + id: "chatRenameInput", + class: "rename-input chat-rename-input", + type: "text", + value: sessionTitle(effective), + spellcheck: "false", + autocomplete: "off", + }); + field.append(input); + panel.append(field); + panel.append(h("p", { class: "chat-rename-helper", text: CHAT_RENAME_HELPER })); + const actions = h("div", { class: "confirm-actions" }); + actions.append( + h("button", { + class: "ghost confirm-dismiss chat-rename-cancel", + type: "button", + text: CHAT_RENAME_DISMISS, + onclick: dismissChatRename, + }), + ); + const save = h("button", { + class: "confirm-accept chat-rename-save", + type: "button", + text: CHAT_RENAME_SAVE, + disabled: input.value.trim() === "", + onclick: () => acceptChatRename(session, input.value), + }); + // Toggle Save in place on input: no renderContent, so the transcript's scroll + // position (C14) is untouched while the operator types. + input.addEventListener("input", () => { + save.disabled = input.value.trim() === ""; + }); + actions.append(save); + panel.append(actions); + overlay.append(panel); + return overlay; +} + +/** + * The background-tasks bar (C11): the running shells this conversation still + * owns. It returns null (renders nothing) unless at least one shell is running, + * so it disappears the moment the last task exits. Heading `Background tasks` + + * `{n} running`; the list shows at most BACKGROUND_TASK_VISIBLE_ROWS rows and + * scrolls beyond; a selected row reveals its bounded, read-only output pane. + * Every server string is set with textContent (never innerHTML). + */ +function renderBackgroundTasks(thread) { + const running = runningBackgroundShells(thread?.shells ?? []); + if (running.length === 0) return null; + const wrap = h("section", { class: "chat-bg-tasks", id: "chatBackgroundTasks" }); + const head = h("div", { class: "chat-bg-tasks-head" }); + head.append(h("span", { class: "chat-bg-tasks-title", text: BACKGROUND_TASKS_TITLE })); + head.append( + h("span", { class: "chat-bg-tasks-count muted", text: backgroundTasksRunningLabel(running.length) }), + ); + wrap.append(head); + const list = h("div", { class: "chat-bg-tasks-list" }); + const selectedId = thread?.selectedShellId ?? null; + running.forEach((shell) => list.append(renderBackgroundTaskRow(shell, shell.id === selectedId))); + wrap.append(list); + const selected = running.find((shell) => shell.id === selectedId) ?? null; + if (selected) wrap.append(renderBackgroundTaskDetail(thread, selected)); + return wrap; +} + +/** One running shell task; tapping it toggles its detail pane. */ +function renderBackgroundTaskRow(shell, selected) { + const row = h("button", { + class: `chat-bg-task${selected ? " selected" : ""}`, + type: "button", + "data-shell": shell.id, + "aria-pressed": selected ? "true" : "false", + onclick: () => selectChatShell(shell.id), + }); + // A CSS play glyph, decorative only (the row's own text names the task). + row.append(h("span", { class: "chat-bg-task-glyph", "aria-hidden": "true" })); + row.append(h("span", { class: "chat-bg-task-status", text: SHELL_ROW_LABEL })); + row.append( + h("span", { + class: "chat-bg-task-command", + text: shellCommandSummary(shell.command), + title: String(shell.command ?? ""), + }), + ); + if (selected) row.append(h("span", { class: "chat-bg-task-details muted", text: SHELL_DETAILS_LABEL })); + return row; +} + +/** + * The selected task's read-only detail: its command, its identity in monospace + * and `Status: running`, then the output area — the exact label order and wording + * of ChatTranscript.BackgroundProcessDetail. Reload is always a bounded reread + * from the page's start (`Refresh`; `Retry` after a failure). + */ +function renderBackgroundTaskDetail(thread, shell) { + const labels = SHELL_OUTPUT_LABELS; + const pane = h("div", { class: "chat-bg-task-detail" }); + pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.COMMAND })); + const command = String(shell.command ?? "").trim(); + pane.append( + h("div", { + class: "chat-bg-task-command-full", + text: command === "" ? labels.UNAVAILABLE : shell.command, + }), + ); + pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.TASK_IDENTITY })); + pane.append(h("div", { class: "chat-bg-task-id monospace", text: String(shell.id ?? "") })); + pane.append(h("div", { class: "chat-bg-task-status-line", text: labels.STATUS_RUNNING })); + + const output = thread?.shellOutput ?? null; + switch (shellOutputState(output)) { + case SHELL_OUTPUT_LOADING: + pane.append(h("span", { class: "spinner chat-bg-task-spinner", "aria-hidden": "true" })); + break; + case SHELL_OUTPUT_ERROR: { + const row = h("div", { class: "chat-bg-task-error-row" }); + row.append(h("span", { class: "chat-bg-task-error", text: output.error })); + row.append( + h("button", { + class: "ghost chat-bg-task-retry", + type: "button", + text: labels.RETRY, + onclick: () => refreshChatShellOutput(shell.id), + }), + ); + pane.append(row); + break; + } + case SHELL_OUTPUT_UNAVAILABLE: + pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_UNAVAILABLE })); + break; + case SHELL_OUTPUT_EMPTY: + pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.NO_OUTPUT })); + break; + case SHELL_OUTPUT_READY: { + const page = output.page; + pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.OUTPUT })); + // Untrusted shell text: set as textContent, never parsed as markup. + pane.append(h("pre", { class: "chat-bg-task-output", text: String(page.output ?? "") })); + if (page.truncated) { + pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_BOUNDED })); + } + pane.append( + h("button", { + class: "ghost chat-bg-task-refresh", + type: "button", + text: labels.REFRESH, + onclick: () => refreshChatShellOutput(shell.id), + }), + ); + break; + } + default: + break; + } + return pane; +} + +/** + * 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, + { notices = [], running = false, now = Date.now(), approval = null } = {}, +) { + 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)); + // The conversation's local command lines sit after the turns, full width and + // deliberately unlike a message bubble (see ChatCommandNoticeItem). + for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice)); + // The approval card is the transcript's last item (C10) — after the notices and + // after the running indicator when it is shown — so the top bar's jump control + // and a fresh card both land at the end. + if (approval) transcript.append(renderChatApproval(sessionId, approval)); + 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 top bar's approval jump control (C10), naming the pending request. */ +function approvalJumpButton() { + return h("button", { + class: "ghost chat-approval-jump", + type: "button", + text: WAITING_FOR_APPROVAL_LABEL, + onclick: () => { + // The card is the transcript's last item, so the transcript's own end is the + // card; the one scroll path shared with jump-to-latest. + const el = document.getElementById("chatTranscript"); + if (!el) return; + state.chatFollowing = true; + el.scrollTop = el.scrollHeight; + updateChatJump(el); + }, + }); +} + +/** + * One approval request as a card (C10), the browser's port of + * `ui/chat/ChatApprovalCard.kt`: a shield and the headline, the status line, the + * request's resources newline-joined in monospace (blank entries dropped, at most + * six lines), the amber `RISK REVIEW` panel only while the app shows it, and the + * once/always/reject controls only while the request is actionable. Every server + * string is set with textContent and every node is built by hand. + */ +function renderChatApproval(sessionId, card) { + const node = h("div", { + class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`, + id: "chatApproval", + "data-request-id": card.requestId, + }); + const head = h("div", { class: "chat-approval-head" }); + head.append(shieldIcon("chat-approval-shield")); + const titles = h("div", { class: "chat-approval-titles" }); + titles.append(h("div", { class: "chat-approval-headline", text: card.headline })); + titles.append(h("div", { class: "chat-approval-status muted", text: card.statusLine })); + head.append(titles); + node.append(head); + if (card.resourceText !== "") { + // The padded frame around a padding-free clamp block: clamping the padded + // element itself lets the seventh line paint into its bottom padding. + const box = h("div", { class: "chat-approval-resources" }); + box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText })); + node.append(box); + } + if (card.showRisk && card.risk.trim() !== "") { + const risk = h("div", { class: "chat-approval-risk" }); + const riskHead = h("div", { class: "chat-approval-risk-head" }); + riskHead.append(shieldIcon("chat-approval-risk-shield")); + riskHead.append(h("span", { class: "chat-approval-risk-label", text: RISK_REVIEW_LABEL })); + risk.append(riskHead); + risk.append(h("div", { class: "chat-approval-risk-text", text: card.risk })); + node.append(risk); + } + if (card.actionable) { + const controls = h("div", { class: "chat-approval-controls" }); + controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary")); + controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId)); + controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId)); + node.append(controls); + } + return node; +} + +/** + * The app's amber outlined Shield (`Icons.Outlined.Shield`): an inline SVG stroked + * with `currentColor` so the palette's warn hue actually tints it, unlike the + * colour emoji it replaces. Decorative — the headline carries the meaning. + */ +function shieldIcon(className) { + const NS = "http://www.w3.org/2000/svg"; + const svg = document.createElementNS(NS, "svg"); + svg.setAttribute("class", className); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("focusable", "false"); + const path = document.createElementNS(NS, "path"); + path.setAttribute("d", "M12 3 5 6v5.5c0 4.2 2.8 8.1 7 9.5 4.2-1.4 7-5.3 7-9.5V6l-7-3z"); + path.setAttribute("fill", "none"); + path.setAttribute("stroke", "currentColor"); + path.setAttribute("stroke-width", "1.8"); + path.setAttribute("stroke-linejoin", "round"); + svg.append(path); + return svg; +} + +function approvalControl(label, decision, sessionId, requestId, extraClass = "") { + return h("button", { + class: `chat-approval-control${extraClass ? ` ${extraClass}` : ""}`, + type: "button", + text: label, + onclick: () => answerPermission(sessionId, requestId, decision), + }); +} + +/** + * 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. + */ +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. + */ +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. + */ +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 ?? "")); + }); +} + +/** One local command line in the transcript (see ChatCommandNoticeItem). */ +function renderChatCommandNotice(sessionId, notice) { + const failed = notice?.failed === true; + const row = h("div", { + class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`, + role: "note", + "data-notice-id": notice?.id ?? "", + }); + const head = h("div", { class: "chat-command-notice-head" }); + head.append( + h("span", { + class: "chat-command-notice-glyph", + "aria-hidden": "true", + // The app draws `Icons.Default.Terminal` for both states and only changes + // the tint, so both notices share the one terminal glyph. + text: CHAT_COMMAND_GLYPH, + }), + ); + head.append( + h("span", { class: "chat-command-notice-label", text: chatNoticeLabel(failed) }), + ); + row.append(head); + row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" })); + if (notice?.offer != null) { + const actions = h("div", { class: "chat-command-notice-actions" }); + actions.append( + h("button", { + class: "ghost chat-command-send-as-message", + type: "button", + text: "Send as message", + onclick: () => sendChatCommandOffer(sessionId, notice.id), + }), + ); + actions.append( + h("button", { + class: "ghost chat-command-cancel", + type: "button", + text: "Cancel", + onclick: () => dismissChatNotice(sessionId, notice.id), + }), + ); + row.append(actions); + } else { + // Android only offers the Send/Cancel pair on an offer-bearing notice, so a + // `/help` or `/new` line cannot be dismissed there. The browser item requires + // each notice to be individually dismissible; the wording and the offer pair + // still match the app verbatim, and this extra control is stated in PARITY. + const actions = h("div", { class: "chat-command-notice-actions" }); + actions.append( + h("button", { + class: "ghost chat-command-dismiss", + type: "button", + text: "Dismiss", + "aria-label": CHAT_COMMAND_DISMISS_LABEL, + onclick: () => dismissChatNotice(sessionId, notice.id), + }), + ); + row.append(actions); + } + return row; +} + +/** + * The composer at the foot of an open conversation: the queued notice, the + * attachment chips, the slash-command offer list, the attach control, the growing + * multiline field and the single send/stop control. All state is derived from the + * thread and its session; every server/model string is set with textContent. + */ +function renderChatComposer(thread, session, sessionId) { + const composer = h("div", { class: "chat-composer", id: "chatComposer" }); + if (!thread) return composer; + const controls = { selected: 0, palette: null, primary: null }; + + if (thread.queued) { + composer.append(h("div", { class: "chat-queued", id: "chatQueued", text: CHAT_QUEUED_NOTICE })); + } + + const strip = renderChatAttachmentStrip(sessionId, thread); + if (strip) composer.append(strip); + + const palette = h("div", { + class: "chat-command-palette", + id: "chatPalette", + role: "listbox", + "aria-label": "Command suggestions", + hidden: true, + }); + controls.palette = palette; + composer.append(palette); + + const row = h("div", { class: "chat-composer-row" }); + const fileInput = h("input", { + id: "chatFileInput", + class: "chat-file-input", + type: "file", + multiple: true, + tabindex: "-1", + "aria-hidden": "true", + onchange: (event) => { + onChatFilesPicked(sessionId, session, event.target.files); + event.target.value = ""; + }, + }); + row.append( + h( + "button", + { + class: "ghost chat-attach", + id: "chatAttach", + type: "button", + "aria-label": CHAT_ATTACH_LABEL, + title: CHAT_ATTACH_LABEL, + onclick: () => fileInput.click(), + }, + "\u{1F4CE}", + ), + ); + row.append(fileInput); + + const input = h("textarea", { + id: "chatInput", + class: "chat-composer-input", + rows: "1", + placeholder: CHAT_COMPOSER_PLACEHOLDER, + "aria-label": CHAT_COMPOSER_PLACEHOLDER, + spellcheck: "false", + }); + input.value = thread.draft ?? ""; + input.addEventListener("input", (event) => onComposerInput(event, sessionId, session, controls)); + input.addEventListener("keydown", (event) => onComposerKeydown(event, sessionId, session, controls)); + row.append(input); + + const primary = h("span", { class: "chat-composer-primary" }); + controls.primary = primary; + row.append(primary); + composer.append(row); + + const suggestions = chatCommandSuggestions(thread.draft); + fillCommandPalette(palette, suggestions, controls.selected, (index) => { + const command = suggestions[index]; + if (command) runChatCommand(sessionId, session, `/${command.name}`); + }); + fillComposerPrimary(primary, thread, { + onSend: () => submitChatComposer(sessionId, session, controls), + onStop: () => stopChatTurn(sessionId), + }); + + if (typeof requestAnimationFrame === "function") { + requestAnimationFrame(() => growComposerTextarea(input)); + } + return composer; +} + +/** The offer list above the composer: `/name` and the summary per row. */ +function fillCommandPalette(palette, suggestions, selected, onPick) { + if (!palette) return; + palette.replaceChildren(); + if (!suggestions || suggestions.length === 0) { + palette.hidden = true; + return; + } + palette.hidden = false; + suggestions.forEach((command, index) => { + palette.append( + h( + "div", + { + class: `chat-command-row${index === selected ? " selected" : ""}`, + role: "option", + "aria-selected": index === selected ? "true" : "false", + tabindex: "-1", + onclick: () => onPick(index), + }, + h("span", { class: "chat-command-name", text: `/${command.name}` }), + h("span", { class: "chat-command-summary", text: command.summary }), + ), + ); + }); +} + +/** + * The composer's single primary control: Stop while a turn is in flight (error + * tint), else Send, disabled unless the draft is sendable (or a slash draft). + * Stop routes to [onStop] (`chat_interrupt`), never to the submit path — the + * control must interrupt the running turn, as Android's `onStop` does. + */ +function fillComposerPrimary(primary, thread, { onSend, onStop } = {}) { + if (!primary) return; + primary.replaceChildren(); + if (composerAction(thread) === COMPOSER_STOP) { + primary.append( + h( + "button", + { + class: "chat-stop", + id: "chatStop", + type: "button", + "aria-label": CHAT_STOP_LABEL, + title: CHAT_STOP_LABEL, + onclick: onStop, + }, + "■", + ), + ); + return; + } + primary.append( + h( + "button", + { + class: "chat-send", + id: "chatSend", + type: "button", + "aria-label": CHAT_SEND_LABEL, + title: CHAT_SEND_LABEL, + disabled: !composerSendEnabled(thread), + onclick: onSend, + }, + "➤", + ), + ); +} + +/** The removable chips for the files attached to the next message. */ +function renderChatAttachmentStrip(sessionId, thread) { + const attachments = thread?.attachments ?? []; + if (attachments.length === 0) return null; + const strip = h("div", { class: "chat-attachment-strip", id: "chatAttachments" }); + for (const attachment of attachments) { + strip.append(renderChatAttachmentChip(sessionId, attachment)); + } + return strip; +} + +/** One attachment chip: its preview, its name, its size or error, and remove. */ +function renderChatAttachmentChip(sessionId, attachment) { + const failed = attachment?.error != null; + const display = attachmentDisplayName(attachment?.name, attachment?.uri); + const chip = h("div", { + class: `chat-attachment-chip${failed ? " chat-attachment-chip-failed" : ""}`, + }); + chip.append(renderAttachmentThumb(attachment, display)); + const body = h("div", { class: "chat-attachment-body" }); + body.append(h("span", { class: "chat-attachment-name", text: display })); + if (failed) { + body.append(h("span", { class: "chat-attachment-meta chat-attachment-error", text: attachment.error })); + } else if (Number(attachment?.size) > 0) { + body.append(h("span", { class: "chat-attachment-meta", text: humanBytes(attachment.size) })); + } + chip.append(body); + chip.append( + h( + "button", + { + class: "ghost chat-attachment-remove", + type: "button", + "aria-label": `Remove ${display}`, + title: `Remove ${display}`, + onclick: () => removeChatAttachment(sessionId, attachment.id), + }, + "✕", + ), + ); + return chip; +} + +/** The chip's square preview: the decoded thumbnail for an image, else a glyph. */ +function renderAttachmentThumb(attachment, display) { + if (attachment?.thumbUrl) { + return h("img", { + class: "chat-attachment-thumb", + src: attachment.thumbUrl, + alt: display, + "aria-hidden": "true", + }); + } + const image = String(attachment?.mime ?? "").startsWith("image/"); + return h("span", { + class: "chat-attachment-glyph", + "aria-hidden": "true", + text: image ? "🖼" : "📄", + }); +} + +/** 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, + ); +} + +/** + * (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; + const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true; + if (state.view === "chat" && thread?.running && !awaiting) { + 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" })); + } + } +} + + return { + renderChatList, + renderChatCreate, + renderChatConversation, + afterChatRender, + updateChatIndicator, + refreshChatClock, + stopChatClock, + captureChatPosition, + loadChatSessions, + loadChatDirectories, + startNewChat, + openChatSession, + subscribeChatSession, + clearChatSubscriptions, + settleChatThreads, + resyncOpenChat, + onChatEvent, + onChatPermission, + onChatFrame, + renderToolCallRow, + renderToolDiff, + renderMarkdown, + dismissChatClose, + dismissChatRename, + }; +} diff --git a/web/src/views/dialogs.js b/web/src/views/dialogs.js new file mode 100644 index 00000000..51cea6b1 --- /dev/null +++ b/web/src/views/dialogs.js @@ -0,0 +1,687 @@ +// Full-screen and modal dialogs owned by the run detail and chat surfaces: +// the rendered/raw diff viewer, the artifact viewer, the human-decision sheet, +// the shared cancel/retry confirm and the shared Action-failed report. + +import { h, canCopyLink, canShare, copyArtifactLink, copyText, shareArtifact } from "../dom.js"; +import { changeKindTone, describeError } from "../format.js"; +import { + BINARY_DIFF_MESSAGE, + NO_LINE_CHANGES_MESSAGE, + TRUNCATED_PATCH_NOTE, + changeKindTitle, + changePositionLabel, + changeStat, + diffLineClass, + diffLineSymbol, + entryHasPatch, + gutterText, + gutterWidth, + parseUnifiedPatch, + patchUnavailableReason, +} from "../changes.js"; +import { + ArtifactKind, + artifactKind, + artifactViewerPositionLabel, + pagedIndex, + resolvedArtifactUrl, +} from "../artifacts.js"; +import { + ACTION_FAILED_OK, + ACTION_FAILED_TITLE, + CANCEL_CONFIRM, + CANCEL_DIALOG_MESSAGE, + DECISION_CANCEL, + DECISION_CONFIRM, + DECISION_SENDING, + DISMISS_KEEP, + DecisionDraft, + FEEDBACK_LABEL, + RESTART_CONFIRM, + RESTART_DIALOG_MESSAGE, + RETRY_CONFIRM, + RETRY_DIALOG_MESSAGE, + cancelDialogTitle, + decisionSheetMeta, + decisionSheetTitle, + optionTargetText, + restartDialogTitle, + retryDialogTitle, + retryRequestKey, +} from "../actions.js"; + +export function createDialogsView(rt) { + const { state, repo } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const selectRun = (...args) => rt.selectRun(...args); + +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; +} + +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(); +} + +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); +} + + return { + closeChangeViewer, + openChangeViewer, + openDecisionSheet, + closeDecisionSheet, + renderDecisionSheet, + confirmDecision, + openConfirm, + dismissConfirm, + renderConfirmDialog, + acceptConfirm, + renderActionFailedDialog, + dismissActionError, + closeArtifactViewer, + openArtifactViewer, + }; +} diff --git a/web/src/views/pipelines.js b/web/src/views/pipelines.js new file mode 100644 index 00000000..aa6618cb --- /dev/null +++ b/web/src/views/pipelines.js @@ -0,0 +1,402 @@ +// The Pipelines destination: the filterable/sortable list, the pipeline detail +// (Summary / Graph / Source) and the list refresh used after a template create. +// The pure models live in pipelines.js and graph.js; this module owns the DOM. + +import { h } from "../dom.js"; +import { describeError } from "../format.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 { PIPELINE_GRAPH_EMPTY, mount as mountGraph } from "../graph.js"; + +export function createPipelinesView(rt) { + const { state, repo } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const selectPipeline = (...args) => rt.selectPipeline(...args); + const pushRoute = (...args) => rt.pushRoute(...args); + + +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, + selectedKey: state.pipelineGraphSelection, + onSelectionChange: (key) => { + // The graph has already opened or closed its own definition pane; record + // the destination in the URL without rebuilding the graph. + state.pipelineGraphSelection = key; + const id = state.selectedPipelineId; + if (!id) return; + const version = state.pipelineRequestedVersion ?? 0; + pushRoute( + key + ? { kind: "pipelineStage", id, version, stageKey: key } + : { kind: "pipeline", id, version }, + ); + }, + 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; +} + +async function refreshPipelines() { + try { + state.pipelines = await repo.listPipelines(); + state.pipelinesLoaded = true; + } catch (error) { + state.error = describeError(error); + } +} + +function pipelineSortLabel(key) { + return (PIPELINE_SORTS.find((option) => option.key === key) ?? PIPELINE_SORTS[0]).label; +} + +function clearPipelineFilters() { + state.pipelineFilters = { ...EMPTY_PIPELINE_FILTERS }; + renderContent(); +} + + return { + renderPipelineList, + renderPipelineDetail, + fillPipelineRows, + clearPipelineFilters, + refreshPipelines, + }; +} diff --git a/web/src/views/runDetail.js b/web/src/views/runDetail.js new file mode 100644 index 00000000..c6bdfcf0 --- /dev/null +++ b/web/src/views/runDetail.js @@ -0,0 +1,954 @@ +// The run detail: Summary / Graph / Input / Output / Timeline, the per-visit +// stage pane, the decision card and run actions, the Summary title/rename row and +// the run's artifact gallery. Pure models live in runDetail.js, changes.js, +// artifacts.js and actions.js; dialogs are delegated to dialogs.js. + +import { h, kvMono, renderLiveBadge, canCopyLink, canShare, copyArtifactLink, shareArtifact } from "../dom.js"; +import { isExecuting, changeKindTone, describeError } from "../format.js"; +import { liveBadgeState } from "../connection.js"; +import { resolveArtifactUrl } from "../serverUrl.js"; +import { runStateOf } from "../runs.js"; +import { PIPELINE_GRAPH_EMPTY, RUN_GRAPH_MISSING, RUN_GRAPH_NOTE, mount as mountGraph } from "../graph.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 { + ArtifactKind, + artifactCaptureNotes, + artifactGroups, + artifactKind, + artifactKindLabel, + artifactsHeader, + artifactsSummary, + artifactViewerPositionLabel, + displayVisit, + humanBytes, + pagedArtifacts, + presentedArtifacts, + resolvedArtifactUrl, + sessionExportArtifact, + viewerIndexByUrl, +} from "../artifacts.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 { + DECISION_ACTION, + DECISION_CARD_TITLE, + RENAME_ACTION, + RENAME_CANCEL, + RENAME_FIELD_LABEL, + RENAME_SAVE, + canCancel, + canRetry, + decisionCardMeta, + pendingDecision, +} from "../actions.js"; + +/** 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."; + +export function createRunDetailView(rt) { + const { state, repo } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const selectRun = (...args) => rt.selectRun(...args); + const pushRoute = (...args) => rt.pushRoute(...args); + const openChangeViewer = (...args) => rt.views.dialogs.openChangeViewer(...args); + const openDecisionSheet = (...args) => rt.views.dialogs.openDecisionSheet(...args); + const openConfirm = (...args) => rt.views.dialogs.openConfirm(...args); + const renderDecisionSheet = (...args) => rt.views.dialogs.renderDecisionSheet(...args); + const renderConfirmDialog = (...args) => rt.views.dialogs.renderConfirmDialog(...args); + const renderActionFailedDialog = (...args) => rt.views.dialogs.renderActionFailedDialog(...args); + const openArtifactViewer = (...args) => rt.views.dialogs.openArtifactViewer(...args); + +/** + * 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(now = Date.now()) { + 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, now)); + } + 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, now) { + const wrap = h("div", { class: "run-tab-body" }); + wrap.append(renderRunTitleRow(d)); + const status = runStateOf(d.status); + const chips = h("div", { class: "run-chip-row" }); + chips.append(h("span", { class: `chip chip-${status}`, text: d.status || status })); + if (String(d.outcome ?? "").trim()) chips.append(h("span", { class: "muted", text: `outcome ${d.outcome}` })); + if (d.executing) chips.append(h("span", { class: "muted", text: "executing" })); + chips.append(renderLiveBadge(liveBadgeState(state.runStream))); + wrap.append(chips); + wrap.append(h("div", { class: "run-identity muted", text: runIdentityLine(d) })); + + const rows = h("div", { class: "kv" }); + for (const row of summaryRows(d, now)) { + 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; +} + +/** + * 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; +} + + +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, { updateRoute = true } = {}) { + state.runStagePane = { stageKey, visitIndex }; + state.runStageSections = new Set(); + if (updateRoute && state.selectedRunId) { + pushRoute({ + kind: "runStage", + id: state.selectedRunId, + stageKey, + visit: Number.isSafeInteger(visitIndex) && visitIndex >= 0 ? visitIndex : null, + }); + } + renderContent(); + document.querySelector(".stage-pane-back")?.focus(); +} + +/** Close the stage pane, returning focus to the timeline row that opened it. */ +function closeStagePane({ updateRoute = true } = {}) { + const closing = state.runStagePane; + if (!closing) return; + state.runStagePane = null; + state.runStageSections = new Set(); + if (updateRoute && state.selectedRunId) { + pushRoute({ kind: "run", id: state.selectedRunId }); + } + 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 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); +} + +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; +} + +/** + * 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; +} + + return { + renderRunDetail, + renderRunGraphTab, + renderRunSummaryTab, + renderStagePane, + openStagePane, + closeStagePane, + renderArtifactGallery, + renderVisitArtifacts, + renderSessionExport, + latestVisitIndex, + }; +} diff --git a/web/src/views/runs.js b/web/src/views/runs.js new file mode 100644 index 00000000..0ba5af05 --- /dev/null +++ b/web/src/views/runs.js @@ -0,0 +1,338 @@ +// The Runs history view: day groups, usage metrics, rows and the filter/sort +// menus. The pure filtering, sorting and formatting live in runs.js; this module +// owns the DOM and the page's run-list state. + +import { h, renderLiveBadge } from "../dom.js"; +import { + RUN_STATES, + RUN_TIME_RANGES, + RUN_SORTS, + runStateOf, + runIdentity, + versionLabel, + progressText, + metaText, + formatDuration, + localDayKey, + filterRuns, + groupRunsByDay, + runComparator, + pipelineFilterOptions, + runListEntries, + runFiltersActiveCount, + DEFAULT_RUN_SORT, + defaultRunFilters, +} from "../runs.js"; +import { liveBadgeState } from "../connection.js"; + +export function createRunsView(rt) { + const { state } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const selectRun = (...args) => rt.selectRun(...args); + + +function renderRunList(now = Date.now()) { + 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, now)); + 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, now) { + 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, now), + }), + ); + if (String(run.diagnostic ?? "").trim()) { + row.append( + h("span", { + class: `run-row-diag${status === "failed" ? " error" : ""}`, + text: run.diagnostic, + }), + ); + } + return row; +} + +function versionChip(version) { + return h("span", { class: "version-chip", text: versionLabel(version) }); +} + +function renderRunToolbar() { + const activeCount = runFiltersActiveCount(state.runFilters); + const filterLabel = activeCount > 0 ? `Filter (${activeCount})` : "Filter"; + const sortLabel = (RUN_SORTS.find((s) => s.value === state.runSort) ?? RUN_SORTS[0]).label; + + const toolbar = h("div", { class: "run-toolbar" }); + toolbar.append( + h( + "div", + { class: "menu-anchor" }, + h("button", { + id: "runFilterBtn", + class: `ghost filter-btn${activeCount > 0 ? " active" : ""}`, + title: activeCount > 0 ? `${activeCount} active filter${activeCount === 1 ? "" : "s"}` : "Filter runs", + text: filterLabel, + "data-active-count": String(activeCount), + onclick: () => toggleMenu("filter"), + }), + state.openMenu === "filter" ? renderFilterMenu() : null, + ), + h( + "div", + { class: "menu-anchor" }, + h("button", { + id: "runSortBtn", + class: "ghost sort-btn", + title: "Sort runs", + text: `Sort: ${sortLabel}`, + onclick: () => toggleMenu("sort"), + }), + state.openMenu === "sort" ? renderSortMenu() : null, + ), + h("span", { class: "spacer" }), + renderLiveBadge(liveBadgeState(state.runStream)), + ); + return toolbar; +} + +/** One small live-stream badge (LiveBadge.kt): a dot plus the honest word. */ + +function 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(); +} + + return { + renderRunList, + renderRunToolbar, + renderRunRow, + renderUsage, + renderEmptyState, + toggleMenu, + closeMenu, + clearRunFilters, + }; +} diff --git a/web/src/views/search.js b/web/src/views/search.js new file mode 100644 index 00000000..d90791a8 --- /dev/null +++ b/web/src/views/search.js @@ -0,0 +1,374 @@ +// Omni-search: the top-bar panel, kind/sort controls, rows and result routing. +// Debounce/staleness/ordering/empty-state decisions are pure in search.js; this +// module owns the DOM and the route hand-off. + +import { h } from "../dom.js"; +import { describeError } from "../format.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"; + +export function createSearchView(rt) { + const { state, repo, searchHost } = rt; + let searchTimer = null; + let searchEdit = null; + const renderHeader = (...args) => rt.renderHeader(...args); + const renderContent = (...args) => rt.renderContent(...args); + const selectPipeline = (...args) => rt.selectPipeline(...args); + const selectRun = (...args) => rt.selectRun(...args); + const openStagePane = (...args) => rt.views.runDetail.openStagePane(...args); + +// 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); + } +} + + return { + openSearch, + closeSearch, + renderSearch, + onSearchInput, + sendSearchNow, + }; +} diff --git a/web/src/views/settings.js b/web/src/views/settings.js new file mode 100644 index 00000000..405ecc7d --- /dev/null +++ b/web/src/views/settings.js @@ -0,0 +1,404 @@ +// The Settings destination: Connection, Workspace, Notifications and the +// Templates card. Every string and validation rule comes from settings.js / +// notify.js; this module owns the DOM, the local drafts and the shared client's +// connection controls. + +import { h } from "../dom.js"; +import { + SERVER_URL_HELPER, + SERVER_URL_PLACEHOLDER, + TEMPLATES_CARD_LABEL, + TEMPLATES_CARD_SECONDARY, + TRUST_BODY, + TRUST_TITLE, + WORKSPACE_HELPER, + WORKSPACE_PLACEHOLDER, + canSaveWorkspace, + connectionActionKind, + connectionActions, + connectionCard, + savedWorkspaceLine, + workspaceErrorText, + writeWorkspace, +} from "../settings.js"; +import { + NOTIFICATION_RATIONALE, + notificationEnvironment, + notificationPermissionState, +} from "../notify.js"; +import { bannerState } from "../connection.js"; + +export function createSettingsView(rt) { + const { state, repo, setServerUrlDraft, endpointConfigured } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const pushRoute = (...args) => rt.pushRoute(...args); + const applyRoute = (...args) => rt.applyRoute(...args); + const openConfiguredEndpoint = (...args) => rt.openConfiguredEndpoint(...args); + const onReconnectClicked = (...args) => rt.onReconnectClicked(...args); + const persistNotifyAsked = (...args) => rt.views.attention.persistNotifyAsked(...args); + +/** + * The Settings destination: the app's three sections (Connection, Workspace, + * Templates) in one pane. It is wiring only — every string, the workspace + * validation and the connection card's lines come from the pure `settings.js`, + * and the connection controls drive the page's existing single client through + * the same handlers the header uses (no second socket or path). Every + * server-derived string is set with textContent. + */ +function renderSettingsView() { + const pane = h("div", { class: "settings" }); + pane.append( + renderSettingsConnection(), + renderSettingsWorkspace(), + renderSettingsNotifications(), + renderSettingsTemplates(), + ); + return pane; +} + +function renderSettingsConnection() { + const section = h("section", { class: "settings-section" }); + section.append(h("h2", { class: "settings-title", text: "Connection" })); + + section.append( + h( + "label", + { class: "settings-field", for: "settingsServerUrl" }, + h("span", { class: "settings-field-label", text: "Server URL" }), + h("input", { + id: "settingsServerUrl", + type: "text", + placeholder: SERVER_URL_PLACEHOLDER, + value: state.url, + spellcheck: "false", + autocomplete: "off", + "aria-describedby": "settingsUrlHelper", + "aria-invalid": state.urlError ? "true" : null, + oninput: (event) => { + setServerUrlDraft(event.target.value, "settingsServerUrl"); + }, + }), + ), + ); + // Android's `urlError ?: helper` supporting text. The error clears on the next + // edit (AppViewModel.updateServerUrlDraft) and is announced as the field's own + // invalid state rather than as a page-level banner. + section.append( + h( + "p", + { + id: "settingsUrlHelper", + class: `settings-helper${state.urlError ? " settings-helper-error" : ""}`, + role: state.urlError ? "alert" : null, + }, + serverUrlSupportingText(), + ), + ); + + const actions = connectionActions(state.connection); + section.append( + h( + "div", + { class: "settings-actions" }, + h("button", { + id: "settingsPrimary", + class: "primary", + type: "button", + text: actions.primary, + onclick: () => runConnectionAction(actions.primary), + }), + h("button", { + id: "settingsSecondary", + class: "ghost", + type: "button", + text: actions.secondary, + onclick: () => runConnectionAction(actions.secondary), + }), + ), + ); + + const tone = bannerState(state.connection, { hasEndpoint: endpointConfigured() }).tone; + const card = h("div", { class: `settings-status status-${tone}` }); + const lines = connectionCard(state.connection, { + version: state.serverBuild?.version, + commit: state.serverBuild?.commit, + serverTime: state.serverTime, + }); + lines.forEach((line, index) => { + // Android's Connecting card leads its one line with a CircularProgressIndicator; + // the shared spinner is drawn only for that state, inline with the text, so the + // other three stay plain text. + if (index === 0 && state.connection.kind === "connecting") { + const row = h("div", { class: "settings-status-head" }); + row.append(h("span", { class: "spinner settings-status-spinner", "aria-hidden": "true" })); + row.append(h("p", { class: "settings-status-line", text: line })); + card.append(row); + return; + } + card.append(h("p", { class: "settings-status-line", text: line })); + }); + section.append(card, renderTrustWarning()); + return section; +} + +/** + * The Notifications section (L5). The Android rationale is shown verbatim; the + * status line is the pure permission view for this page's real browser facts. + * Only the explicit control asks for permission, never page load. When the API + * is unavailable, the page is insecure or permission is denied, the wording says + * plainly that the in-app Needs you surface is the only channel — no fake + * notification is ever drawn. + */ +function renderSettingsNotifications() { + const view = notificationPermissionState({ + ...notificationEnvironment(), + asked: state.notifyAsked, + }); + const section = h("section", { class: "settings-section", id: "settingsNotifications" }); + section.append(h("h2", { class: "settings-title", text: "Notifications" })); + section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE })); + section.append( + h("p", { + id: "settingsNotificationState", + class: `settings-notify-state settings-notify-${view.state}`, + role: "status", + text: view.body, + }), + ); + if (view.canRequest) { + section.append( + h( + "div", + { class: "settings-actions" }, + h("button", { + id: "settingsEnableNotifications", + class: "primary", + type: "button", + text: view.actionLabel, + onclick: requestNotifications, + }), + ), + ); + } + return section; +} + +/** + * Ask for notification permission from the operator's explicit click. The asked + * flag is persisted first and the page re-renders from the browser's real answer; + * a refused/dismissed prompt leaves the honest default/denied wording in place. + */ +function requestNotifications() { + persistNotifyAsked(true); + const ctor = globalThis.Notification; + if (typeof ctor !== "function" || !globalThis.isSecureContext) { + renderContent(); + return; + } + try { + const result = ctor.requestPermission(); + if (result && typeof result.then === "function") { + result.then( + () => renderContent(), + () => renderContent(), + ); + return; + } + } catch { + // A browser that refuses the request keeps the honest fallback wording. + } + renderContent(); +} + +/** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */ +function renderTrustWarning() { + return h( + "div", + { class: "settings-warning" }, + h("p", { class: "settings-warning-title", text: TRUST_TITLE }), + h("p", { class: "settings-warning-body", text: TRUST_BODY }), + ); +} + +/** + * Route a Settings connection control through the page's existing single client, + * mirroring AppViewModel: Disconnect closes the shared socket, Connect is + * connect-only (validate + persist + open — never the header's toggle), and + * Reconnect re-opens the same validated endpoint now. Nothing here opens a second + * connection. + */ +function runConnectionAction(label) { + const kind = connectionActionKind(label); + if (kind === "disconnect") { + repo.disconnect(); + return; + } + if (kind === "reconnect") { + onReconnectClicked(); + return; + } + // The `Connect` label must never fall through to the header's toggle: while + // connected that would tear the live socket down (Android's connect() is + // connect-only). + openConfiguredEndpoint(); +} + +/** Android's `urlError ?: helper` supporting text for the Server URL field. */ +function serverUrlSupportingText() { + return state.urlError || SERVER_URL_HELPER; +} + +/** + * Update the Server URL field's own error state in place (supporting text, + * aria-invalid and the error tint) so an invalid Connect never needs a full + * re-render and the field being typed in is never rebuilt. + */ +function refreshServerUrlError() { + const field = document.getElementById("settingsServerUrl"); + const helper = document.getElementById("settingsUrlHelper"); + if (field) { + if (state.urlError) field.setAttribute("aria-invalid", "true"); + else field.removeAttribute("aria-invalid"); + } + if (helper) { + helper.textContent = serverUrlSupportingText(); + helper.classList.toggle("settings-helper-error", Boolean(state.urlError)); + if (state.urlError) helper.setAttribute("role", "alert"); + else helper.removeAttribute("role"); + } +} + +function renderSettingsWorkspace() { + const section = h("section", { class: "settings-section" }); + section.append(h("h2", { class: "settings-title", text: "Workspace" })); + section.append( + h( + "label", + { class: "settings-field", for: "settingsWorkspace" }, + h("span", { class: "settings-field-label", text: "Workspace path (on the server)" }), + h("input", { + id: "settingsWorkspace", + type: "text", + placeholder: WORKSPACE_PLACEHOLDER, + value: state.workspaceDraft, + spellcheck: "false", + autocomplete: "off", + "aria-describedby": "workspaceHelper", + "aria-invalid": workspaceErrorText(state.workspaceDraft) ? "true" : null, + oninput: (event) => { + state.workspaceDraft = event.target.value; + refreshWorkspaceControls(); + }, + }), + ), + ); + section.append( + h( + "p", + { + id: "workspaceHelper", + class: `settings-helper${workspaceErrorText(state.workspaceDraft) ? " settings-helper-error" : ""}`, + }, + workspaceSupportingText(), + ), + ); + section.append( + h("button", { + id: "saveWorkspace", + class: "primary settings-save", + type: "button", + text: "Save workspace", + disabled: !canSaveWorkspace(state.workspaceDraft), + onclick: saveWorkspace, + }), + ); + section.append(h("p", { id: "savedWorkspace", class: "settings-saved", text: savedWorkspaceLine(state.workspace) })); + return section; +} + +/** Android's `workspaceError ?: helper` supporting text for the workspace field. */ +function workspaceSupportingText() { + return workspaceErrorText(state.workspaceDraft) || WORKSPACE_HELPER; +} + +/** + * Update the workspace field's dependent controls in place (the helper/error line + * and the Save button's enabled state) so typing never re-renders — and so never + * blurs — the field being typed in. + */ +function refreshWorkspaceControls() { + const helper = document.getElementById("workspaceHelper"); + const invalid = Boolean(workspaceErrorText(state.workspaceDraft)); + if (helper) { + helper.textContent = workspaceSupportingText(); + helper.classList.toggle("settings-helper-error", invalid); + } + const field = document.getElementById("settingsWorkspace"); + if (field) { + if (invalid) field.setAttribute("aria-invalid", "true"); + else field.removeAttribute("aria-invalid"); + } + const save = document.getElementById("saveWorkspace"); + if (save) save.disabled = !canSaveWorkspace(state.workspaceDraft); +} + +/** Persist the workspace (trimmed) and update the `Saved workspace:` line. */ +function saveWorkspace() { + if (!canSaveWorkspace(state.workspaceDraft)) return; + state.workspace = writeWorkspace(localStorage, state.workspaceDraft); + state.workspaceDraft = state.workspace; + // Show the trimmed value that was actually stored, in the field as well as the + // saved line (both updated in place so the keyboard focus is not disturbed). + const field = document.getElementById("settingsWorkspace"); + if (field) field.value = state.workspace; + const saved = document.getElementById("savedWorkspace"); + if (saved) saved.textContent = savedWorkspaceLine(state.workspace); +} + +function openTemplatesFromSettings() { + const route = { kind: "templates" }; + pushRoute(route); + applyRoute(route); +} + +function renderSettingsTemplates() { + const section = h("section", { class: "settings-section" }); + section.append(h("h2", { class: "settings-title", text: "Templates" })); + const card = h( + "button", + { + id: "browseTemplates", + class: "card settings-card", + type: "button", + onclick: openTemplatesFromSettings, + }, + // SettingsScreen.kt's row idiom: a leading glyph, the label and secondary + // line, then a forward chevron. + h("span", { class: "settings-card-glyph", "aria-hidden": "true", text: "\u25a4" }), + h( + "span", + { class: "settings-card-text" }, + h("span", { class: "card-name", text: TEMPLATES_CARD_LABEL }), + h("span", { class: "card-desc", text: TEMPLATES_CARD_SECONDARY }), + ), + h("span", { class: "settings-card-chevron", "aria-hidden": "true", text: "\u203a" }), + ); + section.append(card); + return section; +} + + return { + renderSettingsView, + renderSettingsConnection, + requestNotifications, + runConnectionAction, + serverUrlSupportingText, + refreshServerUrlError, + renderSettingsWorkspace, + workspaceSupportingText, + refreshWorkspaceControls, + saveWorkspace, + openTemplatesFromSettings, + renderSettingsTemplates, + }; +} diff --git a/web/src/views/templates.js b/web/src/views/templates.js new file mode 100644 index 00000000..80c32380 --- /dev/null +++ b/web/src/views/templates.js @@ -0,0 +1,405 @@ +// The Templates gallery and detail, including the create-from-template dialog +// and its validate-then-submit flow. Pure wording/model helpers live in +// templates.js; this module owns the DOM and the page's template state. + +import { h, kvMono } from "../dom.js"; +import { describeError } from "../format.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"; + +export function createTemplatesView(rt) { + const { state, repo } = rt; + const renderContent = (...args) => rt.renderContent(...args); + const pushRoute = (...args) => rt.pushRoute(...args); + const setError = (...args) => rt.setError(...args); + const refreshPipelines = (...args) => rt.views.pipelines.refreshPipelines(...args); + +/** + * Reset the template detail/create state that belongs to a selection. Shared by + * selecting a template and opening the gallery from Settings, so the two lists of + * fields can never drift. + */ +function resetTemplateCreateState() { + state.templateTab = "summary"; + // A different template reseeds the create dialog, so a name typed for one + // template can never be submitted against another. + state.templateCreateOpen = false; + state.templateCreateName = ""; + state.templateCreateSending = false; + state.templateCreateError = ""; + state.templateCreateCreated = null; +} + +/** Clear the selection and everything that belongs to it. */ +function resetTemplateSelection() { + state.selectedTemplateKey = null; + resetTemplateCreateState(); +} + +/** 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(); +} + +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; +} + +/** + * 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) { + if (key) pushRoute({ kind: "template", key }); + else pushRoute({ kind: "templates" }); + state.selectedTemplateKey = key || null; + resetTemplateCreateState(); + renderContent(); +} + + return { + resetTemplateCreateState, + resetTemplateSelection, + renderTemplateGallery, + renderTemplateDetail, + loadTemplates, + selectTemplate, + }; +}