Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
3 changes: 2 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
59 changes: 17 additions & 42 deletions packages/api/src/postgres/operations-repository.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,4 @@
import type { Database } from "./database";
import { rankField, searchMatches } from "../search";

const HIGHLIGHT_START = "<<<FACTORIZE_MATCH>>>";
const HIGHLIGHT_END = "<<<FACTORIZE_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) {}
Expand All @@ -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<any>(`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=<<<FACTORIZE_MATCH>>>,StopSel=<<<FACTORIZE_END>>>,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: [] },
})) };
}
}
19 changes: 10 additions & 9 deletions packages/app/src/features/search/dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dialog ref={dialog} aria-label="Search jobs, runs, and messages" onClose={close} onClick={e => { if (e.target === e.currentTarget) close(); }} className="w-[min(92vw,42rem)] h-[min(36rem,80dvh)] overflow-hidden">
<div className="flex h-full min-h-0 flex-col">
<div className="mb-4 flex shrink-0 items-start justify-between gap-3"><h2>Search</h2><Button onClick={close}>Close search</Button></div><Label className="shrink-0">Search jobs, runs, and messages <Input autoFocus role="combobox" aria-expanded={items.length > 0} aria-autocomplete="list" value={text} maxLength={500} aria-controls="search-results" aria-activedescendant={items.length ? `search-result-${selected}` : undefined} onChange={e => setText(e.target.value)} onKeyDown={e => {
if (e.key === "ArrowDown" && items.length) { e.preventDefault(); setSelected(index => (index + 1) % items.length); }
if (e.key === "ArrowUp" && items.length) { e.preventDefault(); setSelected(index => (index - 1 + items.length) % items.length); }
<div className="mb-4 flex shrink-0 items-start justify-between gap-3"><h2>Search</h2><Button onClick={close}>Close search</Button></div><Label className="shrink-0">Search jobs and runs by name, title, or issue identifier <Input autoFocus role="combobox" aria-expanded={items.length > 0} aria-autocomplete="list" value={text} maxLength={500} aria-controls="search-results" aria-activedescendant={queryCurrent && items.length ? `search-result-${selected}` : undefined} onChange={e => { setText(e.target.value); setSelected(0); }} onKeyDown={e => {
if (e.key === "ArrowDown" && queryCurrent && items.length) { e.preventDefault(); setSelected(index => (index + 1) % items.length); }
if (e.key === "ArrowUp" && queryCurrent && items.length) { e.preventDefault(); setSelected(index => (index - 1 + items.length) % items.length); }
if (e.key === "Enter") { e.preventDefault(); choose(selected); }
}} /></Label>
<div className="mt-4 min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]">
{!q && <p className="my-4 text-sm text-slate-600 dark:text-slate-400">Find jobs, runs, and messages by name or matching text. Use ↑ ↓ to select and Enter to open.</p>}
{results.isFetching && <p role="status">Searching…</p>}{results.error && <p role="alert">{results.error.message}</p>}{q && !results.isPending && !items.length && <p>No results found.</p>}
<ul id="search-results" role="listbox" aria-label="Search results">{items.map((item, index) => <li key={`${item.kind}:${item.id}:${index}`} role="presentation"><Button role="option" id={`search-result-${index}`} aria-selected={selected === index} tabIndex={-1} className="my-2 w-full flex-col items-start !items-start text-left font-normal aria-selected:border-factorize-500 aria-selected:bg-factorize-50 dark:aria-selected:bg-factorize-500/10" onClick={() => choose(index)}><span className="block font-medium">{item.source.kind[0]!.toUpperCase() + item.source.kind.slice(1)} · {item.source.label}</span><span className="block text-sm"><Highlighted text={item.match.text} ranges={item.match.ranges} /></span></Button></li>)}</ul>
{!currentText && <p className="my-4 text-sm text-slate-600 dark:text-slate-400">Find jobs and runs by approximate name, title, or issue identifier. Use ↑ ↓ to select and Enter to open.</p>}
{(results.isFetching || (currentText && !queryCurrent)) && <p role="status">{results.isFetching ? "Searching…" : "Updating…"}</p>}{results.error && <p role="alert">{results.error.message}</p>}{currentText && queryCurrent && !results.isPending && !items.length && <p>No results found.</p>}
<ul id="search-results" role="listbox" aria-label="Search results">{items.map((item, index) => <li key={`${item.kind}:${item.id}:${index}`} role="presentation"><Button role="option" id={`search-result-${index}`} aria-selected={queryCurrent && selected === index} tabIndex={-1} className="my-2 w-full flex-col items-start !items-start text-left font-normal aria-selected:border-factorize-500 aria-selected:bg-factorize-50 dark:aria-selected:bg-factorize-500/10" onClick={() => choose(index)}><span className="block font-medium">{item.source.kind[0]!.toUpperCase() + item.source.kind.slice(1)} · {item.source.label}</span><span className="block text-sm"><Highlighted text={item.match.text} ranges={item.match.ranges} /></span></Button></li>)}</ul>
</div>
</div>
</dialog>;
Expand Down
2 changes: 1 addition & 1 deletion packages/app/test/editor.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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(), /<script>unsafe<\/script>/);
assert.equal(await page.getByRole("listbox", { name: "Search results" }).getByRole("option").locator("strong").innerText(), "Build");
Expand Down
Binary file modified packages/app/test/visual/baselines/search-empty-mobile.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/search-error-dark-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/search-error-light-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/search-loading-dark-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/search-loading-light-390.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified packages/app/test/visual/baselines/search-results-mobile.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions packages/app/test/visual/design.spec.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ test("mobile profile, search and run dialog keyboard/focus behavior; long conten
await profile.click(); await expect(page.getByRole("link", { name: "Settings", exact: true }).last()).toBeVisible();
await page.keyboard.press("Escape"); await expect(profile).toBeFocused();
await page.getByRole("button", { name: "Search jobs, runs, and messages", exact: true }).click();
await expect(page.getByRole("combobox", { name: "Search jobs, runs, and messages", exact: true })).toBeFocused();
await expect(page.getByRole("combobox", { name: "Search jobs and runs by name, title, or issue identifier", exact: true })).toBeFocused();
await page.keyboard.press("Escape"); await expect(page.getByRole("dialog")).toHaveCount(0);
const run = page.getByRole("button", { name: "Run job", exact: true }); await run.click();
await page.getByLabel("JSON data (optional)").fill("[]"); await page.getByRole("button", { name: "Invoke", exact: true }).click();
Expand Down Expand Up @@ -131,7 +131,7 @@ for (const theme of ["light", "dark"]) test(`search loading, error and no result
await page.route("**/api/v1/search?**", route => mode === "pending" ? (pending = route) : mode === "error" ? route.fulfill(failure) : route.fulfill({ json: { items: [] } }));
await page.goto(origin + "/jobs"); await page.getByRole("heading", { name: "Jobs", exact: true }).waitFor();
await page.getByRole("button", { name: "Search jobs, runs, and messages", exact: true }).click();
const dialog = page.getByRole("dialog"), input = dialog.getByRole("combobox", { name: "Search jobs, runs, and messages", exact: true });
const dialog = page.getByRole("dialog"), input = dialog.getByRole("combobox", { name: "Search jobs and runs by name, title, or issue identifier", exact: true });
await input.fill("release"); await expect(dialog.getByRole("status")).toHaveText("Searching…");
await expect(page).toHaveScreenshot(`search-loading-${theme}-390.png`);
mode = "error"; await pending.fulfill(failure);
Expand Down Expand Up @@ -213,7 +213,7 @@ for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844
}
}
await input.fill("");
await expect(dialog.getByText("Find jobs, runs, and messages", { exact: false })).toBeVisible();
await expect(dialog.getByText("Find jobs and runs by approximate name, title, or issue identifier", { exact: false })).toBeVisible();
expect(await geometry()).toEqual(initial);
await input.fill("select");
await expect(dialog.getByRole("status")).toHaveText("Searching…");
Expand Down
12 changes: 7 additions & 5 deletions packages/docs/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7443,7 +7443,13 @@ paths:
minLength: 1
/api/v1/search:
get:
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.

Requires the runs:read scope.

Accepts a scoped bearer token or interactive owner session.
responses:
"200":
description: Search results
Expand Down Expand Up @@ -7543,10 +7549,6 @@ paths:
$ref: "#/components/responses/Error500"
"503":
$ref: "#/components/responses/Error503"
description: |-
Requires the runs:read scope.

Accepts a scoped bearer token or interactive owner session.
operationId: get_api_v1_search
tags:
- search
Expand Down
Loading