diff --git a/web/PARITY.md b/web/PARITY.md index 2a367dd9..28f08fbd 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -41,10 +41,10 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | R8 | Artifacts gallery + full-screen viewer (images inline, others download/open) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/04-run-430-artifacts.png`, `captures/05-artifact-viewer.png`) | | R9 | Session export link (read-only `session.html`) | `GET /artifacts/…` | done (captured 2026-10-19: `captures/06-session-export-link.png`) | | R10 | Live run updates: subscribe/unsubscribe + event fold | `subscribe`, `unsubscribe`, `run_event` | todo | -| R11 | Human decision sheet: prompt, options, feedback | `decide_run` | todo | -| R12 | Cancel run | `cancel_run` | todo | -| R13 | Retry failed stage (resume) / restart from start | `retry_run` | todo | -| R14 | Rename a run | `set_run_title` | todo | +| R11 | Human decision sheet: prompt, options, feedback | `decide_run` | partial — the pure model (`src/actions.js`: `pendingDecision`, `lastWaitingStep`, `waitingPrompt`/`waitingOptions`, `humanOptions`, `decisionTargetLabel`, `DecisionDraft`) and the card + sheet are implemented with the Android copy verbatim: card title `Waiting for your decision`, meta `{stage} · run {id} · {runLabel}`, action `Decide`; sheet title `Decide {stage}`, meta `run {id} · {runLabel}`, the recorded instructions verbatim when non-blank, one selectable row per option in author order showing the option and `→ {target}` only when the declared edge resolves, the `Feedback (optional)` field, and `Cancel` / `Confirm decision` (reading `Sending…` while in flight). Selecting a row sends nothing and Confirm is disabled until a non-blank option is chosen; a refusal keeps the sheet open with the server's exact reason and re-reads the run. The request shape is unit-tested (`decide_run` = `{type, run_id, option, stage?, feedback?}`, stage/feedback omitted when blank, feedback trimmed). **No browser capture yet**: the live server had no `waiting` run when `ui-smoke.mjs` ran (only executing/failed/finished runs), so this row stays `partial`; `test/ui-smoke.mjs` now captures the card, the sheet and the selected state automatically (`captures/41-run--decision-card.png`, `captures/42-run--decision-sheet.png`, `captures/43-run--decision-selected.png`) the moment a waiting run exists | +| R12 | Cancel run | `cancel_run` | done — `src/actions.js` `canCancel` offers a `Cancel run` action only while the run is `executing`; the confirm dialog is the Android copy verbatim (title `Cancel run {id}?`, `This asks the server to stop the active run.`, confirm `Cancel run`, dismiss `Keep`), and the request is exactly `{type:'cancel_run',run_id}` followed by a silent `get_run` refresh (unit-tested in `test/repository.test.mjs`). Captured `captures/40-run-459-cancel-confirm.png` on the executing run present at capture time. **Shown, not executed**: the only candidate was another live pipeline's executing run, so the dialog was shown and dismissed with `Keep` — no `cancel_run` was sent (a real cancel is only safe against a run started in a scratch workspace, which this stage did not do) | +| R13 | Retry failed stage (resume) / restart from start | `retry_run` | done — `canRetry` is true only for a loaded, non-executing, `failed` run; the Retry confirm is the Android copy verbatim (title `Retry run {id}?`, `Only failed runs can be retried. The server starts a new run from the same input.`, confirm `Retry`, dismiss `Keep`) and the default send carries only `run_id` + a fresh `request_key` (**no** `retry_mode`, so the server's `resume` default applies exactly like the Android client's mode-less call; unit-tested). Captured `captures/35-run-440-run-actions.png` (failed run 440 offers Retry and no Cancel) and `captures/36-run-440-retry-confirm.png`. **Divergence from the Android UI, stated here**: Android exposes resume only while the protocol has both modes, so the browser adds a clearly-labelled secondary `Restart from start` confirm that states it `replays the whole pipeline from the start instead of resuming the failed stage` and sends `retry_mode:"restart"` (`captures/37-run-440-restart-confirm.png`). Both dialogs were shown and dismissed with `Keep`; no run was started | +| R14 | Rename a run | `set_run_title` | done — an inline field on the Summary title row (pre-filled with the current title, `Rename` / `Save` / `Cancel`) sending exactly `{type:'set_run_title',run_id,title}` and then refreshing the run and the runs-list row (unit-tested). Captured `captures/38-run-440-rename-field.png`. The one shared `Action failed` dialog was exercised by a real refused rename: `captures/39-run-440-action-failed.png` shows the live server's exact reason `a title with usable text is required` (a blank title mutates nothing). **Divergence from the Android UI, stated here**: Android does not surface `set_run_title` at all (its README records the deliberate omission), so this control is browser-only | | R15 | Attention / "Needs you" surface: counts, open, individual dismiss, clear all | derived from `list_runs` + run events | done — the pure `src/attention.js` model mirrors `ui/Attention.kt` and feeds a bell action in the top bar (badge only when non-empty; accessible name `Notifications` / `Notifications, {n} needing attention`) and a bottom sheet titled `Needs you` in `src/app.js`. Only a `waiting` run (kind Decision, rank 0) and a `failed` run (kind Failed, rank 1) qualify; order is kind rank, then recency descending (`finished_at` else `created_at`), then run id descending. Rows carry a status icon, the trimmed-title-else-pipeline label, the exact `{pipeline} · {detail}` line (`Waiting for your decision`, or the trimmed diagnostic else `Run failed`) and a trailing `Dismiss`; tapping a row opens the run, dismissing a Failed row first while a Decision row is left for its answer. Clear all acts only on the snapshot taken when the sheet opened; dismissals persist as one JSON array of `{runId}:{kind}` identities under `pipelines.web.attention.v1` with no expiry (blank/unreadable storage decodes to empty and never throws). Entries are derived from `list_runs` here; R10 will feed the same pure model the pushed `run_event` summaries, with no wording or ordering change. Captured 2026-10-19: `captures/35-attention-bell.png` (bell + badge on the Runs list), `captures/36-attention-sheet.png` (the open sheet), `captures/37-attention-dismissed.png` (one entry individually dismissed, badge 171→170), `captures/38-attention-cleared.png` (Clear all: the empty copy, no Clear all, badge gone). No run was parked in `waiting` on the live server at capture time, so the sheet is exercised with real failed runs and the decision-open path is unit-tested | Two wording decisions in R3's stage pane, recorded here as the app-authoritative @@ -62,11 +62,28 @@ empty-capture variants carry the `Changes · ` prefix — while the expanded bod own summary line repeats the count and stat. The header is rendered verbatim, not re-composed. +R11–R14 share one `Action failed` dialog (title `Action failed`, the server's own +message, a single `OK`), matching `RunDetailScreen.kt`; every server string is set +with `textContent`, never `innerHTML`. Where a live action was unsafe this stage +says so rather than mutating shared state: the R12 cancel and the R13 retry/restart +sends were shown and dismissed with `Keep` (never executed), and R11 has no live +capture because the server had no waiting run. The request shapes for all four are +unit-tested in `test/repository.test.mjs` and the model in `test/actions.test.mjs`; +`test/ui-smoke.mjs` captures the rendered dialogs, the rename field, the refused +rename's exact server reason and — when a waiting run exists — the decision +card/sheet. + ## Search | # | Feature | Protocol | Status | | --- | --- | --- | --- | -| S1 | Omni-search across pipelines, versions, runs, steps, fields, artifacts | `search` | todo | -| S2 | Result routing (open the pipeline, run, stage, artifact) | — | todo | +| S1 | Omni-search across pipelines, versions, runs, steps, fields, artifacts | `search` | done — the top bar's `Search` control opens a full-width panel under it (field autofocused, placeholder `Search pipelines, runs and artifacts`, a `Close search` control; opening and closing leave the current view, selection and loaded data untouched, and Escape closes the field). One flat result list with no kind grouping, over a controls row: the kind select (`All kinds`/`Pipelines`/`Runs`/`Steps`/`Fields`/`Artifacts`/`Versions`), the sort select (`Relevance`/`Newest first`/`Name`), the one-line `{Kind} · {Sort}` summary and a `Clear filter` reset. The request is exactly `{type:"search",search:{query,kind,limit:0}}` — the server's own default cap, never above `SearchMaxLimit` 200 — debounced 250 ms after the last keystroke with Enter sending at once; a blank query clears locally with no request; the previous results stay visible (a thin progress bar above them) while a newer query loads and a stale reply is dropped by token; the first load shows the spinner and `Searching…`; an error takes precedence over the results. Failure copy is `AppViewModel`'s: a rejection naming an unknown command, or an older server's reply without `search_results`, reads `This server does not support search. Update the Pipelines server, then try again.` and any other failure carries the server's own text. Row text and blank fallbacks mirror `OmniSearchResults.searchRow` (a field hit's snippet emphasises the first case-insensitive query occurrence, never via `innerHTML`) and the empty state keeps Android's `No matches for "{query}".` / `No {kind} match "{query}".`. Captured 2026-10-19: `captures/01-search-results.png` (flat mixed list for the query `plan`, the controls row and summary `All kinds · Relevance`), `captures/02-search-kind-filter.png` (the `Pipelines` filter narrowing the list and the summary to `Pipelines · Relevance`) | +| S2 | Result routing (open the pipeline, run, stage, artifact) | — | done — every selection closes and clears the search first, then routes through the page's existing navigation: a pipeline/version hit opens the pipeline detail at the result version (version 0 = latest); a run hit opens the run detail; a text hit opens the run-detail tab holding the match, resolved from the hit's `matched_field` (`input` → Input, `output` → Output, else Summary — the browser item's deliberate rule, not the recorded field name); a step or artifact hit opens the recorded visit's stage pane (the zero-based visit index within the stage, falling back to the plain run detail when the visit cannot be located); an unknown/absent payload is read-only and never navigates. Captured 2026-10-19, each with the routed destination asserted in the smoke run: `captures/03-search-route-pipeline.png` (`pipeline:24:v5` → `Plan and land` detail), `captures/04-search-route-run.png` (`run:457` → Runs detail), `captures/05-search-route-field.png` (`run:458:3`, `matched_field input` → the Input tab active), `captures/06-search-route-step.png` (`run:457:1` → the `planner` visit stage pane), `captures/07-search-route-artifact.png` (`/artifacts/355/2/…` → the `implementer` visit pane), `captures/08-search-route-version.png` (`pipeline:22:v6` → the `Server` detail) | + +Two wording decisions in Search, recorded here as the app-authoritative choices: +the controls summary is exactly `{Kind} · {Sort}` (the browser item's wording, with +none of the Android panel's ` (in hand)` note), and the kind-filtered empty state +keeps Android's invariant `No {kind} match "{query}".` — the same sentence shape +the pipeline list already carries — rather than a pluralised verb. ## Chat | # | Feature | Protocol | Status | diff --git a/web/src/actions.js b/web/src/actions.js new file mode 100644 index 00000000..302a4a3e --- /dev/null +++ b/web/src/actions.js @@ -0,0 +1,245 @@ +// Pure, DOM-free logic for the run-level operator actions the browser client +// offers on a run detail: the pending human decision (R11), cancel (R12), retry +// / restart (R13) and rename (R14). Ported from the Android client so the +// browser asks for and shows exactly the same things: +// ui/Decision.kt PendingDecision, DecisionOption, +// pendingDecision, decisionTargetLabel, +// DecisionDraft +// data/protocol/HumanDecision.kt lastWaitingStep, waitingPrompt, +// waitingOptions, humanOptions +// ui/components/DecisionPrompt.kt the decision card and sheet wording +// ui/screens/RunDetailScreen.kt the cancel/retry dialogs, Action failed +// +// Nothing here touches the DOM or imports the app: the decision model, the +// action eligibility rules and every user-visible string are unit-tested without +// a browser. The caller sets each string with textContent, never innerHTML. +import { nodeLabel, resolveTarget, runLabelFor } from "./runDetail.js"; + +/** Run status while parked on a person (mirrors protocol.RunStatusWaiting). */ +export const RUN_STATUS_WAITING = "waiting"; + +/** The waiting step's status, i.e. the step a decision answers. */ +export const STEP_STATUS_WAITING = "waiting"; + +/** Run status a retry is offered for. */ +export const RUN_STATUS_FAILED = "failed"; + +/** Waiting evidence keys, the wire contract the server records. */ +export const WAITING_PROMPT_KEY = "prompt"; +export const WAITING_OPTIONS_KEY = "options"; + +// --------------------------------------------------------------------------- +// Decision evidence (data/protocol/HumanDecision.kt) +// --------------------------------------------------------------------------- + +function str(value) { + return value == null ? "" : String(value); +} + +/** + * The most recent step a run is waiting on (the last waiting step), or null when + * no step is waiting. Mirrors `tui.lastWaitingStep` / `HumanDecision.kt`. + */ +export function lastWaitingStep(steps) { + const list = steps ?? []; + for (let index = list.length - 1; index >= 0; index -= 1) { + if (list[index]?.status === STEP_STATUS_WAITING) return list[index]; + } + return null; +} + +/** + * The recorded operator instructions from a waiting step's output, or "" when + * none were recorded. Mirrors `protocol.WaitingPrompt`. + */ +export function waitingPrompt(output) { + const value = output?.[WAITING_PROMPT_KEY]; + return typeof value === "string" ? value : ""; +} + +/** + * The recorded selectable options from a waiting step's output, in recorded + * order. Strings only, a malformed/blank entry dropped, an absent key yields an + * empty list — exactly like `protocol.WaitingOptions` / `waitingOptions`. + */ +export function waitingOptions(output) { + const value = output?.[WAITING_OPTIONS_KEY]; + if (!Array.isArray(value)) return []; + return value.filter((entry) => typeof entry === "string" && entry.trim() !== ""); +} + +/** + * A stage's selectable outcomes: its non-`error` edges in sorted order. Mirrors + * `stage.HumanOptions`, the fallback when a waiting step recorded no options. + */ +export function humanOptions(edges) { + return Object.keys(edges ?? {}) + .filter((key) => key !== "error") + .sort(); +} + +/** + * The resolved target label for one option: the author's target with the `#` + * shorthand resolved and terminals named as the graph names them. Blank when the + * option's edge is not declared, so the sheet omits the detail. + */ +export function decisionTargetLabel(option, target) { + if (target == null || String(target).trim() === "") return ""; + return nodeLabel(resolveTarget(option, target)); +} + +/** + * The pending decision a run is waiting on, or null when it is not waiting (or + * recorded no selectable options). The waiting step's own evidence wins over the + * pinned graph; the graph only supplies the target labels and, for a step from + * an older server, the option set itself. Mirrors `pendingDecision`. + */ +export function pendingDecision(run) { + if (run == null || run.status !== RUN_STATUS_WAITING) return null; + const step = lastWaitingStep(run.steps ?? []); + const stepStage = str(step?.stage).trim() !== "" ? String(step.stage) : ""; + const runStage = str(run.current_stage).trim() !== "" ? String(run.current_stage) : ""; + const stageKey = stepStage !== "" ? stepStage : runStage; + if (stageKey === "") return null; + + const declared = (run.graph?.stages ?? []).find((candidate) => candidate?.key === stageKey) ?? null; + const recorded = waitingOptions(step?.output); + const keys = recorded.length > 0 ? recorded : humanOptions(declared?.edges); + if (keys.length === 0) return null; + + const edges = declared?.edges ?? {}; + const options = keys.map((key) => ({ key, target: decisionTargetLabel(key, edges[key]) })); + const stepPrompt = waitingPrompt(step?.output); + const instructions = stepPrompt.trim() !== "" ? stepPrompt : str(declared?.prompt); + return { + runId: run.id, + runLabel: runLabelFor(run), + stageKey, + instructions, + options, + }; +} + +/** + * The operator's in-progress answer: the chosen option and optional feedback. + * Pure, so the deliberate-confirm rule (nothing is sent until an option is + * chosen and Confirm is pressed) is unit-tested without a device. Mirrors + * `DecisionDraft`. + */ +export class DecisionDraft { + constructor(selected = null, feedback = "") { + this.selected = selected; + this.feedback = feedback; + } + + /** A decision is only sendable once the operator has chosen one option. */ + get canSubmit() { + return typeof this.selected === "string" && this.selected.trim() !== ""; + } + + /** Selecting an option is not an answer: it only enables the confirm. */ + select(option) { + return new DecisionDraft(option, this.feedback); + } + + /** Feedback is optional and carried verbatim (trimmed by the sender). */ + withFeedback(text) { + return new DecisionDraft(this.selected, String(text ?? "")); + } +} + +// --------------------------------------------------------------------------- +// Action eligibility (RunDetailScreen.kt) +// --------------------------------------------------------------------------- + +/** Cancel is offered only while the run is executing. */ +export function canCancel(run) { + return Boolean(run?.executing); +} + +/** Retry is offered only for a loaded, non-executing, `failed` run. */ +export function canRetry(run) { + return run != null && !run.executing && run.status === RUN_STATUS_FAILED; +} + +/** The retry modes available for a run: resume (default) and restart. */ +export function retryModes(run) { + return canRetry(run) ? ["resume", "restart"] : []; +} + +/** + * A fresh idempotency key for a retry request. The server requires one and caps + * it at 128 characters (PipelinesRepository.MAX_REQUEST_KEY); this stays well + * inside that bound and unique per attempt. + */ +export function retryRequestKey(runId, now = Date.now(), random = Math.random) { + const suffix = Math.floor((Number(random()) || 0) * 1e9).toString(36); + return `web-retry-${runId}-${now}-${suffix}`; +} + +// --------------------------------------------------------------------------- +// Wording (DecisionPrompt.kt / RunDetailScreen.kt), verbatim +// --------------------------------------------------------------------------- + +export const DECISION_CARD_TITLE = "Waiting for your decision"; +export const DECISION_ACTION = "Decide"; +export const FEEDBACK_LABEL = "Feedback (optional)"; +export const DECISION_CANCEL = "Cancel"; +export const DECISION_CONFIRM = "Confirm decision"; +export const DECISION_SENDING = "Sending…"; + +export const CANCEL_DIALOG_MESSAGE = "This asks the server to stop the active run."; +export const CANCEL_CONFIRM = "Cancel run"; +export const RETRY_DIALOG_MESSAGE = + "Only failed runs can be retried. The server starts a new run from the same input."; +export const RETRY_CONFIRM = "Retry"; +export const DISMISS_KEEP = "Keep"; +// The restart confirm is browser-only (Android exposes resume alone): it states +// plainly that it replays the whole pipeline instead of resuming the failed +// stage, so the more destructive choice is never ambiguous. +export const RESTART_CONFIRM = "Restart from start"; +export const RESTART_DIALOG_MESSAGE = + "This replays the whole pipeline from the start instead of resuming the failed stage."; + +export const RENAME_ACTION = "Rename"; +export const RENAME_SAVE = "Save"; +export const RENAME_CANCEL = "Cancel"; +export const RENAME_FIELD_LABEL = "Run title"; + +export const ACTION_FAILED_TITLE = "Action failed"; +export const ACTION_FAILED_OK = "OK"; + +/** The decision card's meta line: `{stage} · run {id} · {runLabel}`. */ +export function decisionCardMeta(decision) { + return `${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}`; +} + +/** The sheet title: `Decide {stage}`. */ +export function decisionSheetTitle(stageKey) { + return `Decide ${stageKey}`; +} + +/** The sheet meta line: `run {id} · {runLabel}`. */ +export function decisionSheetMeta(decision) { + return `run ${decision.runId} · ${decision.runLabel}`; +} + +/** The option's target line, `→ {target}`, or "" when the target is unknown. */ +export function optionTargetText(target) { + return String(target ?? "").trim() === "" ? "" : `→ ${target}`; +} + +/** The cancel dialog's title: `Cancel run {id}?`. */ +export function cancelDialogTitle(runId) { + return `Cancel run ${runId}?`; +} + +/** The retry dialog's title: `Retry run {id}?`. */ +export function retryDialogTitle(runId) { + return `Retry run ${runId}?`; +} + +/** The restart dialog's title: `Restart run {id}?`. */ +export function restartDialogTitle(runId) { + return `Restart run ${runId}?`; +} diff --git a/web/src/app.js b/web/src/app.js index e2447b9e..8bfc0ce6 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -145,6 +145,58 @@ import { decodeAttentionDismissals, encodeAttentionDismissals, } from "./attention.js"; +import { + DEFAULT_SEARCH_KIND, + DEFAULT_SEARCH_SORT, + SEARCH_DEBOUNCE_MS, + SEARCH_KINDS, + SEARCH_SORTS, + SearchSequencer, + filterSearchResults, + resolveRunTarget, + searchControlsSummary, + searchFailureText, + searchPanelBody, + searchPanelProgress, + searchQuerySendable, + searchResultKindLabel, + searchRow, + searchTarget, + sortSearchResults, +} from "./search.js"; +import { + ACTION_FAILED_OK, + ACTION_FAILED_TITLE, + CANCEL_CONFIRM, + CANCEL_DIALOG_MESSAGE, + DECISION_ACTION, + DECISION_CANCEL, + DECISION_CARD_TITLE, + DECISION_CONFIRM, + DECISION_SENDING, + DISMISS_KEEP, + DecisionDraft, + FEEDBACK_LABEL, + RENAME_ACTION, + RENAME_CANCEL, + RENAME_FIELD_LABEL, + RENAME_SAVE, + RESTART_CONFIRM, + RESTART_DIALOG_MESSAGE, + RETRY_CONFIRM, + RETRY_DIALOG_MESSAGE, + canCancel, + canRetry, + cancelDialogTitle, + decisionCardMeta, + decisionSheetMeta, + decisionSheetTitle, + optionTargetText, + pendingDecision, + restartDialogTitle, + retryDialogTitle, + retryRequestKey, +} from "./actions.js"; const STORAGE_KEY = "pipelines.web.serverUrl.v2"; @@ -229,6 +281,33 @@ const state = { attentionDismissed: new Set(), attentionSheetOpen: false, attentionSnapshot: null, + // Omni-search (S1/S2): the field/panel state, kept beside the view it never + // changes, plus the pure debounce/stale-token sequencer. Opening or closing the + // search leaves state.view, the selection and the loaded data untouched. + searchOpen: false, + searchQuery: "", + searchKind: DEFAULT_SEARCH_KIND, + searchSort: DEFAULT_SEARCH_SORT, + searchResults: [], + searchLoading: false, + searchError: "", + searchLoaded: false, + searchFocusPending: false, + searchSequencer: new SearchSequencer(), + // Run-level operator actions (R11–R14): the decision the open sheet renders + // (retained across a refused send so the server's own reason can be shown even + // after a refresh), the sheet's draft/sending/error, the action awaiting a + // confirm dialog, the in-progress rename title (null when not editing) and the + // one shared Action-failed dialog. + runDecision: null, + decisionOpen: false, + decisionDraft: new DecisionDraft(), + decisionSending: false, + decisionError: "", + confirmKind: null, + renameValue: null, + renameBusy: false, + actionError: "", }; let runPoll = null; @@ -276,6 +355,10 @@ function isExecuting(run) { // --------------------------------------------------------------------------- const header = h("header", { class: "topbar" }); +// The full-width omni-search panel sits directly under the top bar (and so under +// the search control that lives in it), above the connection banner so it can +// never be mistaken for a status strip. +const searchHost = h("div", { id: "searchHost", class: "search-host" }); // The persistent connection banner sits in normal document flow directly under // the header (never fixed/overlaying), so it can never cover the content. const connBanner = h("div", { id: "connBanner", class: "conn-banner", hidden: true }); @@ -283,7 +366,12 @@ const content = h("main", { id: "content" }); // The attention sheet lives in its own layer so it can overlay any view without // being torn down by a content re-render; renderAttentionSheet rebuilds it. const attentionLayer = h("div", { id: "attentionLayer" }); -document.body.append(header, connBanner, content, 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() { @@ -293,6 +381,7 @@ function endpointConfigured() { function renderHeader() { const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() }); const controls = [ + ...searchHeaderControls(), h("input", { id: "url", type: "text", @@ -329,6 +418,58 @@ function renderHeader() { ), h("div", { class: "connbar" }, ...controls), ); + // Autofocus the field only for the render that opened it, so a later + // connection-state re-render never steals the operator's focus. + if (state.searchOpen && state.searchFocusPending) { + document.getElementById("searchInput")?.focus(); + state.searchFocusPending = false; + } +} + +/** + * The top bar's search control: the Search button while closed, and the query + * field with its Close control while open. The field's value is always read back + * from `state.searchQuery`, so a re-render can never desync the two. + */ +function searchHeaderControls() { + if (!state.searchOpen) { + return [ + h("button", { + id: "searchToggle", + class: "ghost search-toggle", + type: "button", + title: "Search", + text: "Search", + onclick: openSearch, + }), + ]; + } + return [ + h("input", { + id: "searchInput", + class: "search-input", + type: "text", + placeholder: "Search pipelines, runs and artifacts", + value: state.searchQuery, + spellcheck: "false", + autocomplete: "off", + "aria-label": "Search", + oninput: (event) => onSearchInput(event.target.value), + onkeydown: (event) => { + if (event.key === "Enter") { + event.preventDefault(); + sendSearchNow(); + } + }, + }), + h("button", { + id: "searchClose", + class: "ghost search-close", + type: "button", + text: "Close search", + onclick: closeSearch, + }), + ]; } /** @@ -591,6 +732,7 @@ function loadAttentionDismissed() { function render() { renderHeader(); renderBanner(); + renderSearch(); renderContent(); renderAttentionSheet(); } @@ -1446,6 +1588,12 @@ function renderRunDetail() { 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", @@ -1474,6 +1622,10 @@ function renderRunDetail() { 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; } @@ -1515,7 +1667,7 @@ function latestVisitIndex(d, key) { /** 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(h("h2", { class: "run-detail-title", text: runLabelFor(d) })); + 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 })); @@ -2174,6 +2326,413 @@ function closeStagePane() { 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; @@ -2511,6 +3070,337 @@ function kvMono(key, value) { ); } +// --------------------------------------------------------------------------- +// 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 // --------------------------------------------------------------------------- @@ -2706,6 +3596,16 @@ async function selectRun(id, { silent = false } = {}) { state.runSections = new Set(); state.runStagePane = null; state.runStageSections = new Set(); + // A different run reseeds the run-level action state, so a decision sheet, + // confirm dialog, rename field or failure report never leaks across runs. + state.runDecision = null; + state.decisionOpen = false; + state.decisionDraft = new DecisionDraft(); + state.decisionSending = false; + state.decisionError = ""; + state.confirmKind = null; + state.renameValue = null; + state.actionError = ""; renderContent(); } try { @@ -2806,10 +3706,12 @@ client.addEventListener("state", (event) => { render(); }); -// The stage pane is a modal dialog: Escape closes it (a stacked overlay — the -// artifact viewer or the diff viewer, when either is above — owns Escape first). -// The attention sheet, when open, is the topmost overlay and owns Escape first. -// Registered once; it is a no-op when no pane is open. +// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the +// omni-search field and the attention sheet are modal: Escape closes the topmost +// one (the artifact viewer or the diff viewer, when either is above, owns Escape +// first via its own listener). The attention sheet, when open, is the topmost +// overlay and owns Escape first. Registered once; every branch is a no-op when +// nothing is open. document.addEventListener("keydown", (event) => { if (event.key !== "Escape") return; if (state.attentionSheetOpen) { @@ -2817,13 +3719,30 @@ document.addEventListener("keydown", (event) => { closeAttentionSheet(); return; } - if ( - state.runStagePane && - !document.querySelector(".artifact-viewer") && - !document.querySelector(".change-viewer") - ) { + if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return; + if (state.actionError) { + event.preventDefault(); + dismissActionError(); + return; + } + if (state.confirmKind) { + event.preventDefault(); + dismissConfirm(); + return; + } + if (state.decisionOpen) { + event.preventDefault(); + closeDecisionSheet(); + return; + } + if (state.runStagePane) { event.preventDefault(); closeStagePane(); + return; + } + if (state.searchOpen) { + event.preventDefault(); + closeSearch(); } }); diff --git a/web/src/protocol.js b/web/src/protocol.js index cc7946d1..6be8f7b4 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -21,6 +21,19 @@ export const Protocol = Object.freeze({ GET_RUN: "get_run", RUN: "run", + // Omni-search (internal/protocol/search.go): the command and its reply type. + // The per-kind payloads and the kind/limit vocabulary live in src/search.js. + SEARCH: "search", + SEARCH_RESULTS: "search_results", + + // The run-level operator actions (R11–R14). Each replies with a `run` (or + // `run_started` for retry) envelope carrying the updated run detail; mirrors + // internal/protocol/runs.go and Message.kt. + CANCEL_RUN: "cancel_run", + RETRY_RUN: "retry_run", + DECIDE_RUN: "decide_run", + SET_RUN_TITLE: "set_run_title", + SUCCESS_END: "#success", FAILURE_END: "#failure", }); diff --git a/web/src/repository.js b/web/src/repository.js index 11251765..75b27b0a 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -72,4 +72,85 @@ export class PipelinesRepository { } return response.run_detail; } + + /** + * Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from + * internal/protocol/search.go: `kind` is the empty string for every kind, and + * `limit` is fixed at `0` so the server applies its own default cap + * (`SearchDefaultLimit`, 50) and never the client's — `SearchMaxLimit` (200) is + * therefore never approached, let alone exceeded. + * + * Returns `reply.search_results`, the ranked `SearchResponse`, or **null** when + * an older server answered without that payload (its default `pong`), which the + * caller reports as "this server does not support search" rather than dropping. + * An explicit server error is already surfaced by `client.call` as a + * `ProtocolError` carrying the server's own text. + */ + async search(query, kind = "") { + const response = await this.#client.call({ + type: Protocol.SEARCH, + search: { query, kind, limit: 0 }, + }); + return response.search_results ?? null; + } + + /** + * Answers a run's waiting human stage with the chosen `option` and optional + * `feedback` (mirrors PipelinesRepository.decideRun). The stage is sent only + * when non-blank and the feedback is trimmed, exactly like the Android client; + * a refused decision rejects with the server's own reason (a ProtocolError). + */ + async decideRun(id, { stage, option, feedback } = {}) { + const request = { type: Protocol.DECIDE_RUN, run_id: id, option }; + if (stage != null && String(stage).trim() !== "") request.stage = stage; + const trimmedFeedback = String(feedback ?? "").trim(); + if (trimmedFeedback !== "") request.feedback = trimmedFeedback; + const response = await this.#client.call(request); + if (!response.run_detail) { + throw new ProtocolError("The server returned no run detail."); + } + return response.run_detail; + } + + /** Cancels a run; mirrors PipelinesRepository.cancelRun (exactly run_id). */ + async cancelRun(id) { + const response = await this.#client.call({ type: Protocol.CANCEL_RUN, run_id: id }); + if (!response.run_detail) { + throw new ProtocolError("The server returned no run detail."); + } + return response.run_detail; + } + + /** + * Retries a terminal failed run. `request_key` is always sent (the retry is + * its own idempotent run); `retry_mode` is sent only for an explicit + * `restart`, so the server's default (resume) applies exactly as the Android + * client's mode-less call. + */ + async retryRun(id, { mode = null, requestKey } = {}) { + const request = { + type: Protocol.RETRY_RUN, + run_id: id, + request_key: requestKey ?? "", + }; + if (mode === "restart") request.retry_mode = "restart"; + const response = await this.#client.call(request); + if (!response.run_detail) { + throw new ProtocolError("The server returned no run detail."); + } + return response.run_detail; + } + + /** Renames a run's stored title; mirrors the set_run_title wire command. */ + async setRunTitle(id, title) { + const response = await this.#client.call({ + type: Protocol.SET_RUN_TITLE, + run_id: id, + title, + }); + if (!response.run_detail) { + throw new ProtocolError("The server returned no run detail."); + } + return response.run_detail; + } } diff --git a/web/src/search.js b/web/src/search.js new file mode 100644 index 00000000..cee6198b --- /dev/null +++ b/web/src/search.js @@ -0,0 +1,500 @@ +// Pure, DOM-free omni-search logic for the web client, ported from the Android +// client so the browser says and shows exactly the same things: +// ui/OmniSearchResults.kt searchRow, snippetSpans, SearchKindFilter, +// SearchSort, filterSearchResults, +// sortSearchResults, searchTarget, +// searchFieldSection, resolveRunTarget, +// SearchSequencer, SearchUiState, +// searchPanelEmptyMessage +// ui/SearchResultsPanel.kt the controls summary and the empty-state copy +// data/protocol/Message.kt the search kind vocabulary (Protocol.SEARCH_KIND_*) +// +// Nothing here touches the DOM or imports the app: every function is pure so the +// per-kind row text, the in-hand filtering/ordering, the routing target and the +// debounce/stale-token sequencing can be unit-tested without a browser. The DOM +// wiring lives in app.js. Every server-provided string is only ever compared or +// rendered, never parsed as markup; the caller sets it with textContent. +import { stageCountText, parseInstant, formatLocalTimestamp } from "./pipelines.js"; +import { artifactKind, artifactKindLabel, humanBytes } from "./artifacts.js"; +import { runTimeline } from "./runDetail.js"; + +// --------------------------------------------------------------------------- +// Kind + sort vocabulary (ui/OmniSearchResults.kt SearchKindFilter/SearchSort) +// --------------------------------------------------------------------------- + +/** + * The kind narrowing the search control offers, in the task's order. `value` is + * exactly the server's `SearchRequest.kind` vocabulary + * (internal/protocol/search.go); the empty string is every kind. There is + * deliberately no "prompts" entry: the server has no such kind, so a filter that + * could only ever match nothing is not offered. + */ +export const SEARCH_KINDS = [ + { value: "", label: "All kinds" }, + { value: "pipeline", label: "Pipelines" }, + { value: "run", label: "Runs" }, + { value: "step", label: "Steps" }, + { value: "field", label: "Fields" }, + { value: "artifact", label: "Artifacts" }, + { value: "version", label: "Versions" }, +]; + +/** The default, no-narrowing kind. */ +export const DEFAULT_SEARCH_KIND = ""; + +/** + * The orders the search sort control offers. "Relevance" keeps the server's own + * ranking (score, then recency, then a stable kind/target tie-break); "Newest + * first" and "Name" cannot be asked of the server — its search command takes only + * a query, an optional kind and a limit — so they order the results already in + * hand. Every sort is stable: two results that tie keep the server's order. + */ +export const SEARCH_SORTS = [ + { value: "relevance", label: "Relevance" }, + { value: "newest", label: "Newest first" }, + { value: "name", label: "Name" }, +]; + +/** The default, server-order sort. */ +export const DEFAULT_SEARCH_SORT = "relevance"; + +/** The quiet period after the last keystroke before a query is sent. */ +export const SEARCH_DEBOUNCE_MS = 250; + +/** + * The report for a server that cannot answer `search`: an explicit rejection + * naming an unknown/unsupported command, or an older server's reply without the + * `search_results` payload. Wording is AppViewModel.kt verbatim. + */ +export const SEARCH_UNSUPPORTED = + "This server does not support search. Update the Pipelines server, then try again."; + +/** The label for `kind` (`""` = All kinds), tolerating a stale/unknown value. */ +export function searchKindLabel(kind) { + return (SEARCH_KINDS.find((option) => option.value === kind) ?? SEARCH_KINDS[0]).label; +} + +/** The label for `sort`, tolerating a stale/unknown value. */ +export function searchSortLabel(sort) { + return (SEARCH_SORTS.find((option) => option.value === sort) ?? SEARCH_SORTS[0]).label; +} + +/** + * The one-line summary of the active filter and order the collapsed controls + * show. The item's browser wording is exactly `{Kind} · {Sort}` — deliberately + * without the Android panel's ` (in hand)` suffix, which is a note about which + * orders run locally rather than a report the browser needs. + */ +export function searchControlsSummary(kind, sort) { + return `${searchKindLabel(kind)} · ${searchSortLabel(sort)}`; +} + +// --------------------------------------------------------------------------- +// Row model (ui/OmniSearchResults.kt searchRow / snippetSpans) +// --------------------------------------------------------------------------- + +/** The non-blank text, else null — the Android `takeIf { it.isNotBlank() }`. */ +function nonBlank(value) { + const text = String(value ?? ""); + return text.trim() === "" ? null : text; +} + +/** A finite number for a payload field, so a missing value never prints "undefined". */ +function num(value) { + const number = Number(value); + return Number.isFinite(number) ? number : 0; +} + +/** The non-null, non-empty fragments joined with ` · `; blanks are omitted. */ +function joinNonBlank(parts) { + return (parts ?? []).filter((part) => part != null && String(part) !== "").join(" · "); +} + +/** Case-insensitive string comparison, matching String.CASE_INSENSITIVE_ORDER for ASCII. */ +function compareInsensitive(a, b) { + const x = String(a ?? "").toUpperCase(); + const y = String(b ?? "").toUpperCase(); + if (x < y) return -1; + if (x > y) return 1; + return 0; +} + +/** + * Splits `snippet` into runs so the first case-insensitive occurrence of `query` + * (trimmed) is a distinct, `matched` span. When the query is blank or does not + * appear — a bare status/date query, or a server-trimmed snippet — the whole + * snippet is returned unmatched, so the caller never drops text. An empty + * snippet yields no spans at all. Mirrors OmniSearchResults.snippetSpans. + */ +export function snippetSpans(snippet, query) { + const text = String(snippet ?? ""); + if (text === "") return []; + const needle = String(query ?? "").trim(); + if (needle === "") return [{ text, matched: false }]; + const index = text.toLowerCase().indexOf(needle.toLowerCase()); + if (index < 0) return [{ text, matched: false }]; + const end = index + needle.length; + const spans = []; + if (index > 0) spans.push({ text: text.slice(0, index), matched: false }); + spans.push({ text: text.slice(index, end), matched: true }); + if (end < text.length) spans.push({ text: text.slice(end), matched: false }); + return spans; +} + +/** + * The one-line non-snippet secondary line of a step hit: its outcome, route and + * first non-blank diagnostic line, or `step {sequence}` when all are blank. + * Mirrors OmniSearchResults.stepSecondary. + */ +function stepSecondary(step) { + const diagnostic = String(step?.diagnostic ?? ""); + const line = diagnostic.split(/\r?\n/).find((candidate) => candidate.trim() !== ""); + const target = nonBlank(step?.target); + const joined = joinNonBlank([ + nonBlank(step?.outcome), + target ? `→ ${target}` : null, + line == null ? null : line.trim(), + ]); + return joined === "" ? `step ${num(step?.sequence)}` : joined; +} + +/** + * One rendered search row: its `title`, its plain `secondary` line and, only for + * a text ("field") match, a `snippet` split into spans so the matched run is + * distinguishable without colour (the caller wraps a matched span in an emphasis + * element). An unknown/absent payload is never dropped: it renders its stable + * target (or a placeholder) and a `read-only` note. Every per-kind rule mirrors + * OmniSearchResults.searchRow, including the Android blank fallbacks. + */ +export function searchRow(hit, query, options = {}) { + const { timeZone } = options; + const pipeline = hit?.pipeline; + const version = hit?.version; + const run = hit?.run; + const step = hit?.step; + const field = hit?.field; + const artifact = hit?.artifact; + + if (pipeline) { + return { + title: nonBlank(pipeline.name) ?? `pipeline ${num(pipeline.id)}`, + secondary: `pipeline ${num(pipeline.id)} · v${num(pipeline.version)} · ${stageCountText(pipeline.stages)}`, + snippet: null, + }; + } + if (version) { + const hash = nonBlank(version.content_hash); + return { + title: `pipeline ${num(version.pipeline_id)} · v${num(version.version)}`, + secondary: joinNonBlank([ + hash ? `content ${hash}` : null, + formatLocalTimestamp(version.created_at, { timeZone }), + ]), + snippet: null, + }; + } + if (run) { + const name = nonBlank(run.pipeline_name); + return { + title: `run #${num(run.id)}${name ? ` · ${name}` : ""}`, + secondary: joinNonBlank([ + nonBlank(run.status), + nonBlank(run.workspace), + formatLocalTimestamp(run.created_at, { timeZone }), + ]), + snippet: null, + }; + } + if (step) { + return { + title: `run #${num(step.run_id)} · ${nonBlank(step.stage) ?? "step"} visit ${num(step.visit)}`, + secondary: stepSecondary(step), + snippet: null, + }; + } + if (field) { + return { + title: `run #${num(field.run_id)} · step ${num(field.sequence)} · ${nonBlank(field.field) ?? "field"}`, + secondary: String(field.snippet ?? ""), + snippet: snippetSpans(field.snippet, query), + }; + } + if (artifact) { + return { + title: nonBlank(artifact.name) ?? "artifact", + secondary: joinNonBlank([ + `run #${num(artifact.run_id)}`, + `step ${num(artifact.sequence)}`, + nonBlank(artifact.content_type), + humanBytes(artifact.size_bytes), + ]), + snippet: null, + }; + } + const kind = nonBlank(hit?.kind); + return { + title: nonBlank(hit?.target) ?? "Unrecognised result", + secondary: kind ? `kind "${kind}" · read-only` : "read-only", + snippet: null, + }; +} + +/** + * The kind in words for a row's accessible description, so a screen reader hears + * what the row is. An artifact is named by its own content type ("Image + * artifact", "JSON artifact"), from the same gallery classification + * searchResultIcon uses. Mirrors OmniSearchResults.searchResultKindLabel. + */ +export function searchResultKindLabel(hit) { + if (hit?.pipeline) return "Pipeline"; + if (hit?.version) return "Pipeline version"; + if (hit?.run) return "Run"; + if (hit?.step) return "Step"; + if (hit?.field) return "Field"; + if (hit?.artifact) { + return `${artifactKindLabel(artifactKind(hit.artifact.content_type, hit.artifact.name))} artifact`; + } + return "Unrecognised result"; +} + +// --------------------------------------------------------------------------- +// In-hand narrowing and ordering (SearchResultsPanel.kt SearchResultList) +// --------------------------------------------------------------------------- + +/** + * Narrows `results` to `kind`'s kind (`""` = every kind). The kind is also sent + * to the server (`SearchRequest.kind`), so this only re-narrows the results + * already in hand, keeping the panel honest while a narrowed request loads. + */ +export function filterSearchResults(results, kind) { + const list = results ?? []; + if (kind === "" || kind == null) return list; + return list.filter((hit) => hit?.kind === kind); +} + +/** + * Orders `results` by `sort`. "Relevance" (and any stale value) leaves the + * server's ranking untouched; "Newest first" orders by parsed recency + * descending, with an unparseable/missing recency last; "Name" orders by the + * displayed title, case-insensitively. Every sort is stable, so ties keep the + * server's order rather than swapping arbitrarily. + */ +export function sortSearchResults(results, sort) { + const list = results ?? []; + if (sort === "newest") { + return [...list].sort((a, b) => { + const ta = parseInstant(a?.recency); + const tb = parseInstant(b?.recency); + const na = ta == null ? -Infinity : ta; + const nb = tb == null ? -Infinity : tb; + if (na === nb) return 0; + return na > nb ? -1 : 1; + }); + } + if (sort === "name") { + return [...list] + .map((hit) => ({ hit, title: searchRow(hit, "").title })) + .sort((a, b) => compareInsensitive(a.title, b.title)) + .map((entry) => entry.hit); + } + return list; +} + +/** + * The empty-state line the panel shows when it has no rows to render for the + * (non-blank) query under `kind`, or null when it is showing rows, progress, an + * error or nothing at all. `shown` is the filtered and sorted list actually + * displayed, so a filter that empties the list reports itself ("No runs match …") + * rather than the generic line. Mirrors searchPanelEmptyMessage. + * + * Android's own copy is the invariant `No {kind} match "{query}".` — the same + * sentence shape the pipeline list already carries in src/pipelines.js — and the + * browser keeps it verbatim. + */ +export function searchPanelEmptyMessage(state, shown, kind) { + if (state?.error) return null; + if ((shown ?? []).length > 0) return null; + if (state?.loading) return null; + const query = String(state?.query ?? ""); + if (query.trim() === "") return null; + if (kind === "" || kind == null) return `No matches for "${query}".`; + return `No ${searchKindLabel(kind).toLowerCase()} match "${query}".`; +} + +/** + * Whether a keystroke's text is worth asking the server about. A blank or + * whitespace-only query is cleared locally and never sent, so the server is not + * asked to scan for nothing. The one predicate the field's input handler and its + * immediate-send path share. + */ +export function searchQuerySendable(query) { + return String(query ?? "").trim() !== ""; +} + +/** + * Whether the panel draws its thin refresh bar: a newer query is loading while + * results are still on screen, so progress is reported above them rather than + * blanking the list. Pure, so "retained results plus progress on a refresh" is + * testable without a browser. + */ +export function searchPanelProgress(state) { + return Boolean(state?.loading) && (state?.results ?? []).length > 0; +} + +/** + * The body the panel renders, mirroring SearchResultsPanel's `when` in order: an + * error takes precedence over the results; the filtered/sorted rows when there + * are any; the first-load searching row while nothing has arrived; otherwise the + * empty-state line, or nothing at all (a blank query, or a filter that emptied a + * list while a refresh is in flight). Pure, so every state is unit-testable + * without a browser. + */ +export function searchPanelBody(state, shown, kind) { + if (state?.error) return { kind: "error", message: state.error }; + if ((shown ?? []).length > 0) return { kind: "results", message: "" }; + // The searching row is the first load only: once any result is retained, a + // refresh reports itself with the progress bar instead of replacing the list. + if (state?.loading && (state?.results ?? []).length === 0) return { kind: "searching", message: "" }; + const message = searchPanelEmptyMessage(state, shown, kind); + return message == null ? { kind: "idle", message: "" } : { kind: "empty", message }; +} + +// --------------------------------------------------------------------------- +// Navigation (ui/OmniSearchResults.kt searchTarget / resolveRunTarget) +// --------------------------------------------------------------------------- + +/** + * The navigation a selected search result asks for, or null for a kind with no + * known payload (an unknown match), which is shown read-only rather than dropped. + * A pipeline/version target names the pipeline detail (version 0 = latest); a + * run target names a run, and carries the recorded `sequence` (0 = the plain run + * detail) plus, for a text match, the `matchedField` naming the run-detail tab + * holding the match. + */ +export function searchTarget(hit) { + if (hit?.pipeline) { + return { kind: "pipeline", pipelineId: num(hit.pipeline.id), version: num(hit.pipeline.version) }; + } + if (hit?.version) { + return { + kind: "pipeline", + pipelineId: num(hit.version.pipeline_id), + version: num(hit.version.version), + }; + } + if (hit?.run) return { kind: "run", runId: num(hit.run.id), sequence: 0, matchedField: "" }; + if (hit?.step) { + return { kind: "run", runId: num(hit.step.run_id), sequence: num(hit.step.sequence), matchedField: "" }; + } + if (hit?.field) { + // The run-detail tab is chosen from the hit's `matched_field` (the browser + // item's deliberate rule), not from the recorded field name. + return { + kind: "run", + runId: num(hit.field.run_id), + sequence: num(hit.field.sequence), + matchedField: String(hit.matched_field ?? ""), + }; + } + if (hit?.artifact) { + return { + kind: "run", + runId: num(hit.artifact.run_id), + sequence: num(hit.artifact.sequence), + matchedField: "", + }; + } + return null; +} + +/** + * The run-detail tab holding a matched step field's text: `input` -> Input, + * `output` -> Output, anything else (a retired evidence/transcript tab, or an + * unknown field) -> Summary, so no stale hit accidentally selects Timeline. + */ +export function searchFieldTab(matchedField) { + switch (String(matchedField ?? "")) { + case "input": + return "input"; + case "output": + return "output"; + default: + return "summary"; + } +} + +/** + * Resolves a run `target` against the loaded run's `steps` into the pane + * selection showing the requested tab or visit. A text match returns the tab + * holding it; a step/artifact target returns the zero-based visit index within + * its stage (the server's visit number need not equal the index); a visit that + * cannot be located — or a bare run target — returns an empty selection, so the + * plain run detail is shown and a hit is never dropped. `runId` is the run the + * target named (kept for parity with the Android signature). + */ +export function resolveRunTarget(target, runId, steps) { + if (!target) return {}; + if (String(target.matchedField ?? "").trim() !== "") { + return { tab: searchFieldTab(target.matchedField) }; + } + const sequence = num(target.sequence); + if (sequence <= 0) return {}; + const list = steps ?? []; + const step = list.find((candidate) => num(candidate?.sequence) === sequence); + if (!step) return {}; + const visits = runTimeline(list).visitsByStage.get(step.stage) ?? []; + const index = visits.findIndex((candidate) => num(candidate?.sequence) === sequence); + return { stageKey: step.stage, visitIndex: Math.max(index, 0) }; +} + +// --------------------------------------------------------------------------- +// Query sequencing: debounce + stale-reply gating +// --------------------------------------------------------------------------- + +/** + * The pure ordering behind omni-search. + * + * `edit` records a keystroke and returns the pending edit to debounce; when the + * quiet period elapses the caller passes it to `begin`, which returns the query + * to send only if no newer keystroke arrived — so a burst of keystrokes collapses + * into one request for the last one. Every sent request carries a monotonically + * increasing token and `accepts` is true only for the newest recorded edit, so a + * reply for a superseded query can never overwrite a newer one. Recording an edit + * (a keystroke, or an empty edit when the panel closes) is enough to reject an + * already in-flight reply; no separate cancel is needed. + */ +export class SearchSequencer { + #newest = 0; + + edit(query) { + return { token: ++this.#newest, query }; + } + + begin(edit) { + if (!edit || edit.token !== this.#newest) return null; + return { token: edit.token, query: edit.query }; + } + + accepts(token) { + return token === this.#newest; + } +} + +// --------------------------------------------------------------------------- +// Failure copy (AppViewModel.runSearch) +// --------------------------------------------------------------------------- + +/** + * The message for a failed search: the "server cannot search" sentence for a + * missing `search_results` payload (an older server's pong) or a rejection naming + * an unknown/unsupported command, otherwise the server's own text unchanged. + */ +export function searchFailureText(error) { + if (error == null) return SEARCH_UNSUPPORTED; + const message = (error instanceof Error ? error.message : String(error)).trim(); + if (message === "") return SEARCH_UNSUPPORTED; + if (/\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b/i.test(message)) { + return SEARCH_UNSUPPORTED; + } + return message; +} diff --git a/web/styles.css b/web/styles.css index 3733944b..26356069 100644 --- a/web/styles.css +++ b/web/styles.css @@ -1143,3 +1143,243 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- @media (max-width: 760px) { .attention-sheet-panel { width: 100%; max-height: 88vh; } } +/* --- Omni-search (S1/S2) ------------------------------------------------- */ + +/* The panel sits in normal flow under the top bar; the wrapper disappears + entirely while the search is closed. */ +.search-host { background: var(--surface); border-bottom: 1px solid var(--border); } +.search-host:empty { display: none; } + +.search-panel { padding: 10px 16px 12px; display: grid; gap: 8px; } + +.search-controls { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } +.search-field { display: flex; gap: 6px; align-items: center; } +.search-field-label { color: var(--muted); font-size: 12px; } +.search-select { + padding: 5px 8px; + background: var(--surface-2); + color: var(--text); + border: 1px solid var(--border); + border-radius: 8px; + font: inherit; +} + +/* --------------------------------------------------------------------------- + Run-level operator actions (parity R11–R14): the waiting-for-decision card + and sheet, the shared cancel/retry/restart confirm dialogs, the one + Action-failed dialog and the inline rename control. Hand-written, the app's + dark palette; every string is set with textContent. + --------------------------------------------------------------------------- */ + +.run-actions { display: flex; gap: 8px; flex-wrap: wrap; margin: 0 0 4px; } +.run-action { padding: 4px 12px; font-size: 12px; } +.run-action.cancel-run { border-color: var(--warn); color: var(--warn); } +.run-action.retry-run { border-color: var(--accent); color: var(--accent); } + +/* The decision card: a prominent banner above the tabs. */ +.decision-card { + display: flex; + gap: 12px; + align-items: center; + padding: 12px 14px; + margin-bottom: 12px; + border: 1px solid #8edff5; + border-radius: 10px; + background: #102329; +} +.decision-card-icon { font-size: 18px; line-height: 1; } +.decision-card-text { flex: 1; min-width: 0; display: grid; gap: 2px; } +.decision-card-title { font-weight: 600; } +.decision-card-meta { font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.decision-open { border-color: #8edff5; color: #8edff5; font-weight: 600; } + +/* The decision sheet: a centred modal panel over a dim backdrop. */ +.decision-sheet { + position: fixed; + inset: 0; + z-index: 35; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + background: rgba(0, 0, 0, 0.55); +} +.decision-sheet-panel { + display: grid; + gap: 10px; + width: min(520px, 100%); + max-height: 100%; + overflow-y: auto; + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 12px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); +} +.decision-sheet-title { margin: 0; font-size: 16px; } +.decision-sheet-meta { font-size: 12px; } +.decision-instructions { margin: 0; line-height: 1.5; } +.decision-options { display: grid; gap: 6px; } +.decision-option { + display: flex; + gap: 10px; + align-items: center; + width: 100%; + text-align: left; + padding: 8px 10px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 8px; +} +.decision-option:hover { border-color: var(--accent); } +.decision-option.selected { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); } +.decision-radio { + width: 14px; + height: 14px; + border-radius: 50%; + border: 2px solid var(--muted); + flex: none; +} +.decision-option.selected .decision-radio { + border-color: var(--accent); + box-shadow: inset 0 0 0 3px var(--surface-2), inset 0 0 0 8px var(--accent); +} +.decision-option-body { display: grid; gap: 2px; min-width: 0; } +.decision-option-key { font-weight: 600; } +.decision-option-target { font-size: 12px; } +.decision-field { display: grid; gap: 4px; } +.decision-field-label { font-size: 12px; color: var(--muted); } +.decision-feedback { + width: 100%; + padding: 6px 8px; + background: var(--surface-2); + color: var(--text); + border: 1px solid var(--border); + border-radius: 8px; + font: inherit; +} + +.search-select:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } +.search-summary { flex: 1 1 160px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.search-clear { padding: 5px 10px; font-size: 12px; } + +.search-input { flex: 1 1 260px; } +.search-close { white-space: nowrap; } + +/* A bounded, self-scrolling result surface: the panel never pushes the page + body around however many hits come back. */ +.search-results { + max-height: min(50vh, 420px); + overflow-y: auto; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface-2); +} + +/* The refresh indicator: shown above retained results rather than replacing + them, so a re-query never blanks the list. */ +.search-progress { + height: 3px; + background: var(--accent); + border-radius: 2px; + transform-origin: left; + animation: search-progress 1.1s ease-in-out infinite; +} +@keyframes search-progress { + 0% { opacity: 0.3; transform: scaleX(0.2); } + 50% { opacity: 1; transform: scaleX(1); } + 100% { opacity: 0.3; transform: scaleX(0.2); } +} +@media (prefers-reduced-motion: reduce) { + .search-progress { animation: none; } +} + +/* A flat list of rows, with no grouping headers, matching the app. */ +.search-row { + display: flex; + gap: 10px; + align-items: baseline; + padding: 8px 12px; + border-bottom: 1px solid var(--border); +} +.search-row:last-child { border-bottom: 0; } +.search-row.clickable { cursor: pointer; } +.search-row.clickable:hover { background: var(--surface); } +.search-row.clickable:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.search-row.readonly { opacity: 0.85; } +.search-kind { flex: 0 0 auto; font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; padding-top: 2px; } +.search-row-main { flex: 1 1 auto; min-width: 0; } +.search-row-title { font-weight: 600; } +.search-row-secondary, .search-row-snippet { + font-size: 12px; + margin-top: 2px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.search-match { color: var(--accent); } + +.search-searching { display: flex; gap: 8px; align-items: center; padding: 12px; } +.search-error { padding: 12px; color: var(--bad); } +.search-empty { padding: 12px; } + +@media (max-width: 760px) { + .search-input { flex-basis: 100%; } + .search-summary { flex-basis: 100%; } +} + +.decision-feedback:focus { outline: none; border-color: var(--accent); } +.decision-error { font-size: 13px; } +.decision-sheet-actions { display: flex; gap: 8px; justify-content: flex-end; } +.decision-confirm { border-color: var(--accent); color: var(--accent); font-weight: 600; } +.decision-confirm:disabled, .decision-cancel:disabled { opacity: 0.5; } + +/* Shared confirm dialog (cancel / retry / restart) and the Action-failed one. */ +.confirm-dialog, +.action-failed { + position: fixed; + inset: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: center; + padding: 24px; + background: rgba(0, 0, 0, 0.55); +} +.confirm-panel, +.action-failed-panel { + display: grid; + gap: 12px; + width: min(420px, 100%); + padding: 16px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: 12px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); +} +.confirm-title, +.action-failed-title { margin: 0; font-size: 16px; } +.confirm-message, +.action-failed-message { margin: 0; line-height: 1.5; } +.action-failed-message { color: var(--bad); } +.confirm-actions { display: flex; gap: 8px; align-items: center; } +.confirm-secondary { margin-right: auto; font-size: 12px; } +.confirm-accept { border-color: var(--accent); color: var(--accent); font-weight: 600; } +.action-failed-ok { justify-self: end; } + +/* The inline rename control on the Summary title row. */ +.run-title-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } +.run-title-row .run-detail-title { margin: 0; } +.rename-field { display: flex; gap: 6px; align-items: center; flex: 1; min-width: 0; } +.rename-input { + flex: 1; + min-width: 0; + padding: 6px 8px; + background: var(--surface-2); + color: var(--text); + border: 1px solid var(--border); + border-radius: 8px; + font: inherit; +} +.rename-input:focus { outline: none; border-color: var(--accent); } +.rename-save { border-color: var(--accent); color: var(--accent); font-weight: 600; } diff --git a/web/test/actions.test.mjs b/web/test/actions.test.mjs new file mode 100644 index 00000000..a2ea0fb5 --- /dev/null +++ b/web/test/actions.test.mjs @@ -0,0 +1,260 @@ +// Pure unit tests for the run-level action helpers (R11–R14): the pending human +// decision extracted from a waiting step (with the pinned-graph fallback), the +// option/target wording, the cancel/retry eligibility, the deliberate-confirm +// draft rule and the verbatim Android copy. No server, no DOM. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +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, + RESTART_CONFIRM, + RESTART_DIALOG_MESSAGE, + RETRY_CONFIRM, + RETRY_DIALOG_MESSAGE, + canCancel, + canRetry, + cancelDialogTitle, + decisionCardMeta, + decisionSheetMeta, + decisionSheetTitle, + decisionTargetLabel, + humanOptions, + lastWaitingStep, + optionTargetText, + pendingDecision, + retryDialogTitle, + retryModes, + retryRequestKey, + restartDialogTitle, + waitingOptions, + waitingPrompt, +} from "../src/actions.js"; + +/** A run with the fields pendingDecision reads; overridable per test. */ +function run(overrides = {}) { + return { + id: 42, + title: "", + name: "Pipe", + status: "waiting", + current_stage: "review", + executing: false, + steps: [], + ...overrides, + }; +} + +test("lastWaitingStep finds the last waiting step, null when none is waiting", () => { + const steps = [ + { stage: "plan", status: "completed" }, + { stage: "review", status: "waiting" }, + { stage: "review", status: "waiting" }, + ]; + assert.equal(lastWaitingStep(steps)?.stage, "review"); + assert.equal(lastWaitingStep(steps), steps[2]); + assert.equal(lastWaitingStep([{ stage: "plan", status: "completed" }]), null); + assert.equal(lastWaitingStep([]), null); + assert.equal(lastWaitingStep(undefined), null); +}); + +test("waitingPrompt returns the recorded instructions, else empty", () => { + assert.equal(waitingPrompt({ prompt: "Choose a path." }), "Choose a path."); + assert.equal(waitingPrompt({ prompt: 7 }), ""); + assert.equal(waitingPrompt({}), ""); + assert.equal(waitingPrompt(null), ""); +}); + +test("waitingOptions keeps string entries in recorded order, dropping malformed and blank", () => { + assert.deepEqual(waitingOptions({ options: ["approve", "reject"] }), ["approve", "reject"]); + assert.deepEqual(waitingOptions({ options: ["a", 3, null, " ", "b"] }), ["a", "b"]); + assert.deepEqual(waitingOptions({ options: "approve" }), []); + assert.deepEqual(waitingOptions({}), []); +}); + +test("humanOptions are a stage's non-error edges, sorted", () => { + assert.deepEqual(humanOptions({ publish: "#success", error: "#failure", revise: "review" }), [ + "publish", + "revise", + ]); + assert.deepEqual(humanOptions({}), []); + assert.deepEqual(humanOptions(undefined), []); +}); + +test("decisionTargetLabel resolves declared edges and is blank otherwise", () => { + assert.equal(decisionTargetLabel("publish", "publish"), "publish"); + assert.equal(decisionTargetLabel("publish", "#"), "SUCCESS"); + assert.equal(decisionTargetLabel("error", "#"), "FAILURE"); + assert.equal(decisionTargetLabel("approve", ""), ""); + assert.equal(decisionTargetLabel("approve", null), ""); + assert.equal(decisionTargetLabel("approve", undefined), ""); + assert.equal(optionTargetText("publish"), "→ publish"); + assert.equal(optionTargetText(""), ""); + assert.equal(optionTargetText(null), ""); +}); + +test("pendingDecision returns null unless the run is waiting", () => { + assert.equal(pendingDecision(null), null); + assert.equal(pendingDecision(run({ status: "failed" })), null); + assert.equal(pendingDecision(run({ status: "running", executing: true })), null); + assert.equal(pendingDecision(run({ status: "succeeded" })), null); +}); + +test("pendingDecision yields the recorded options in author order and the verbatim prompt", () => { + const decision = pendingDecision( + run({ + title: "Review the plan", + current_stage: "review", + steps: [ + { stage: "plan", status: "completed" }, + { + stage: "review", + status: "waiting", + output: { prompt: "Ship it or revise it?", options: ["revise", "approve"] }, + }, + ], + graph: { + stages: [ + { + key: "review", + prompt: "graph prompt", + edges: { approve: "publish", revise: "review", error: "#failure" }, + }, + ], + }, + }), + ); + assert.deepEqual(decision.options.map((o) => o.key), ["revise", "approve"]); + assert.equal(decision.instructions, "Ship it or revise it?"); + assert.equal(decision.stageKey, "review"); + assert.equal(decision.runId, 42); + assert.equal(decision.runLabel, "Review the plan"); + assert.deepEqual(decision.options, [ + { key: "revise", target: "review" }, + { key: "approve", target: "publish" }, + ]); +}); + +test("pendingDecision falls back to the pinned graph's sorted non-error edges", () => { + const decision = pendingDecision( + run({ + current_stage: "review", + steps: [{ stage: "", status: "waiting", output: {} }], + graph: { + stages: [ + { key: "review", prompt: "Graph instructions.", edges: { publish: "#success", error: "#failure", revise: "review" } }, + ], + }, + }), + ); + assert.deepEqual(decision.options.map((o) => o.key), ["publish", "revise"]); + assert.equal(decision.instructions, "Graph instructions."); + assert.equal(decision.stageKey, "review"); +}); + +test("pendingDecision keeps a recorded option whose edge is not declared, with a blank target", () => { + const decision = pendingDecision( + run({ + steps: [{ stage: "review", status: "waiting", output: { options: ["approve", "legacy"] } }], + graph: { stages: [{ key: "review", edges: { approve: "publish" } }] }, + }), + ); + assert.deepEqual(decision.options, [ + { key: "approve", target: "publish" }, + { key: "legacy", target: "" }, + ]); +}); + +test("pendingDecision is null when no option can be derived", () => { + assert.equal( + pendingDecision(run({ steps: [{ stage: "review", status: "waiting", output: {} }], graph: { stages: [] } })), + null, + ); +}); + +test("DecisionDraft: a blank selection cannot submit and selecting never sends", () => { + const blank = new DecisionDraft(); + assert.equal(blank.canSubmit, false); + const selected = blank.select("approve"); + assert.equal(selected.canSubmit, true); + assert.equal(selected.selected, "approve"); + // Selecting is pure: the original draft is untouched and no side effect fires. + assert.equal(blank.selected, null); + assert.equal(blank.canSubmit, false); + // Feedback is carried verbatim and never changes the submit rule. + const withFeedback = selected.withFeedback(" looks good "); + assert.equal(withFeedback.feedback, " looks good "); + assert.equal(withFeedback.canSubmit, true); + assert.equal(new DecisionDraft(" ").canSubmit, false); +}); + +test("canCancel is true only while executing; canRetry only for a failed, idle run", () => { + assert.equal(canCancel(run({ executing: true })), true); + assert.equal(canCancel(run({ executing: false })), false); + assert.equal(canCancel(null), false); + + assert.equal(canRetry(run({ status: "failed", executing: false })), true); + assert.equal(canRetry(run({ status: "failed", executing: true })), false); + assert.equal(canRetry(run({ status: "succeeded", executing: false })), false); + assert.equal(canRetry(run({ status: "waiting", executing: false })), false); + assert.equal(canRetry(null), false); + assert.equal(canRetry(undefined), false); +}); + +test("retryModes offers resume and restart for a retryable run, nothing otherwise", () => { + assert.deepEqual(retryModes(run({ status: "failed" })), ["resume", "restart"]); + assert.deepEqual(retryModes(run({ status: "succeeded" })), []); + assert.deepEqual(retryModes(run({ status: "failed", executing: true })), []); +}); + +test("retryRequestKey is unique, prefixed and within the server's 128-character bound", () => { + const key = retryRequestKey(440, 1_700_000_000_000, () => 0.5); + assert.match(key, /^web-retry-440-1700000000000-/); + assert.ok(key.length <= 128, `key too long: ${key.length}`); + assert.notEqual( + retryRequestKey(440, 1, () => 0.1), + retryRequestKey(440, 1, () => 0.2), + ); +}); + +test("the decision/action copy matches the Android sources verbatim", () => { + assert.equal(DECISION_CARD_TITLE, "Waiting for your decision"); + assert.equal(DECISION_ACTION, "Decide"); + assert.equal(FEEDBACK_LABEL, "Feedback (optional)"); + assert.equal(DECISION_CANCEL, "Cancel"); + assert.equal(DECISION_CONFIRM, "Confirm decision"); + assert.equal(DECISION_SENDING, "Sending…"); + assert.equal(cancelDialogTitle(440), "Cancel run 440?"); + assert.equal(CANCEL_DIALOG_MESSAGE, "This asks the server to stop the active run."); + assert.equal(CANCEL_CONFIRM, "Cancel run"); + assert.equal(retryDialogTitle(440), "Retry run 440?"); + assert.equal( + RETRY_DIALOG_MESSAGE, + "Only failed runs can be retried. The server starts a new run from the same input.", + ); + assert.equal(RETRY_CONFIRM, "Retry"); + assert.equal(DISMISS_KEEP, "Keep"); + assert.equal(RESTART_CONFIRM, "Restart from start"); + assert.ok(RESTART_DIALOG_MESSAGE.includes("replays the whole pipeline")); + assert.ok(RESTART_DIALOG_MESSAGE.includes("instead of resuming the failed stage")); + assert.equal(restartDialogTitle(440), "Restart run 440?"); + assert.equal(ACTION_FAILED_TITLE, "Action failed"); + assert.equal(ACTION_FAILED_OK, "OK"); +}); + +test("the decision card and sheet meta/title render the app's exact shapes", () => { + const decision = { runId: 12, runLabel: "Ship it", stageKey: "review" }; + assert.equal(decisionCardMeta(decision), "review · run 12 · Ship it"); + assert.equal(decisionSheetTitle(decision.stageKey), "Decide review"); + assert.equal(decisionSheetMeta(decision), "run 12 · Ship it"); +}); diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs index 1b560c5e..6d414c94 100644 --- a/web/test/repository.test.mjs +++ b/web/test/repository.test.mjs @@ -104,3 +104,130 @@ test("validate throws when the reply has no graph", async () => { ws.reply = (frame) => ({ id: frame.id, type: "validated" }); await assert.rejects(() => repo.validate("empty"), ProtocolError); }); + +test("search sends exactly {type:'search',search:{query,kind:'',limit:0}} and returns search_results", async () => { + const { repo, ws } = connected(); + const payload = { query: "release", results: [{ kind: "run" }], cap: 50, scanned_steps: 3 }; + ws.reply = (frame) => ({ id: frame.id, type: "search_results", search_results: payload }); + + const reply = await repo.search("release"); + assert.deepEqual(lastFrame(ws), { + type: "search", + search: { query: "release", kind: "", limit: 0 }, + }); + assert.deepEqual(reply, payload); +}); + +test("search sends the selected kind verbatim and never a limit above the cap", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "search_results", search_results: { results: [] } }); + + await repo.search("release", "run"); + const { search } = lastFrame(ws); + assert.deepEqual(search, { query: "release", kind: "run", limit: 0 }); + // limit 0 asks for the server's own default (SearchDefaultLimit 50); the client + // never asks for more than SearchMaxLimit (200), let alone sends a larger value. + assert.ok(search.limit <= 200); +}); + +test("search returns null when an older server replies without search_results", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "pong" }); + assert.equal(await repo.search("release"), null); +}); + +test("search surfaces an explicit server error with the server's own text", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: search" }); + await assert.rejects(() => repo.search("release"), { + name: "ProtocolError", + message: "unknown command: search", + }); +}); +/** The run detail a run.action reply carries in these tests. */ +const RUN_DETAIL = { id: 440, status: "failed" }; + +test("decideRun sends exactly {type:'decide_run',run_id,option,feedback} and returns the run detail", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL }); + + const detail = await repo.decideRun(440, { stage: "review", option: "approve", feedback: " yes " }); + assert.deepEqual(lastFrame(ws), { + type: "decide_run", + run_id: 440, + stage: "review", + option: "approve", + feedback: "yes", + }); + assert.deepEqual(detail, RUN_DETAIL); +}); + +test("decideRun omits a blank stage and blank feedback", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL }); + + await repo.decideRun(12, { stage: " ", option: "publish", feedback: " " }); + assert.deepEqual(lastFrame(ws), { type: "decide_run", run_id: 12, option: "publish" }); +}); + +test("cancelRun sends exactly {type:'cancel_run',run_id} and returns the run detail", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL }); + + const detail = await repo.cancelRun(440); + assert.deepEqual(lastFrame(ws), { type: "cancel_run", run_id: 440 }); + assert.deepEqual(detail, RUN_DETAIL); +}); + +test("retryRun always sends request_key and omits retry_mode for the default resume", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run_started", run_detail: RUN_DETAIL }); + + await repo.retryRun(440, { requestKey: "key-1" }); + assert.deepEqual(lastFrame(ws), { type: "retry_run", run_id: 440, request_key: "key-1" }); +}); + +test("retryRun sends retry_mode only for an explicit restart", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run_started", run_detail: RUN_DETAIL }); + + await repo.retryRun(440, { mode: "restart", requestKey: "key-2" }); + assert.deepEqual(lastFrame(ws), { + type: "retry_run", + run_id: 440, + request_key: "key-2", + retry_mode: "restart", + }); +}); + +test("setRunTitle sends exactly {type:'set_run_title',run_id,title} and returns the run detail", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run", run_detail: RUN_DETAIL }); + + const detail = await repo.setRunTitle(440, "New title"); + assert.deepEqual(lastFrame(ws), { type: "set_run_title", run_id: 440, title: "New title" }); + assert.deepEqual(detail, RUN_DETAIL); +}); + +test("each run action rejects a server error envelope instead of returning a detail", async () => { + const calls = [ + (repo) => () => repo.decideRun(440, { option: "approve" }), + (repo) => () => repo.cancelRun(440), + (repo) => () => repo.retryRun(440, { requestKey: "key-3" }), + (repo) => () => repo.setRunTitle(440, ""), + ]; + for (const makeCall of calls) { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "error", error: "a title with usable text is required" }); + await assert.rejects(makeCall(repo), { + name: "ProtocolError", + message: "a title with usable text is required", + }); + } +}); + +test("a run action throws when the reply has no run detail", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "run" }); + await assert.rejects(() => repo.cancelRun(7), ProtocolError); +}); diff --git a/web/test/search.test.mjs b/web/test/search.test.mjs new file mode 100644 index 00000000..53377cf9 --- /dev/null +++ b/web/test/search.test.mjs @@ -0,0 +1,519 @@ +// Pure omni-search tests: the per-kind row text, the in-hand narrowing and +// ordering, the routing target/tab resolution, the debounce/stale-token sequencer +// and the failure copy. Everything here is DOM-free and needs no server, mirroring +// android/.../ui/OmniSearchResultsTest.kt and OmniSearchTest.kt. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { + DEFAULT_SEARCH_KIND, + DEFAULT_SEARCH_SORT, + SEARCH_KINDS, + SEARCH_SORTS, + SEARCH_UNSUPPORTED, + SearchSequencer, + filterSearchResults, + resolveRunTarget, + searchControlsSummary, + searchFailureText, + searchFieldTab, + searchKindLabel, + searchPanelBody, + searchPanelEmptyMessage, + searchPanelProgress, + searchQuerySendable, + searchResultKindLabel, + searchRow, + searchTarget, + snippetSpans, + sortSearchResults, +} from "../src/search.js"; + +const UTC = { timeZone: "UTC" }; + +// --------------------------------------------------------------------------- +// Fixtures — the same shapes the Android test uses +// --------------------------------------------------------------------------- + +function pipelineHit(overrides = {}) { + return { + kind: "pipeline", + target: "pipeline:7", + pipeline: { id: 7, name: "release", version: 3, stages: 4, ...overrides }, + }; +} + +function versionHit(overrides = {}) { + return { + kind: "version", + target: "pipeline:9:v2", + version: { + pipeline_id: 9, + version: 2, + content_hash: "abc", + created_at: "2026-01-01T00:00:00Z", + ...overrides, + }, + }; +} + +function runHit(overrides = {}) { + return { + kind: "run", + target: "run:11", + run: { + id: 11, + pipeline_name: "release", + status: "succeeded", + created_at: "2026-01-01T00:00:00Z", + ...overrides, + }, + }; +} + +function stepHit(overrides = {}) { + return { + kind: "step", + target: "run:11:4", + step: { run_id: 11, sequence: 4, stage: "builder", visit: 2, outcome: "success", ...overrides }, + }; +} + +function fieldHit(overrides = {}, matchedField = "output") { + return { + kind: "field", + target: "run:11:4:output", + matched_field: matchedField, + field: { + run_id: 11, + sequence: 4, + field: "output", + snippet: "the release is ready", + ...overrides, + }, + }; +} + +function artifactHit(overrides = {}) { + return { + kind: "artifact", + target: "/artifacts/11/4/notes.md", + artifact: { + run_id: 11, + sequence: 4, + name: "notes.md", + content_type: "text/markdown", + size_bytes: 2048, + url: "/artifacts/11/4/notes.md", + ...overrides, + }, + }; +} + +// --------------------------------------------------------------------------- +// Kind/sort vocabulary +// --------------------------------------------------------------------------- + +test("the kind options are exactly the server vocabulary, All kinds first", () => { + assert.deepEqual( + SEARCH_KINDS.map((option) => [option.value, option.label]), + [ + ["", "All kinds"], + ["pipeline", "Pipelines"], + ["run", "Runs"], + ["step", "Steps"], + ["field", "Fields"], + ["artifact", "Artifacts"], + ["version", "Versions"], + ], + ); + assert.equal(DEFAULT_SEARCH_KIND, ""); + assert.deepEqual( + SEARCH_SORTS.map((option) => [option.value, option.label]), + [ + ["relevance", "Relevance"], + ["newest", "Newest first"], + ["name", "Name"], + ], + ); + assert.equal(DEFAULT_SEARCH_SORT, "relevance"); + // A stale/unknown value falls back rather than inventing an option. + assert.equal(searchKindLabel("prompts"), "All kinds"); + assert.equal(searchKindLabel("run"), "Runs"); +}); + +// --------------------------------------------------------------------------- +// Row text +// --------------------------------------------------------------------------- + +test("pipeline rows carry the name (or the id fallback) and the version/stage line", () => { + assert.deepEqual(searchRow(pipelineHit(), "release", UTC), { + title: "release", + secondary: "pipeline 7 · v3 · 4 stages", + snippet: null, + }); + const blank = searchRow(pipelineHit({ name: " " }), "release", UTC); + assert.equal(blank.title, "pipeline 7"); + // The stage count keeps the app's singular form. + assert.equal(searchRow(pipelineHit({ stages: 1 }), "", UTC).secondary, "pipeline 7 · v3 · 1 stage"); +}); + +test("version rows name the pipeline/version and omit blank content parts", () => { + assert.deepEqual(searchRow(versionHit(), "release", UTC), { + title: "pipeline 9 · v2", + secondary: "content abc · 1 Jan 00:00", + snippet: null, + }); + const blankHash = searchRow(versionHit({ content_hash: " " }), "release", UTC); + assert.equal(blankHash.secondary, "1 Jan 00:00"); +}); + +test("run rows join the non-blank status, workspace and timestamp", () => { + assert.deepEqual(searchRow(runHit(), "release", UTC), { + title: "run #11 · release", + secondary: "succeeded · 1 Jan 00:00", + snippet: null, + }); + const withWorkspace = searchRow(runHit({ workspace: "/tmp/ws" }), "", UTC); + assert.equal(withWorkspace.secondary, "succeeded · /tmp/ws · 1 Jan 00:00"); + const unnamed = searchRow(runHit({ pipeline_name: "" }), "", UTC); + assert.equal(unnamed.title, "run #11"); +}); + +test("step rows carry outcome, route and the first non-blank diagnostic line", () => { + const withTarget = searchRow(stepHit({ target: "#success" }), "", UTC); + assert.deepEqual(withTarget, { + title: "run #11 · builder visit 2", + secondary: "success · → #success", + snippet: null, + }); + const withDiagnostic = searchRow( + stepHit({ diagnostic: "\n the first line\nsecond line" }), + "", + UTC, + ); + assert.equal(withDiagnostic.secondary, "success · the first line"); + // Every part blank: the sequence is the honest fallback. + const allBlank = searchRow(stepHit({ outcome: "", target: "", diagnostic: "" }), "", UTC); + assert.equal(allBlank.secondary, "step 4"); + // A blank stage falls back to the word "step". + assert.equal(searchRow(stepHit({ stage: "" }), "", UTC).title, "run #11 · step visit 2"); +}); + +test("field rows carry the server snippet with the matched query span", () => { + const row = searchRow(fieldHit(), "release", UTC); + assert.equal(row.title, "run #11 · step 4 · output"); + assert.equal(row.secondary, "the release is ready"); + assert.deepEqual(row.snippet, [ + { text: "the ", matched: false }, + { text: "release", matched: true }, + { text: " is ready", matched: false }, + ]); + // No occurrence: one unmatched run, never dropped text. + assert.deepEqual(searchRow(fieldHit(), "absent", UTC).snippet, [ + { text: "the release is ready", matched: false }, + ]); + // A blank field falls back to the word "field". + assert.equal(searchRow(fieldHit({ field: " " }), "release", UTC).title, "run #11 · step 4 · field"); +}); + +test("artifact rows join name, run, step, content type and human size", () => { + assert.deepEqual(searchRow(artifactHit(), "notes", UTC), { + title: "notes.md", + secondary: "run #11 · step 4 · text/markdown · 2.0 KiB", + snippet: null, + }); + assert.equal(searchRow(artifactHit({ name: "", content_type: "" }), "", UTC).title, "artifact"); +}); + +test("an unknown row is read-only and never dropped", () => { + const named = searchRow({ kind: "future_kind", target: "widget:7" }, "x", UTC); + assert.deepEqual(named, { + title: "widget:7", + secondary: 'kind "future_kind" · read-only', + snippet: null, + }); + const anonymous = searchRow({ kind: "", target: "" }, "x", UTC); + assert.deepEqual(anonymous, { title: "Unrecognised result", secondary: "read-only", snippet: null }); +}); + +test("snippetSpans splits only the first occurrence, case-insensitively", () => { + assert.deepEqual(snippetSpans("the Release notes mention it", "release"), [ + { text: "the ", matched: false }, + { text: "Release", matched: true }, + { text: " notes mention it", matched: false }, + ]); + // The FIRST occurrence is the emphasised one; a later one is left in the tail. + assert.deepEqual(snippetSpans("aXbXc", "x"), [ + { text: "a", matched: false }, + { text: "X", matched: true }, + { text: "bXc", matched: false }, + ]); + // A match at the very start/end needs no empty leading/trailing run. + assert.deepEqual(snippetSpans("release", "release"), [{ text: "release", matched: true }]); + assert.deepEqual(snippetSpans("nothing here", "release"), [{ text: "nothing here", matched: false }]); + assert.deepEqual(snippetSpans("nothing here", " "), [{ text: "nothing here", matched: false }]); + assert.deepEqual(snippetSpans("", "release"), []); +}); + +test("searchResultKindLabel names the kind in words, artifact by its content type", () => { + assert.equal(searchResultKindLabel(pipelineHit()), "Pipeline"); + assert.equal(searchResultKindLabel(versionHit()), "Pipeline version"); + assert.equal(searchResultKindLabel(runHit()), "Run"); + assert.equal(searchResultKindLabel(stepHit()), "Step"); + assert.equal(searchResultKindLabel(fieldHit()), "Field"); + assert.equal(searchResultKindLabel(artifactHit({ content_type: "text/markdown" })), "Document artifact"); + assert.equal( + searchResultKindLabel(artifactHit({ name: "shot.png", content_type: "image/png" })), + "Image artifact", + ); + assert.equal(searchResultKindLabel({ kind: "future_kind", target: "x" }), "Unrecognised result"); +}); + +// --------------------------------------------------------------------------- +// Kind filtering + in-hand sorting +// --------------------------------------------------------------------------- + +test("the kind filter narrows the list, and All kinds keeps it whole", () => { + const mixed = [pipelineHit(), runHit(), stepHit(), fieldHit(), artifactHit(), versionHit()]; + assert.deepEqual(filterSearchResults(mixed, ""), mixed); + assert.deepEqual(filterSearchResults(mixed, "run"), [mixed[1]]); + assert.deepEqual(filterSearchResults(mixed, "version"), [mixed[5]]); + assert.deepEqual(filterSearchResults(mixed, "nothing"), []); +}); + +function hitWithRecency(kind, recency) { + return { kind, target: `${kind}:1`, recency }; +} + +test("Relevance keeps the server's ranking untouched", () => { + const ordered = [ + hitWithRecency("run", "2026-01-01T00:00:00Z"), + hitWithRecency("pipeline", "2026-03-01T00:00:00Z"), + ]; + assert.deepEqual(sortSearchResults(ordered, "relevance"), ordered); + assert.deepEqual(sortSearchResults(ordered, "stale-sort-value"), ordered); +}); + +test("Newest first orders by parsed recency, descending", () => { + const older = hitWithRecency("run", "2026-01-01T00:00:00Z"); + const newer = hitWithRecency("pipeline", "2026-03-01T00:00:00Z"); + assert.deepEqual(sortSearchResults([older, newer], "newest"), [newer, older]); +}); + +test("Newest first keeps ties stable, and puts a missing/invalid recency last", () => { + const first = hitWithRecency("run", "2026-01-01T00:00:00Z"); + const second = hitWithRecency("pipeline", "2026-01-01T00:00:00Z"); + assert.deepEqual(sortSearchResults([first, second], "newest"), [first, second]); + + const dated = hitWithRecency("run", "2026-01-01T00:00:00Z"); + const undated = hitWithRecency("run", null); + const invalid = hitWithRecency("run", "not-a-date"); + assert.deepEqual(sortSearchResults([undated, invalid, dated], "newest"), [dated, undated, invalid]); +}); + +test("Name orders by the displayed title, case-insensitively, with ties stable", () => { + const alpha1 = pipelineHit({ id: 1, name: "alpha" }); + const beta = pipelineHit({ id: 2, name: "Beta" }); + const alpha2 = pipelineHit({ id: 3, name: "ALPHA" }); + assert.deepEqual(sortSearchResults([beta, alpha1, alpha2], "name"), [alpha1, alpha2, beta]); +}); + +// --------------------------------------------------------------------------- +// Summary + empty state +// --------------------------------------------------------------------------- + +test("the controls summary is exactly {Kind} · {Sort}, with no (in hand) suffix", () => { + assert.equal(searchControlsSummary("", "relevance"), "All kinds · Relevance"); + assert.equal(searchControlsSummary("run", "newest"), "Runs · Newest first"); + assert.equal(searchControlsSummary("field", "name"), "Fields · Name"); + assert.equal(searchControlsSummary("bogus", "bogus"), "All kinds · Relevance"); +}); + +test("the empty state names the query and the active filter, or nothing", () => { + const empty = { query: "release", loading: false, error: "" }; + assert.equal(searchPanelEmptyMessage(empty, [], ""), 'No matches for "release".'); + assert.equal(searchPanelEmptyMessage(empty, [], "run"), 'No runs match "release".'); + assert.equal(searchPanelEmptyMessage(empty, [], "version"), 'No versions match "release".'); + // Rows shown, still loading, a blank query or an error: no message at all. + assert.equal(searchPanelEmptyMessage(empty, [runHit()], ""), null); + assert.equal(searchPanelEmptyMessage({ ...empty, loading: true }, [], ""), null); + assert.equal(searchPanelEmptyMessage({ query: " " }, [], ""), null); + assert.equal(searchPanelEmptyMessage({ ...empty, error: "boom" }, [], ""), null); +}); + +test("a blank or whitespace query is never sent to the server", () => { + assert.equal(searchQuerySendable(""), false); + assert.equal(searchQuerySendable(" "), false); + assert.equal(searchQuerySendable(undefined), false); + assert.equal(searchQuerySendable("plan"), true); + assert.equal(searchQuerySendable(" plan "), true); +}); + +test("the refresh bar shows only when results are retained while a newer query loads", () => { + assert.equal(searchPanelProgress({ loading: true, results: [runHit()] }), true); + assert.equal(searchPanelProgress({ loading: true, results: [] }), false); + assert.equal(searchPanelProgress({ loading: false, results: [runHit()] }), false); + assert.equal(searchPanelProgress({}), false); +}); + +test("the panel body reports an error first, then rows, Searching…, the empty line or nothing", () => { + const loading = { query: "plan", loading: true, results: [], error: "" }; + // The first load, nothing yet: the searching row. + assert.deepEqual(searchPanelBody(loading, [], ""), { kind: "searching", message: "" }); + // A retained result set is still shown while a refresh is in flight. + const refresh = { query: "plan", loading: true, results: [runHit()], error: "" }; + assert.deepEqual(searchPanelBody(refresh, [runHit()], ""), { kind: "results", message: "" }); + // An error takes precedence over results. + assert.deepEqual(searchPanelBody({ ...refresh, error: "boom" }, [runHit()], ""), { + kind: "error", + message: "boom", + }); + // A landed, empty reply: the empty-state sentence, naming the kind when set. + const landed = { query: "plan", loading: false, results: [], error: "" }; + assert.deepEqual(searchPanelBody(landed, [], ""), { kind: "empty", message: 'No matches for "plan".' }); + assert.deepEqual(searchPanelBody(landed, [], "run"), { + kind: "empty", + message: 'No runs match "plan".', + }); + // A blank query, or a filter that emptied a list while a refresh is in flight: + // nothing at all. + assert.deepEqual(searchPanelBody({ query: " ", loading: false }, [], ""), { kind: "idle", message: "" }); + assert.deepEqual(searchPanelBody(refresh, [], "run"), { kind: "idle", message: "" }); +}); + +// --------------------------------------------------------------------------- +// Routing target + tab resolution +// --------------------------------------------------------------------------- + +test("pipeline and version hits open the pipeline detail (version 0 = latest)", () => { + assert.deepEqual(searchTarget(pipelineHit()), { kind: "pipeline", pipelineId: 7, version: 3 }); + assert.deepEqual(searchTarget(pipelineHit({ version: 0 })), { + kind: "pipeline", + pipelineId: 7, + version: 0, + }); + assert.deepEqual(searchTarget(versionHit()), { kind: "pipeline", pipelineId: 9, version: 2 }); +}); + +test("run, step, field and artifact hits open runs", () => { + assert.deepEqual(searchTarget(runHit()), { kind: "run", runId: 11, sequence: 0, matchedField: "" }); + assert.deepEqual(searchTarget(stepHit()), { kind: "run", runId: 11, sequence: 4, matchedField: "" }); + assert.deepEqual(searchTarget(fieldHit({}, "output")), { + kind: "run", + runId: 11, + sequence: 4, + matchedField: "output", + }); + assert.deepEqual(searchTarget(artifactHit()), { kind: "run", runId: 11, sequence: 4, matchedField: "" }); +}); + +test("an unknown result has no target and is never navigated", () => { + assert.equal(searchTarget({ kind: "future_kind", target: "widget:7" }), null); +}); + +test("the matched field resolves the run-detail tab, everything else Summary", () => { + assert.equal(searchFieldTab("input"), "input"); + assert.equal(searchFieldTab("output"), "output"); + assert.equal(searchFieldTab("transcript"), "summary"); + assert.equal(searchFieldTab("evidence"), "summary"); + assert.equal(searchFieldTab("other"), "summary"); + assert.equal(searchFieldTab(""), "summary"); + assert.equal(searchFieldTab(undefined), "summary"); +}); + +const STEPS = [ + { sequence: 1, stage: "planner" }, + { sequence: 2, stage: "builder" }, + { sequence: 3, stage: "builder" }, +]; + +test("a text-match target resolves to the run-detail tab holding it", () => { + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "input" }, 11, STEPS), { + tab: "input", + }); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "output" }, 11, STEPS), { + tab: "output", + }); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, matchedField: "transcript" }, 11, STEPS), { + tab: "summary", + }); +}); + +test("a step/artifact target resolves the visit index within its stage, not the visit number", () => { + // "builder" recorded two visits; sequence 3 is its second, index 1. + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 3 }, 11, STEPS), { + stageKey: "builder", + visitIndex: 1, + }); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 2 }, 11, STEPS), { + stageKey: "builder", + visitIndex: 0, + }); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 1 }, 11, STEPS), { + stageKey: "planner", + visitIndex: 0, + }); +}); + +test("a bare run target or a visit that cannot be located falls back to the run detail", () => { + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 0 }, 11, STEPS), {}); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 99 }, 11, STEPS), {}); + assert.deepEqual(resolveRunTarget(null, 11, STEPS), {}); + assert.deepEqual(resolveRunTarget({ kind: "run", runId: 11, sequence: 1 }, 11, []), {}); +}); + +// --------------------------------------------------------------------------- +// Debounce + stale-reply sequencing +// --------------------------------------------------------------------------- + +test("a burst of keystrokes collapses to one request for the last query", () => { + const sequencer = new SearchSequencer(); + const first = sequencer.edit("r"); + const second = sequencer.edit("re"); + const third = sequencer.edit("rel"); + assert.equal(sequencer.begin(first), null); + assert.equal(sequencer.begin(second), null); + assert.deepEqual(sequencer.begin(third), { token: third.token, query: "rel" }); +}); + +test("only the newest recorded edit is accepted, so a stale reply can never land", () => { + const sequencer = new SearchSequencer(); + const sentOld = sequencer.begin(sequencer.edit("old")); + // A keystroke while the old reply is in flight invalidates it immediately. + const next = sequencer.edit("new"); + assert.equal(sequencer.accepts(sentOld.token), false); + const sentNew = sequencer.begin(next); + assert.equal(sequencer.accepts(sentNew.token), true); + // A token that was never recorded is not accepted either. + assert.equal(sequencer.accepts(sentNew.token + 100), false); + // Closing records an empty edit, which invalidates the in-flight reply too. + sequencer.edit(""); + assert.equal(sequencer.accepts(sentNew.token), false); +}); + +test("Enter sends the current query at once, skipping the debounce", () => { + const sequencer = new SearchSequencer(); + sequencer.edit("release"); + const sent = sequencer.begin(sequencer.edit("release")); + assert.deepEqual(sent, { token: sent.token, query: "release" }); + assert.equal(sequencer.accepts(sent.token), true); +}); + +// --------------------------------------------------------------------------- +// Failure copy +// --------------------------------------------------------------------------- + +test("a missing payload or an unknown command reports the unsupported sentence", () => { + assert.equal(searchFailureText(null), SEARCH_UNSUPPORTED); + assert.equal(searchFailureText(undefined), SEARCH_UNSUPPORTED); + assert.equal(searchFailureText(new Error("")), SEARCH_UNSUPPORTED); + assert.equal(searchFailureText(new Error("unknown command: search")), SEARCH_UNSUPPORTED); + assert.equal(searchFailureText(new Error("unsupported command")), SEARCH_UNSUPPORTED); +}); + +test("any other failure carries the server's own text", () => { + assert.equal(searchFailureText(new Error("boom")), "boom"); + assert.equal(searchFailureText(new Error("request timed out after 30000ms")), "request timed out after 30000ms"); + assert.equal(searchFailureText("plain string"), "plain string"); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 94768982..4b3d9998 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -90,6 +90,17 @@ async function openRunDetail(runId) { await page.waitForSelector(row, { timeout: 20000 }); await page.click(row); await page.waitForSelector(".detail .detail-tabs", { timeout: 20000 }); + // The tabstrip already exists from the previously opened run, so it is not + // proof this run's detail loaded. Wait for this run's own identity line + // (`run {id} · …`) before returning, or the next assertion can read the + // previous run's actions. + await eventually( + () => + page.evaluate( + `document.querySelector(".run-detail .run-identity")?.textContent?.startsWith("run ${runId} ") ?? false`, + ), + { timeout: 20000, what: `run ${runId}'s detail to load` }, + ); return; } catch (error) { if (attempt === 1) throw error; @@ -98,6 +109,74 @@ async function openRunDetail(runId) { } } +// --- Omni-search (S1/S2) --------------------------------------------------- +// The page's own search UI drives every one of the helpers below; nothing is +// stubbed. `searchTargets` opens the panel (if it is not already open), types the +// query, applies the kind filter and returns the `data-target` of every row of +// that kind once one has rendered. + +async function searchTargets(query, kind) { + await ensureConnected(); + if (!(await page.evaluate(`!!document.querySelector("#searchInput")`))) { + await page.click("#searchToggle"); + await page.waitForSelector("#searchInput", { timeout: 15000 }); + } + await page.fill("#searchInput", query); + await page.evaluate(`(() => { + const select = document.querySelector("#searchKind"); + select.value = ${JSON.stringify(kind)}; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await eventually( + () => + page.evaluate( + `[...document.querySelectorAll("#searchResults .search-row")].some((r) => r.dataset.kind === ${JSON.stringify(kind)})`, + ), + { timeout: 25000, what: `a ${kind} search result` }, + ); + return page.evaluate( + `[...document.querySelectorAll("#searchResults .search-row")] + .filter((r) => r.dataset.kind === ${JSON.stringify(kind)}) + .map((r) => r.dataset.target ?? "")`, + ); +} + +/** + * Click one search row by its exact data-target; routing closes the panel. The + * lookup and the click happen in one evaluate so a reply landing between them + * cannot replace the row first. This drives the row's own click handler, exactly + * as a mouse click would. + */ +async function clickSearchTarget(target) { + return page.evaluate(`(() => { + const row = [...document.querySelectorAll("#searchResults .search-row")] + .find((r) => (r.dataset.target ?? "") === ${JSON.stringify(target)}); + if (!row) return false; + row.click(); + return true; + })()`); +} + +/** + * Route candidate rows of `kind` until the expected destination renders (routing + * always closes the panel, so each attempt reopens and re-queries). Live data can + * change between runs, so up to `attempts` rows are tried before giving up; + * returns the target that landed or null. + */ +async function routeSearchKind(query, kind, landed, attempts = 4) { + const targets = await searchTargets(query, kind); + for (const target of targets.slice(0, attempts)) { + await searchTargets(query, kind); + if (!(await clickSearchTarget(target))) continue; + if (await landed()) return target; + await page.evaluate(`document.querySelector(".stage-pane-back")?.click()`); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + }).catch(() => {}); + } + return null; +} + // The mounted graph's current transform, read back so the pan/zoom clamp checks // assert the real rendered state rather than a claim. const graphState = () => @@ -1545,6 +1624,526 @@ try { shots.push(await page.screenshot(`${out}/34-run-${pendingRunId}-changes-pending.png`)); } + // S1/S2: omni-search over the real server. The panel is opened from the top + // bar; the query is typed through the page's own field, the flat result list + // and its controls are asserted, a kind filter is applied and captured, and one + // result of each kind is routed to its real destination. Every capture below is + // a real screenshot of the rendered page. + step("opening omni-search from the top bar (S1)"); + await ensureConnected(); + await page.clickText("nav.tabs button.tab", "Runs"); + await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); + const viewSnapshot = () => + page.evaluate(`(() => ({ + tab: document.querySelector("nav.tabs button.tab.active")?.textContent ?? "", + detail: document.querySelector("#content .detail h2")?.textContent ?? "", + }))()`); + const beforeOpen = await viewSnapshot(); + await page.click("#searchToggle"); + await page.waitForSelector("#searchInput", { timeout: 15000 }); + const chrome = await page.evaluate(`(() => { + const input = document.querySelector("#searchInput"); + return { + placeholder: input?.getAttribute("placeholder") ?? "", + autofocused: document.activeElement === input, + close: document.querySelector("#searchClose")?.textContent ?? "", + }; + })()`); + if (chrome.placeholder !== "Search pipelines, runs and artifacts") { + throw new Error(`search placeholder is wrong: ${chrome.placeholder}`); + } + if (!chrome.autofocused) throw new Error("the search field was not autofocused on open"); + if (chrome.close !== "Close search") throw new Error(`the close control is wrong: ${chrome.close}`); + const afterOpen = await viewSnapshot(); + if (afterOpen.tab !== beforeOpen.tab || afterOpen.detail !== beforeOpen.detail) { + throw new Error(`opening search changed the view: ${JSON.stringify({ beforeOpen, afterOpen })}`); + } + console.log( + ` field autofocused, placeholder "${chrome.placeholder}", "${chrome.close}" present; view stayed ${afterOpen.tab}`, + ); + + const SEARCH_QUERY = "plan"; + step(`running a real query ("${SEARCH_QUERY}") and capturing the flat result list (S1)`); + await page.fill("#searchInput", SEARCH_QUERY); + await page.waitForSelector("#searchResults .search-row", { timeout: 25000 }); + const list = await page.evaluate(`(() => ({ + kinds: [...document.querySelectorAll("#searchKind option")].map((o) => o.textContent), + sorts: [...document.querySelectorAll("#searchSort option")].map((o) => o.textContent), + kindValue: document.querySelector("#searchKind")?.value ?? "", + sortValue: document.querySelector("#searchSort")?.value ?? "", + summary: document.querySelector("#searchSummary")?.textContent ?? "", + clear: document.querySelector("#searchClearFilter")?.textContent ?? "", + rows: document.querySelectorAll("#searchResults .search-row").length, + headers: document.querySelectorAll("#searchResults h1, #searchResults h2, #searchResults h3").length, + kindsPresent: [...new Set([...document.querySelectorAll("#searchResults .search-row")].map((r) => r.dataset.kind))], + matchedSpans: document.querySelectorAll("#searchResults .search-match").length, + }))()`); + if ( + JSON.stringify(list.kinds) !== + JSON.stringify(["All kinds", "Pipelines", "Runs", "Steps", "Fields", "Artifacts", "Versions"]) + ) { + throw new Error(`kind options are wrong: ${list.kinds.join(",")}`); + } + if (JSON.stringify(list.sorts) !== JSON.stringify(["Relevance", "Newest first", "Name"])) { + throw new Error(`sort options are wrong: ${list.sorts.join(",")}`); + } + if (list.kindValue !== "" || list.sortValue !== "relevance") { + throw new Error(`the default controls are wrong: kind=${list.kindValue} sort=${list.sortValue}`); + } + if (list.summary !== "All kinds · Relevance") throw new Error(`the summary line is wrong: ${list.summary}`); + if (list.clear !== "Clear filter") throw new Error(`the reset control is wrong: ${list.clear}`); + if (!list.rows) throw new Error("the query rendered no result rows"); + if (list.headers !== 0) throw new Error("the result list carries grouping headers, not a flat list"); + if (list.kindsPresent.length < 2) { + throw new Error(`the query returned only ${list.kindsPresent.join(",")}, expected a mixed list`); + } + console.log( + ` ${list.rows} flat rows across ${list.kindsPresent.join(",")}; summary "${list.summary}"; ` + + `${list.matchedSpans} emphasised snippet span(s)`, + ); + await page.rect("#searchPanel"); + await shot("01-search-results.png"); + + step("applying a kind filter and capturing it (S1)"); + await page.evaluate(`(() => { + const select = document.querySelector("#searchKind"); + select.value = "pipeline"; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await eventually( + () => + page.evaluate(`(() => { + const rows = [...document.querySelectorAll("#searchResults .search-row")]; + return rows.length > 0 && rows.every((r) => r.dataset.kind === "pipeline"); + })()`), + { timeout: 25000, what: "the kind filter to narrow the list to pipelines" }, + ); + const filteredSummary = await text("#searchSummary"); + if (filteredSummary !== "Pipelines · Relevance") { + throw new Error(`the filtered summary is wrong: ${filteredSummary}`); + } + const filteredRows = await page.evaluate(`document.querySelectorAll("#searchResults .search-row").length`); + console.log(` Pipelines filter: ${filteredRows} row(s), summary "${filteredSummary}"`); + await page.rect("#searchPanel"); + await shot("02-search-kind-filter.png"); + + step("Clear filter returns the kind to All kinds"); + await page.click("#searchClearFilter"); + await eventually(async () => (await text("#searchSummary")) === "All kinds · Relevance", { + timeout: 15000, + what: "Clear filter to reset the kind", + }); + console.log(' Clear filter reset the kind to "All kinds"'); + + step("a Fields filter emphasises the matched snippet in the page, never as markup (S1)"); + await page.evaluate(`(() => { + const select = document.querySelector("#searchKind"); + select.value = "field"; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await eventually( + () => page.evaluate(`!!document.querySelector("#searchResults .search-row .search-match")`), + { timeout: 25000, what: "an emphasised snippet span" }, + ); + const emphasis = await page.evaluate(`(() => { + const node = document.querySelector("#searchResults .search-row .search-match"); + return { + tag: node?.tagName ?? "", + inner: node?.firstElementChild?.tagName ?? "", + text: node?.textContent ?? "", + kind: node?.closest(".search-row")?.dataset.kind ?? "", + }; + })()`); + if (emphasis.tag !== "STRONG" || emphasis.inner !== "U") { + throw new Error(`the matched span is not : ${JSON.stringify(emphasis)}`); + } + if (!emphasis.text) throw new Error("the emphasised span carries no text"); + if (emphasis.kind !== "field") throw new Error(`the emphasis is not on a field hit: ${emphasis.kind}`); + console.log(` matched snippet emphasised as <${emphasis.tag}><${emphasis.inner}>: "${emphasis.text}"`); + // Back to every kind for the routing steps. + await page.evaluate(`(() => { + const select = document.querySelector("#searchKind"); + select.value = ""; + select.dispatchEvent(new Event("change", { bubbles: true })); + })()`); + await eventually(() => page.evaluate(`!!document.querySelector("#searchResults .search-row")`), { + timeout: 25000, + what: "the unfiltered list", + }); + + step("routing a pipeline hit to its detail (S2)"); + const pipelineTarget = await routeSearchKind(SEARCH_QUERY, "pipeline", async () => { + await page.waitForSelector("#content .detail h2", { timeout: 25000 }); + await page.waitForSelector("#content .detail .monospace", { timeout: 25000 }); + return true; + }); + if (!pipelineTarget) throw new Error("no pipeline result routed to a pipeline detail"); + const pipelineView = await page.evaluate(`(() => ({ + active: document.querySelector("nav.tabs button.tab.active")?.textContent ?? "", + title: document.querySelector("#content .detail h2")?.textContent ?? "", + searchOpen: !!document.querySelector("#searchInput"), + }))()`); + if (!pipelineView.active.startsWith("Pipelines")) { + throw new Error(`a pipeline hit landed on ${pipelineView.active}`); + } + if (!pipelineView.title) throw new Error("the routed pipeline detail has no heading"); + if (pipelineView.searchOpen) throw new Error("selecting a result did not close the search panel"); + console.log(` ${pipelineTarget} -> Pipelines detail "${pipelineView.title}"`); + await page.rect("#content .detail"); + await shot("03-search-route-pipeline.png"); + + step("routing a run hit to its detail (S2)"); + const runTarget = await routeSearchKind(SEARCH_QUERY, "run", async () => { + await eventually( + () => + page.evaluate(`(() => { + const tab = document.querySelector("nav.tabs button.tab.active")?.textContent ?? ""; + return tab.startsWith("Runs") && !!document.querySelector("#content .detail .detail-tabs"); + })()`), + { timeout: 25000, what: "the routed run detail" }, + ); + return true; + }); + if (!runTarget) throw new Error("no run result routed to a run detail"); + const runView = await page.evaluate(`(() => ({ + active: document.querySelector("nav.tabs button.tab.active")?.textContent ?? "", + title: document.querySelector("#content .detail h2")?.textContent ?? "", + tabs: [...document.querySelectorAll("#content .detail .detail-tabs .detail-tab")].map((n) => n.textContent), + }))()`); + if (!runView.active.startsWith("Runs")) throw new Error(`a run hit landed on ${runView.active}`); + if (!runView.tabs.includes("Summary")) throw new Error(`the routed run detail has no tabs: ${runView.tabs}`); + console.log(` ${runTarget} -> Runs detail "${runView.title}" (${runView.tabs.join("/")})`); + await page.rect("#content .detail"); + await shot("04-search-route-run.png"); + + step("routing a field hit to the run-detail tab holding the match (S2)"); + const fieldTargets = await searchTargets(SEARCH_QUERY, "field"); + let fieldRoute = null; + for (const target of fieldTargets.slice(0, 4)) { + // data-target is run:{id}:{sequence}:{matchedField}. + const matchedField = target.split(":")[3] ?? ""; + const expectedTab = matchedField === "input" ? "Input" : matchedField === "output" ? "Output" : "Summary"; + await searchTargets(SEARCH_QUERY, "field"); + if (!(await clickSearchTarget(target))) continue; + const landed = await eventually( + () => + page.evaluate(`(() => { + const tab = document.querySelector("nav.tabs button.tab.active")?.textContent ?? ""; + const active = document.querySelector("#content .detail .detail-tabs .detail-tab.active")?.textContent ?? ""; + return tab.startsWith("Runs") && active === ${JSON.stringify(expectedTab)}; + })()`), + { timeout: 25000, what: `the ${expectedTab} run-detail tab` }, + ) + .then(() => true) + .catch(() => false); + if (landed) { + fieldRoute = { target, matchedField, expectedTab }; + break; + } + } + if (!fieldRoute) throw new Error("no field result opened the run-detail tab holding its match"); + console.log(` ${fieldRoute.target} (matched_field ${fieldRoute.matchedField}) -> ${fieldRoute.expectedTab} tab`); + await page.rect("#content .detail"); + await shot("05-search-route-field.png"); + + step("routing a step hit to the visit's stage pane (S2)"); + const stepTarget = await routeSearchKind(SEARCH_QUERY, "step", async () => { + await eventually(() => page.evaluate(`!!document.querySelector(".stage-pane")`), { + timeout: 20000, + what: "the routed visit stage pane", + }); + return true; + }); + if (!stepTarget) throw new Error("no step result opened a visit stage pane"); + const stepPane = await page.evaluate(`(() => ({ + title: document.querySelector(".stage-pane-title")?.textContent ?? "", + tab: document.querySelector("nav.tabs button.tab.active")?.textContent ?? "", + }))()`); + if (!stepPane.title) throw new Error("the routed stage pane named no stage"); + if (!stepPane.tab.startsWith("Runs")) throw new Error(`the step route landed on ${stepPane.tab}`); + console.log(` ${stepTarget} -> run stage pane "${stepPane.title}"`); + await page.rect(".stage-pane-sheet"); + await shot("06-search-route-step.png"); + await page.click(".stage-pane-back"); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + what: "the step stage pane to close", + }); + + step("routing an artifact hit to the same visit pane (S2)"); + const artifactTarget = await routeSearchKind(SEARCH_QUERY, "artifact", async () => { + await eventually(() => page.evaluate(`!!document.querySelector(".stage-pane")`), { + timeout: 20000, + what: "the routed artifact visit pane", + }); + return true; + }); + if (artifactTarget) { + const artifactPane = await page.evaluate( + `document.querySelector(".stage-pane-title")?.textContent ?? ""`, + ); + console.log(` ${artifactTarget} -> run stage pane "${artifactPane}"`); + await page.rect(".stage-pane-sheet"); + await shot("07-search-route-artifact.png"); + await page.click(".stage-pane-back"); + await eventually(() => page.evaluate(`!document.querySelector(".stage-pane")`), { + timeout: 5000, + what: "the artifact stage pane to close", + }); + } else { + console.log(" -- no artifact hit routed to a visit pane; skipped the artifact capture"); + } + + step("routing a version hit to its pipeline detail (S2)"); + const versionTarget = await routeSearchKind(SEARCH_QUERY, "version", async () => { + await eventually( + () => + page.evaluate(`(() => { + const tab = document.querySelector("nav.tabs button.tab.active")?.textContent ?? ""; + return tab.startsWith("Pipelines") && !!document.querySelector("#content .detail h2"); + })()`), + { timeout: 25000, what: "the pipeline detail for the version" }, + ); + return true; + }); + if (versionTarget) { + const versionTitle = await text("#content .detail h2"); + console.log(` ${versionTarget} -> Pipelines detail "${versionTitle}"`); + await page.rect("#content .detail"); + await shot("08-search-route-version.png"); + } else { + console.log(" -- no version hit routed; skipped the version capture"); + } + + step("Closing search clears the query and leaves the view intact (S1)"); + await searchTargets("release", "field"); + const beforeClose = await viewSnapshot(); + await page.click("#searchClose"); + await eventually(() => page.evaluate(`!document.querySelector("#searchInput")`), { + timeout: 10000, + what: "the search panel to close", + }); + const afterClose = await viewSnapshot(); + if (afterClose.tab !== beforeClose.tab || afterClose.detail !== beforeClose.detail) { + throw new Error(`closing search changed the view: ${JSON.stringify({ beforeClose, afterClose })}`); + } + await page.click("#searchToggle"); + await page.waitForSelector("#searchInput", { timeout: 15000 }); + const reopenedQuery = await page.evaluate(`document.querySelector("#searchInput")?.value ?? ""`); + if (reopenedQuery !== "") throw new Error(`closing search did not clear the query: "${reopenedQuery}"`); + await page.evaluate( + `document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))`, + ); + await eventually(() => page.evaluate(`!document.querySelector("#searchInput")`), { + timeout: 10000, + what: "Escape to close the search", + }); + console.log(" Close search cleared the query and kept the view; Escape also closed the field"); + + // R13/R14: the run-level actions on run 440 (failed, not executing). The + // Retry action is offered; Cancel is not. The Retry confirm and its secondary + // Restart-from-start confirm are captured and dismissed with Keep — no run is + // started here. The rename field is captured pre-filled, then a blank rename is + // actually sent: the live server refuses it without mutating anything, so the + // shared Action-failed dialog shows the server's own reason. + step("R13/R14: run 440 (failed) — Retry eligibility, restart confirm and the rename field"); + // The search block above leaves the routed detail (a Pipelines detail) on + // screen; R13/R14 needs the Runs list rendered before it can open run 440. + await page.clickText("nav.tabs button.tab", "Runs"); + await page.waitForSelector(".list.runs .run-row", { timeout: 25000 }); + await openRunDetail(440); + const actions440 = await page.evaluate(`(() => ({ + retry: !!document.querySelector(".run-detail .run-actions .retry-run"), + cancel: !!document.querySelector(".run-detail .run-actions .cancel-run"), + }))()`); + if (!actions440.retry) throw new Error("run 440 (failed, not executing) offered no Retry action"); + if (actions440.cancel) throw new Error("run 440 (not executing) must not offer a Cancel action"); + shots.push(await page.screenshot(`${out}/35-run-440-run-actions.png`)); + + step("R13: the Retry confirm — resume is the default, Restart from start is secondary"); + await page.click(".run-detail .run-actions .retry-run"); + await page.waitForSelector(".confirm-dialog.confirm-retry", { timeout: 15000 }); + const retryDialog = await page.evaluate(`(() => ({ + title: document.querySelector(".confirm-retry .confirm-title")?.textContent ?? "", + message: document.querySelector(".confirm-retry .confirm-message")?.textContent ?? "", + confirm: document.querySelector(".confirm-retry .confirm-accept")?.textContent ?? "", + dismiss: document.querySelector(".confirm-retry .confirm-dismiss")?.textContent ?? "", + secondary: document.querySelector(".confirm-retry .confirm-secondary")?.textContent ?? "", + }))()`); + if (retryDialog.title !== "Retry run 440?") throw new Error(`retry title: ${retryDialog.title}`); + if (retryDialog.message !== "Only failed runs can be retried. The server starts a new run from the same input.") { + throw new Error(`retry message: ${retryDialog.message}`); + } + if (retryDialog.confirm !== "Retry") throw new Error(`retry confirm: ${retryDialog.confirm}`); + if (retryDialog.dismiss !== "Keep") throw new Error(`retry dismiss: ${retryDialog.dismiss}`); + if (retryDialog.secondary !== "Restart from start") { + throw new Error(`retry secondary: ${retryDialog.secondary}`); + } + console.log(` retry dialog: "${retryDialog.title}" — ${retryDialog.message}`); + shots.push(await page.screenshot(`${out}/36-run-440-retry-confirm.png`)); + + step("R13: the Restart-from-start confirm states the whole-pipeline replay"); + await page.click(".confirm-retry .confirm-secondary"); + await page.waitForSelector(".confirm-dialog.confirm-restart", { timeout: 15000 }); + const restartDialog = await page.evaluate(`(() => ({ + title: document.querySelector(".confirm-restart .confirm-title")?.textContent ?? "", + message: document.querySelector(".confirm-restart .confirm-message")?.textContent ?? "", + confirm: document.querySelector(".confirm-restart .confirm-accept")?.textContent ?? "", + dismiss: document.querySelector(".confirm-restart .confirm-dismiss")?.textContent ?? "", + }))()`); + if (restartDialog.title !== "Restart run 440?") throw new Error(`restart title: ${restartDialog.title}`); + if (!restartDialog.message.includes("replays the whole pipeline")) { + throw new Error(`restart message does not state the whole-pipeline replay: ${restartDialog.message}`); + } + if (!restartDialog.message.includes("instead of resuming the failed stage")) { + throw new Error(`restart message does not contrast with resume: ${restartDialog.message}`); + } + if (restartDialog.confirm !== "Restart from start") { + throw new Error(`restart confirm: ${restartDialog.confirm}`); + } + if (restartDialog.dismiss !== "Keep") throw new Error(`restart dismiss: ${restartDialog.dismiss}`); + console.log(` restart dialog: "${restartDialog.title}" — ${restartDialog.message}`); + shots.push(await page.screenshot(`${out}/37-run-440-restart-confirm.png`)); + + step("R13: dismissing the dialog with Keep sends nothing"); + await page.click(".confirm-restart .confirm-dismiss"); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-dialog")`), { + timeout: 5000, + what: "the confirm dialog to close", + }); + + step("R14: the rename field is pre-filled with the current title"); + await page.click(".run-detail .rename-open"); + await page.waitForSelector(".run-detail .rename-input", { timeout: 15000 }); + const renameValue = await page.evaluate( + `document.querySelector(".run-detail .rename-input")?.value ?? ""`, + ); + if (!renameValue) throw new Error("the rename field was not pre-filled with the current title"); + console.log(` rename field pre-filled with: ${JSON.stringify(renameValue)}`); + shots.push(await page.screenshot(`${out}/38-run-440-rename-field.png`)); + + step("Action failed: a refused rename shows the server's exact reason"); + await page.fill(".run-detail .rename-input", ""); + await page.click(".run-detail .rename-save"); + await page.waitForSelector(".action-failed", { timeout: 15000 }); + const actionFailed = await page.evaluate(`(() => ({ + title: document.querySelector(".action-failed .action-failed-title")?.textContent ?? "", + message: document.querySelector(".action-failed .action-failed-message")?.textContent ?? "", + ok: document.querySelector(".action-failed .action-failed-ok")?.textContent ?? "", + }))()`); + if (actionFailed.title !== "Action failed") throw new Error(`action-failed title: ${actionFailed.title}`); + if (actionFailed.ok !== "OK") throw new Error(`action-failed ok: ${actionFailed.ok}`); + if (actionFailed.message !== "a title with usable text is required") { + throw new Error(`action-failed message is not the server's own reason: ${actionFailed.message}`); + } + console.log(` action failed: "${actionFailed.title}" — ${actionFailed.message}`); + shots.push(await page.screenshot(`${out}/39-run-440-action-failed.png`)); + await page.click(".action-failed .action-failed-ok"); + await eventually(() => page.evaluate(`!document.querySelector(".action-failed")`), { + timeout: 5000, + what: "the Action-failed dialog to close", + }); + // Leave the rename field without changing anything. + await page.click(".run-detail .rename-cancel"); + + // R12: the Cancel confirm on an executing run. Shown and dismissed with Keep — + // no cancel_run is sent (a real cancel is unsafe against a shared live run). + step("R12: the Cancel confirm on an executing run (shown, not executed)"); + const cancelRunId = await page.evaluate(`(() => { + const row = [...document.querySelectorAll(".list.runs .run-row")].find((n) => n.querySelector(".chip-running")); + const meta = row?.querySelector(".run-row-meta[data-run-id]"); + return meta ? Number(meta.getAttribute("data-run-id")) : null; + })()`); + if (cancelRunId == null) { + console.log(" -- no executing run available; skipped the Cancel confirm capture"); + } else { + await openRunDetail(cancelRunId); + const cancelOffered = await page.evaluate( + `!!document.querySelector(".run-detail .run-actions .cancel-run")`, + ); + if (!cancelOffered) { + console.log(` -- run ${cancelRunId} stopped before the Cancel action could be shown`); + } else { + await page.click(".run-detail .run-actions .cancel-run"); + await page.waitForSelector(".confirm-dialog.confirm-cancel", { timeout: 15000 }); + const cancelDialog = await page.evaluate(`(() => ({ + title: document.querySelector(".confirm-cancel .confirm-title")?.textContent ?? "", + message: document.querySelector(".confirm-cancel .confirm-message")?.textContent ?? "", + confirm: document.querySelector(".confirm-cancel .confirm-accept")?.textContent ?? "", + dismiss: document.querySelector(".confirm-cancel .confirm-dismiss")?.textContent ?? "", + }))()`); + if (cancelDialog.title !== `Cancel run ${cancelRunId}?`) { + throw new Error(`cancel title: ${cancelDialog.title}`); + } + if (cancelDialog.message !== "This asks the server to stop the active run.") { + throw new Error(`cancel message: ${cancelDialog.message}`); + } + if (cancelDialog.confirm !== "Cancel run") throw new Error(`cancel confirm: ${cancelDialog.confirm}`); + if (cancelDialog.dismiss !== "Keep") throw new Error(`cancel dismiss: ${cancelDialog.dismiss}`); + console.log(` cancel dialog (run ${cancelRunId}, not executed): "${cancelDialog.title}" — ${cancelDialog.message}`); + shots.push(await page.screenshot(`${out}/40-run-${cancelRunId}-cancel-confirm.png`)); + await page.click(".confirm-cancel .confirm-dismiss"); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-dialog")`), { + timeout: 5000, + what: "the Cancel dialog to close", + }); + } + } + + // R11: the decision card/sheet, only when the live server actually has a run + // waiting on a person with recorded options. There is normally none (a human + // stage blocks a run until a person answers), so this stays a best-effort + // capture rather than a failure; the model is unit-tested in actions.test.mjs. + step("R11: the human-decision card/sheet (only when a waiting run is present)"); + const waitingRunId = await page.evaluate(`(() => { + const row = [...document.querySelectorAll(".list.runs .run-row")].find((n) => n.querySelector(".chip-waiting")); + const meta = row?.querySelector(".run-row-meta[data-run-id]"); + return meta ? Number(meta.getAttribute("data-run-id")) : null; + })()`); + if (waitingRunId == null) { + console.log(" -- no waiting run available; skipped the decision card/sheet capture (R11 stays partial)"); + } else { + await openRunDetail(waitingRunId); + await page.waitForSelector(".run-detail .decision-card", { timeout: 15000 }); + const cardText = await page.evaluate(`(() => ({ + title: document.querySelector(".decision-card .decision-card-title")?.textContent ?? "", + meta: document.querySelector(".decision-card .decision-card-meta")?.textContent ?? "", + action: document.querySelector(".decision-card .decision-open")?.textContent ?? "", + }))()`); + if (cardText.title !== "Waiting for your decision") throw new Error(`card title: ${cardText.title}`); + if (cardText.action !== "Decide") throw new Error(`card action: ${cardText.action}`); + console.log(` decision card (run ${waitingRunId}): ${cardText.title} — ${cardText.meta}`); + shots.push(await page.screenshot(`${out}/41-run-${waitingRunId}-decision-card.png`)); + await page.click(".decision-card .decision-open"); + await page.waitForSelector(".decision-sheet .decision-option", { timeout: 15000 }); + const sheet = await page.evaluate(`(() => ({ + title: document.querySelector(".decision-sheet-title")?.textContent ?? "", + meta: document.querySelector(".decision-sheet-meta")?.textContent ?? "", + label: document.querySelector(".decision-field-label")?.textContent ?? "", + options: [...document.querySelectorAll(".decision-sheet .decision-option-key")].map((n) => n.textContent), + confirmDisabled: document.querySelector(".decision-confirm")?.disabled ?? null, + }))()`); + if (sheet.label !== "Feedback (optional)") throw new Error(`sheet feedback label: ${sheet.label}`); + if (sheet.confirmDisabled !== true) { + throw new Error("Confirm decision must be disabled until an option is selected"); + } + console.log(` decision sheet (run ${waitingRunId}): ${sheet.title} — ${sheet.meta}; options ${sheet.options.join(", ")}`); + shots.push(await page.screenshot(`${out}/42-run-${waitingRunId}-decision-sheet.png`)); + // Selecting an option enables the confirm but sends nothing. + await page.click(".decision-sheet .decision-option"); + await eventually( + () => page.evaluate(`document.querySelector(".decision-confirm")?.disabled === false`), + { timeout: 5000, what: "the confirm to enable after selecting an option" }, + ); + shots.push(await page.screenshot(`${out}/43-run-${waitingRunId}-decision-selected.png`)); + // Dismiss with Cancel: no decide_run is sent for a real waiting run here. + await page.click(".decision-sheet .decision-cancel"); + await eventually(() => page.evaluate(`!document.querySelector(".decision-sheet")`), { + timeout: 5000, + what: "the decision sheet to close", + }); + } + console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`); } catch (error) {