// 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 = ""; /** Unquoted, whitespace-delimited t:/type: tokens; last supported token wins. * Unknown tokens and quoted text stay literal, including their whitespace. * The selector is a fallback; explicitly changing it removes tokens in the view. */ export function parseSearchQuery(value, selectedKind = DEFAULT_SEARCH_KIND) { const source = String(value ?? ""); let kind = selectedKind; let hasType = false; const query = source.replace(/(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+/g, (token) => { const match = /^(?:t|type):([a-z]+)$/i.exec(token); const candidate = match?.[1].toLowerCase(); if (!candidate || !SEARCH_KINDS.some((option) => option.value === candidate)) return token; kind = candidate; hasType = true; return ""; }); return { query, kind, hasType }; } /** * 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() === "") { if (!state?.loaded || !kind) return null; const label = searchKindLabel(kind).toLowerCase(); return state?.truncated ? `No ${label} found within the server's scan limit.` : `No ${label} yet.`; } if (kind === "" || kind == null) return `No matches for "${query}".`; return `No ${searchKindLabel(kind).toLowerCase()} match "${query}".`; } /** * Text searches and valid kind-only browsing are sendable. Empty text with no * supported kind still clears locally, without an all-kind scan. */ export function searchQuerySendable(query, kind = "") { return String(query ?? "").trim() !== "" || SEARCH_KINDS.some((option) => option.value !== "" && option.value === kind); } /** * 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; }