diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 9a99479b..cc20d57f 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1198,8 +1198,10 @@ export interface paths { cookie?: never; }; /** - * Search jobs, runs, and trace messages - * @description Requires the runs:read scope. + * Search jobs and runs by approximate metadata matches + * @description Search uses PostgreSQL pg_trgm approximate matching over job names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching. + * + * Requires the runs:read scope. * * Accepts a scoped bearer token or interactive owner session. */ diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 80191819..1781a773 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -803,7 +803,8 @@ export const API_ROUTES: RouteContract[] = [ "/api/v1/search", "runs:read", { - summary: "Search jobs, runs, and trace messages", + summary: "Search jobs and runs by approximate metadata matches", + description: "Search uses PostgreSQL pg_trgm approximate matching over job names/slugs and run names, issue titles, and issue identifiers. Identifier matching is whole-field trigram matching; names and titles use word-level trigram matching. Exact identifiers and metadata names rank first, followed by the strongest individual field score. Results are unique, tenant-scoped, deterministically ordered, and limited to 100. Blank or punctuation-only queries return no results. One- and two-character queries may return no results because trigram matching is approximate; this is not ordered-character or substring matching.", responses: { "200": { description: "Search results", content: { "application/json": { schema: jsonSchema(searchResponse, "output") } } } }, }, (service, { query }) => service.search(query.q), diff --git a/packages/api/src/postgres/operations-repository.ts b/packages/api/src/postgres/operations-repository.ts index bc5b9cc2..03fd00aa 100644 --- a/packages/api/src/postgres/operations-repository.ts +++ b/packages/api/src/postgres/operations-repository.ts @@ -1,25 +1,4 @@ import type { Database } from "./database"; -import { rankField, searchMatches } from "../search"; - -const HIGHLIGHT_START = "<<>>"; -const HIGHLIGHT_END = "<<>>"; - -function markedMatch(value: string, fallback: string, query: string) { - const text = value || fallback, ranges: { start: number; end: number }[] = []; - let output = "", cursor = 0, start = text.indexOf(HIGHLIGHT_START); - while (start >= 0) { - const end = text.indexOf(HIGHLIGHT_END, start + HIGHLIGHT_START.length); - if (end < 0) break; - output += text.slice(cursor, start); - const matchStart = output.length; - output += text.slice(start + HIGHLIGHT_START.length, end); - ranges.push({ start: matchStart, end: output.length }); - cursor = end + HIGHLIGHT_END.length; - start = text.indexOf(HIGHLIGHT_START, cursor); - } - output += text.slice(cursor); - return { text: output || fallback, ranges: ranges.length ? ranges : searchMatches(output || fallback, query) }; -} export class OperationsRepository { constructor(private database: Database, private tenantId: string) {} @@ -38,31 +17,27 @@ export class OperationsRepository { return { items, nextCursor: rows.length > limit ? encoded : null }; } async search(query: string) { - const needle = query.trim(); if (!needle) return { items: [] }; + const needle = query.trim(); if (!needle || !/[\p{L}\p{N}]/u.test(needle)) return { items: [] }; const rows = await this.database.pool.query(`SELECT * FROM ( SELECT 'job' kind,j.id::text id,j.name title,j.slug subtitle,'/jobs/'||j.id url,j.id::text source_id,j.name source_label, - CASE WHEN j.name ILIKE '%'||$2||'%' THEN j.name ELSE j.slug END match_text, - similarity(j.name||' '||j.slug,$2) score,0 category,j.id::text stable_key,NULL match_excerpt - FROM app.jobs j WHERE j.tenant_id=$1 AND (j.name ILIKE '%'||$2||'%' OR j.slug ILIKE '%'||$2||'%') + CASE WHEN word_similarity($2,j.name) >= word_similarity($2,j.slug) THEN j.name ELSE j.slug END match_text, + GREATEST(word_similarity($2,j.name),word_similarity($2,j.slug)) score, + CASE WHEN lower(j.name)=$2 OR lower(j.slug)=$2 THEN 1 ELSE 2 END category,j.id::text stable_key + FROM app.jobs j WHERE j.tenant_id=$1 AND (j.name <% $2 OR j.slug <% $2) UNION ALL SELECT 'run',r.id::text,coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),r.state,'/job-runs/'||r.id,r.id::text, coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)), - CASE WHEN r.run_name ILIKE '%'||$2||'%' THEN r.run_name WHEN r.issue_title ILIKE '%'||$2||'%' THEN r.issue_title ELSE r.issue_id END, - similarity(coalesce(r.run_name,'')||' '||coalesce(r.issue_title,'')||' '||r.issue_id,$2),1,r.id::text,NULL - FROM app.runs r WHERE r.tenant_id=$1 AND (r.run_name ILIKE '%'||$2||'%' OR r.issue_title ILIKE '%'||$2||'%' OR r.issue_id ILIKE '%'||$2||'%') - UNION ALL - SELECT 'trace',e.id,e.title,left(e.preview_text,120),'/job-runs/'||e.run_id,e.run_id::text, - coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),e.title, - ts_rank(e.search_vector,websearch_to_tsquery('english',$2)),2,e.run_id::text||':'||e.sequence, - ts_headline('english',e.title||' '||e.preview_text,websearch_to_tsquery('english',$2), - 'StartSel=<<>>,StopSel=<<>>,MaxFragments=1,MaxWords=32,MinWords=8') - FROM app.run_trace_events e JOIN app.runs r ON r.tenant_id=e.tenant_id AND r.id=e.run_id - WHERE e.tenant_id=$1 AND e.search_vector @@ websearch_to_tsquery('english',$2) - ) found ORDER BY category,score DESC,stable_key LIMIT 100`, [this.tenantId, needle]); - return { items: rows.rows.map(row => { - const ranked = row.kind === "trace" ? null : rankField(row.match_text, needle, row.kind === "job" ? "job" : "run"); - const match = row.kind === "trace" ? markedMatch(row.match_excerpt, row.title, needle) : { text: row.match_text, ranges: ranked?.range ? [ranked.range] : searchMatches(row.match_text, needle) }; - return { kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url, source: { kind: row.kind, label: row.source_label, id: row.source_id }, match }; - }) }; + CASE WHEN r.issue_id % $2 THEN r.issue_id + WHEN word_similarity($2,r.run_name) >= word_similarity($2,r.issue_title) THEN coalesce(nullif(r.run_name,''),r.issue_id) + ELSE coalesce(nullif(r.issue_title,''),r.issue_id) END match_text, + GREATEST(similarity(r.issue_id,$2),word_similarity($2,r.run_name),word_similarity($2,r.issue_title)) score, + CASE WHEN lower(r.issue_id)=$2 THEN 0 WHEN lower(r.run_name)=$2 OR lower(r.issue_title)=$2 THEN 1 ELSE 2 END category,r.id::text stable_key + FROM app.runs r WHERE r.tenant_id=$1 AND (r.issue_id % $2 OR r.run_name <% $2 OR r.issue_title <% $2) + ) found ORDER BY category,score DESC,kind,stable_key LIMIT 100`, [this.tenantId, needle.toLowerCase()]); + return { items: rows.rows.map(row => ({ + kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url, + source: { kind: row.kind, label: row.source_label, id: row.source_id }, + match: { text: row.match_text, ranges: [] }, + })) }; } } diff --git a/packages/app/src/features/search/dialog.tsx b/packages/app/src/features/search/dialog.tsx index e74be057..cdee9b52 100644 --- a/packages/app/src/features/search/dialog.tsx +++ b/packages/app/src/features/search/dialog.tsx @@ -17,21 +17,22 @@ export default function SearchDialog({ close }: { close: () => void }) { const [text, setText] = useState(""), [q, setQuery] = useState(""), [selected, setSelected] = useState(0); useEffect(() => { const previous = document.activeElement as HTMLElement | null; dialog.current?.showModal(); dialog.current?.querySelector("input")?.focus(); return () => { dialog.current?.close(); previous?.focus(); }; }, []); useEffect(() => { const timer = window.setTimeout(() => { setQuery(text.trim()); setSelected(0); }, 120); return () => window.clearTimeout(timer); }, [text]); - const results = useQuery({ queryKey: ["search", q], enabled: !!q, queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/search", { signal, params: { query: { q } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 15_000, retry: 1 }); - const items = results.data?.items ?? []; + const results = useQuery({ queryKey: ["search", q], enabled: !!q, queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/search", { signal, params: { query: { q } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, placeholderData: previous => previous, staleTime: 15_000, retry: 1 }); + const currentText = text.trim(), queryCurrent = currentText === q, items = currentText ? (results.data?.items ?? []) : []; + useEffect(() => { setSelected(0); }, [q, results.data]); useEffect(() => { dialog.current?.querySelector(`#search-result-${selected}`)?.scrollIntoView({ block: "nearest" }); }, [selected, results.data]); - const choose = (index: number) => { const item = items[index]; if (!item) return; close(); if (item.kind === "job") void navigate({ to: "/jobs/$jobId", params: { jobId: item.id } }); else void navigate({ to: "/job-runs/$runId", params: { runId: item.source.id }, search: { after: 0 } }); }; + const choose = (index: number) => { if (!queryCurrent) return; const item = items[index]; if (!item) return; close(); if (item.kind === "job") void navigate({ to: "/jobs/$jobId", params: { jobId: item.id } }); else void navigate({ to: "/job-runs/$runId", params: { runId: item.source.id }, search: { after: 0 } }); }; return { if (e.target === e.currentTarget) close(); }} className="w-[min(92vw,42rem)] h-[min(36rem,80dvh)] overflow-hidden">
-

Search

; diff --git a/packages/app/test/editor.browser.test.mjs b/packages/app/test/editor.browser.test.mjs index 5d50a298..f456f5f0 100644 --- a/packages/app/test/editor.browser.test.mjs +++ b/packages/app/test/editor.browser.test.mjs @@ -73,7 +73,7 @@ test("search dialog keeps keyboard focus, escapes results and leaves a draft int await page.goto(origin + "/jobs/" + id + "/edit"); await page.getByLabel("Name", { exact: true }).fill("Unsaved draft"); await page.getByRole("button", { name: "Search jobs, runs, and messages", exact: true }).click(); - await page.getByRole("combobox", { name: "Search jobs, runs, and messages", exact: true }).fill("build"); + await page.getByRole("combobox", { name: "Search jobs and runs by name, title, or issue identifier", exact: true }).fill("build"); await page.getByRole("listbox", { name: "Search results" }).getByRole("option").waitFor(); assert.match(await page.getByRole("listbox", { name: "Search results" }).getByRole("option").innerText(), /