web: add omni-search results and routing (S1/S2)

This commit is contained in:
2026-10-19 04:27:59 +01:00
parent 9555bfe58f
commit 26eaec2531
9 changed files with 2003 additions and 10 deletions
+437 -8
View File
@@ -133,6 +133,25 @@ import {
runChangesHeader,
runChangesNote,
} from "./changes.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";
const STORAGE_KEY = "pipelines.web.serverUrl.v2";
@@ -209,6 +228,19 @@ const state = {
runSections: new Set(),
runStagePane: null,
runStageSections: new Set(),
// 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(),
};
let runPoll = null;
@@ -256,11 +288,20 @@ 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 });
const content = h("main", { id: "content" });
document.body.append(header, connBanner, content);
document.body.append(header, searchHost, connBanner, content);
// 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() {
@@ -270,6 +311,7 @@ function endpointConfigured() {
function renderHeader() {
const info = bannerState(state.connection, { hasEndpoint: endpointConfigured() });
const controls = [
...searchHeaderControls(),
h("input", {
id: "url",
type: "text",
@@ -300,6 +342,58 @@ function renderHeader() {
h("div", { class: "brand" }, h("strong", { text: "Pipelines" }), h("span", { class: "muted", text: "web spike" })),
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,
}),
];
}
/**
@@ -330,6 +424,7 @@ function connectionLabel() {
function render() {
renderHeader();
renderBanner();
renderSearch();
renderContent();
}
@@ -2249,6 +2344,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
// ---------------------------------------------------------------------------
@@ -2543,16 +2969,19 @@ client.addEventListener("state", (event) => {
// 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).
// Registered once; it is a no-op when no pane is open.
// Once no pane is open, Escape closes the omni-search field. Registered once;
// every branch is a no-op when nothing relevant is open.
document.addEventListener("keydown", (event) => {
if (
event.key === "Escape" &&
state.runStagePane &&
!document.querySelector(".artifact-viewer") &&
!document.querySelector(".change-viewer")
) {
if (event.key !== "Escape") return;
if (document.querySelector(".artifact-viewer") || document.querySelector(".change-viewer")) return;
if (state.runStagePane) {
event.preventDefault();
closeStagePane();
return;
}
if (state.searchOpen) {
event.preventDefault();
closeSearch();
}
});
+5
View File
@@ -21,6 +21,11 @@ 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",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
});
+21
View File
@@ -72,4 +72,25 @@ 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;
}
}
+500
View File
@@ -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;
}