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
17 changes: 15 additions & 2 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1196,7 +1196,7 @@ export interface paths {
cookie?: never;
};
/**
* Search jobs and runs
* Search jobs, runs, and trace messages
* @description Requires the runs:read scope.
*
* Accepts a scoped bearer token or interactive owner session.
Expand Down Expand Up @@ -4943,11 +4943,24 @@ export interface operations {
"application/json": {
items: {
/** @enum {string} */
kind: "job" | "run";
kind: "job" | "run" | "trace";
id: string;
title: string;
subtitle: string;
url: string;
source: {
/** @enum {string} */
kind: "job" | "run" | "trace";
label: string;
id: string;
};
match: {
text: string;
ranges: {
start: number;
end: number;
}[];
};
}[];
};
};
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,7 @@ export const API_ROUTES: RouteContract[] = [
"/api/v1/search",
"runs:read",
{
summary: "Search jobs and runs",
summary: "Search jobs, runs, and trace messages",
responses: { "200": { description: "Search results", content: { "application/json": { schema: jsonSchema(searchResponse, "output") } } } },
},
(service, { query }) => service.search(query.q),
Expand Down
50 changes: 45 additions & 5 deletions packages/api/src/postgres/operations-repository.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,25 @@
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 @@ -19,10 +40,29 @@ export class OperationsRepository {
async search(query: string) {
const needle = query.trim(); if (!needle) return { items: [] };
const rows = await this.database.pool.query<any>(`SELECT * FROM (
SELECT 'job' kind,j.id,j.name title,j.slug subtitle,'/jobs/'||j.id url,similarity(j.name||' '||j.slug,$2) score FROM app.jobs j WHERE j.tenant_id=$1 AND (j.name ILIKE '%'||$2||'%' OR j.slug ILIKE '%'||$2||'%')
UNION ALL SELECT 'run',r.id,coalesce(nullif(r.run_name,''),nullif(r.issue_title,''),'Run '||left(r.id::text,8)),r.state,'/job-runs/'||r.id,similarity(coalesce(r.run_name,'')||' '||coalesce(r.issue_title,'')||' '||r.issue_id,$2) 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 'run',e.run_id,e.title,left(e.preview_text,120),'/job-runs/'||e.run_id,ts_rank(e.search_vector,websearch_to_tsquery('english',$2)) FROM app.run_trace_events e WHERE e.tenant_id=$1 AND e.search_vector @@ websearch_to_tsquery('english',$2)
) found ORDER BY score DESC LIMIT 100`, [this.tenantId, needle]);
return { items: rows.rows.map(row => ({ kind: row.kind, id: row.id, title: row.title, subtitle: row.subtitle, url: row.url })) };
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||'%')
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 };
}) };
}
}
8 changes: 7 additions & 1 deletion packages/api/src/search-contracts.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
import { z } from "zod";
export const searchResponse = z.object({ items: z.array(z.object({ kind: z.enum(["job", "run"]), id: z.string(), title: z.string(), subtitle: z.string(), url: z.string() })) });

export const searchRange = z.object({ start: z.number().int().nonnegative(), end: z.number().int().nonnegative() });
export const searchResponse = z.object({ items: z.array(z.object({
kind: z.enum(["job", "run", "trace"]), id: z.string(), title: z.string(), subtitle: z.string(), url: z.string(),
source: z.object({ kind: z.enum(["job", "run", "trace"]), label: z.string(), id: z.string() }),
match: z.object({ text: z.string(), ranges: z.array(searchRange) }),
})) });
20 changes: 14 additions & 6 deletions packages/app/src/features/search/dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { Button, Input, Label } from "../../shared/ui";
import { useEffect, useRef, useState } from "react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { api } from "factorize-api-client";
import { messageOf } from "../auth/session";

function Highlighted({ text, ranges }: { text: string; ranges: { start: number; end: number }[] }) {
const parts: ReactNode[] = [], ordered = [...ranges].sort((a, b) => a.start - b.start);
let cursor = 0;
for (const range of ordered) { if (range.start > cursor) parts.push(text.slice(cursor, range.start)); parts.push(<strong key={`${range.start}:${range.end}`}>{text.slice(range.start, range.end)}</strong>); cursor = Math.max(cursor, range.end); }
if (cursor < text.length) parts.push(text.slice(cursor));
return <>{parts}</>;
}
export default function SearchDialog({ close }: { close: () => void }) {
const dialog = useRef<HTMLDialogElement>(null), navigate = useNavigate();
const [text, setText] = useState(""), [q, setQuery] = useState(""), [selected, setSelected] = useState(0);
Expand All @@ -12,18 +20,18 @@ export default function SearchDialog({ close }: { close: () => void }) {
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 ?? [];
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.id }, search: { after: 0 } }); };
return <dialog ref={dialog} aria-label="Search jobs and runs" onClose={close} onClick={e => { if (e.target === e.currentTarget) close(); }} className="w-[min(92vw,42rem)] h-[min(36rem,80dvh)] overflow-hidden">
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 } }); };
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 and runs <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 => {
<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); }
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 and runs by name, prompt, or context. Use ↑ ↓ to select and Enter to open.</p>}
{!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 text-left aria-selected:border-factorize-500 aria-selected:bg-factorize-50 dark:aria-selected:bg-factorize-500/10" onClick={() => choose(index)}>{item.title}<span className="block text-sm">{item.kind} · {item.subtitle}</span></Button></li>)}</ul>
<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>
</div>
</div>
</dialog>;
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/search/launcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ export function SearchLauncher() {
};
window.addEventListener("keydown", handler); return () => window.removeEventListener("keydown", handler);
}, []);
return <><Button aria-label="Search jobs and runs" onClick={() => setOpen(true)}>Search (/)</Button>{open && <Suspense fallback={<p role="status">Loading search…</p>}><Dialog close={() => setOpen(false)} /></Suspense>}</>;
return <><Button aria-label="Search jobs, runs, and messages" onClick={() => setOpen(true)}>Search (/)</Button>{open && <Suspense fallback={<p role="status">Loading search…</p>}><Dialog close={() => setOpen(false)} /></Suspense>}</>;
}
7 changes: 4 additions & 3 deletions packages/app/test/editor.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,14 @@ test("provider editor fetches only the selected provider and submits project/mat
test("search dialog keeps keyboard focus, escapes results and leaves a draft intact after chunk failure", async () => {
const { context, page } = await setup();
await page.route("**/api/v1/jobs/" + id, route => route.fulfill({ json: initial }));
await page.route("**/api/v1/search?**", route => route.fulfill({ json: { items: [{ kind: "job", id, title: "<script>unsafe</script> Build", subtitle: "Matching job", url: "/jobs/" + id }] } }));
await page.route("**/api/v1/search?**", route => route.fulfill({ json: { items: [{ kind: "job", id, title: "<script>unsafe</script> Build", subtitle: "Matching job", url: "/jobs/" + id, source: { kind: "job", label: "<script>unsafe</script> Build", id }, match: { text: "<script>unsafe</script> Build", ranges: [{ start: 24, end: 29 }] } }] } }));
await page.goto(origin + "/jobs/" + id + "/edit");
await page.getByLabel("Name", { exact: true }).fill("Unsaved draft");
await page.getByRole("button", { name: "Search jobs and runs", exact: true }).click();
await page.getByRole("combobox", { name: "Search jobs and runs", exact: true }).fill("build");
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("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");
assert.equal(await page.locator("dialog script").count(), 0);
await page.keyboard.press("Escape");
assert.equal(await page.getByRole("dialog").count(), 0);
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-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.
Loading
Loading