Merge branch 'main' into web-attention

# Conflicts:
#	web/PARITY.md
#	web/src/app.js
#	web/styles.css
This commit is contained in:
2026-10-19 04:55:01 +01:00
11 changed files with 3537 additions and 17 deletions
+245
View File
@@ -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}?`;
}
+930 -11
View File
File diff suppressed because it is too large Load Diff
+13
View File
@@ -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",
});
+81
View File
@@ -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;
}
}
+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;
}