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
9 changes: 9 additions & 0 deletions packages/app/src/features/runs/format-created.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function formatCreated(value: string) {
const date = new Date(value), age = Date.now() - date.getTime();
if (age >= 0 && age < 24 * 60 * 60 * 1000) {
const units: Array<[number, Intl.RelativeTimeFormatUnit]> = [[60 * 60 * 1000, "hour"], [60 * 1000, "minute"], [1000, "second"]];
const unit = units.find(([size]) => age >= size) ?? units.at(-1)!;
return new Intl.RelativeTimeFormat(undefined, { numeric: "always" }).format(-Math.max(1, Math.floor(age / unit[0])), unit[1]);
}
return date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
}
11 changes: 6 additions & 5 deletions packages/app/src/features/runs/history.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ import { Link, useNavigate, useSearch } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { historyQuery } from "./queries";
import { formatElapsedTime } from "../../shared/elapsed-time";
export type HistorySort = "run" | "status" | "created" | "agent";
import { formatCreated } from "./format-created";
export type HistorySort = "run" | "status" | "created";
export type HistorySearch = { cursor?: string; previous?: string; states?: RunStatus[]; sort?: HistorySort; direction?: "asc" | "desc" };
export function RunHistory({ jobId }: { jobId: string }) {
const search = useSearch({ strict: false }) as HistorySearch;
const navigate = useNavigate();
const runs = useQuery(historyQuery(jobId, search.cursor, search.sort, search.direction, search.states));
const previous = search.previous === undefined ? [] : search.previous.split(",");
const pageClasses = `inline-flex min-h-10 items-center rounded-lg border px-3 py-2 text-sm font-semibold ${buttonClasses.secondary}`;
const columns: Array<[HistorySort, string]> = [["status", "Status"], ["run", "Run"], ["created", "Created"], ["agent", "Execution"]];
const columns: Array<[HistorySort, string]> = [["status", "Status"], ["run", "Run"], ["created", "Created"]];
const sortColumn = (column: HistorySort) => {
const direction = search.sort === column && search.direction === "asc" ? "desc" : "asc";
void navigate({ to: "/jobs/$jobId", params: { jobId }, search: { ...search, sort: column, direction, cursor: undefined, previous: undefined } });
Expand All @@ -22,13 +23,13 @@ export function RunHistory({ jobId }: { jobId: string }) {
const clearStatuses = () => void navigate({ to: "/jobs/$jobId", params: { jobId }, search: { ...search, states: undefined, sort: undefined, direction: undefined, cursor: undefined, previous: undefined } });
return <section aria-label="Runs" className="my-6 min-w-0">
{runs.isPending && <p role="status">Loading run history…</p>}{runs.error && <p role="alert">{runs.error.message} <Button onClick={() => void runs.refetch()}>Retry</Button></p>}
{runs.data && <><Table className="min-w-[40rem] table-fixed" shellProps={{ role: "region", "aria-label": "Runs table", tabIndex: 0 }}><caption className="sr-only">Job runs{search.sort ? "" : ", queued and starting first, running second, then other states; newest first within each group"}</caption><colgroup><col className="w-20" /><col className="w-60" /><col className="w-44" /><col className="w-52" /><col className="w-32" /></colgroup>
{runs.data && <><Table className="min-w-[40rem] table-fixed" shellProps={{ role: "region", "aria-label": "Runs table", tabIndex: 0 }}><caption className="sr-only">Job runs{search.sort ? "" : ", queued and starting first, running second, then other states; newest first within each group"}</caption><colgroup><col className="w-20" /><col className="w-64" /><col className="w-52" /><col className="w-44" /></colgroup>
<thead className={tableHeadClasses}><tr><StatusHeader selected={search.states ?? []} sortDirection={search.sort === "status" ? search.direction : undefined} onFilterChange={changeFilter} onSortChange={changeStatusSort} onClear={clearStatuses} />{columns.slice(1, 2).map(([column, label]) => <SortableHeader key={column} label={label} active={search.sort === column} direction={search.direction} ariaLabel={`${label}, ${sortLabel(column)}`} onSort={() => sortColumn(column)} />)}<th scope="col" className={tableCellClasses}>Elapsed</th>{columns.slice(2).map(([column, label]) => <SortableHeader key={column} label={label} active={search.sort === column} direction={search.direction} ariaLabel={`${label}, ${sortLabel(column)}`} onSort={() => sortColumn(column)} />)}</tr></thead>
<tbody>{runs.data.items.map(run => <tr className={tableRowClasses} key={run.id}>
<td className={`whitespace-nowrap ${tableCellClasses}`}><RunStatusDot state={run.state} failureSource={run.failure_source} failure={run.failure} /></td>
<td className={tableCellClasses}><Link to="/job-runs/$runId" params={{ runId: run.id }} search={{ after: 0 }} title={run.run_name || run.issue_title || "Run"} className="block truncate font-semibold hover:text-factorize-700 focus-visible:rounded-sm dark:hover:text-factorize-500">{run.run_name || run.issue_title || "Run"}</Link>{(run.failure?.reason || (run.agent_error as any)?.reason) && <p className="mt-1 truncate text-xs text-red-700 dark:text-red-300" title={(run.failure?.reason || (run.agent_error as any).reason)}>{(run.failure?.reason || (run.agent_error as any).reason)}</p>}</td>
<td className={`whitespace-nowrap ${tableCellClasses}`} title={run.elapsed_time ? formatElapsedTime(run.elapsed_time) : undefined}>{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}</td><td className={`whitespace-nowrap ${tableCellClasses}`}><time dateTime={run.created_at}>{new Date(run.created_at).toLocaleString()}</time></td><td className={`${tableCellClasses} truncate`} title={run.execution_type === "code" ? "Code script" : run.agent_kind}>{run.execution_type === "code" ? "Code script" : run.agent_kind}</td>
</tr>)}{runs.data.items.length === 0 && <tr><td colSpan={5} className="px-3 py-6 text-center">{search.states?.length ? <><p>No runs match the selected statuses.</p><Button className="mt-3" onClick={() => void navigate({ to: "/jobs/$jobId", params: { jobId }, search: { ...search, states: undefined, cursor: undefined, previous: undefined } })}>Clear status filters</Button></> : "No runs found."}</td></tr>}</tbody>
<td className={`whitespace-nowrap ${tableCellClasses}`} title={run.elapsed_time ? formatElapsedTime(run.elapsed_time) : undefined}>{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}</td><td className={`whitespace-nowrap ${tableCellClasses}`}><time dateTime={run.created_at}>{formatCreated(run.created_at)}</time></td>
</tr>)}{runs.data.items.length === 0 && <tr><td colSpan={4} className="px-3 py-6 text-center">{search.states?.length ? <><p>No runs match the selected statuses.</p><Button className="mt-3" onClick={() => void navigate({ to: "/jobs/$jobId", params: { jobId }, search: { ...search, states: undefined, cursor: undefined, previous: undefined } })}>Clear status filters</Button></> : "No runs found."}</td></tr>}</tbody>
</Table></>}
<nav aria-label="Run pages" className="mt-4 flex flex-wrap items-center gap-2">
{search.cursor && <Link className={pageClasses} to="/jobs/$jobId" params={{ jobId }} search={{ states: search.states, sort: search.sort, direction: search.direction }}>First page</Link>}
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/features/runs/list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { runPageQuery } from "./queries";
import { formatElapsedTime } from "../../shared/elapsed-time";
import { projectsQuery } from "../projects/queries";
import { jobsQuery } from "../jobs/queries";
import { formatCreated } from "./format-created";

export type RunListSearch = { cursor?: string; previous?: string; projects?: string[]; jobs?: string[]; states?: RunStatus[]; sort?: "job" | "run" | "status" | "created" | "agent"; direction?: "asc" | "desc" };
const formatCreated = (value: string) => { const date = new Date(value), age = Date.now() - date.getTime(); if (age >= 0 && age < 24 * 60 * 60 * 1000) { const units: Array<[number, Intl.RelativeTimeFormatUnit]> = [[60 * 60 * 1000, "hour"], [60 * 1000, "minute"], [1000, "second"]]; const unit = units.find(([size]) => age >= size) ?? units.at(-1)!; return new Intl.RelativeTimeFormat(undefined, { numeric: "always" }).format(-Math.max(1, Math.floor(age / unit[0])), unit[1]); } return date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); };
function FunnelButton({ kind, name, selected, onToggle }: { kind: "project" | "job"; name: string; selected: boolean; onToggle: () => void }) { return <button type="button" aria-label={`${selected ? "Remove " : "Filter by "}${kind} ${name}`} aria-pressed={selected} title={`${selected ? "Remove " : "Filter by "}${kind}`} className={`mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-factorize-500 ${selected ? "bg-factorize-100 text-factorize-700 dark:bg-factorize-500/20 dark:text-factorize-400" : "text-slate-400 hover:bg-stone-100 hover:text-slate-700 dark:hover:bg-slate-800 dark:hover:text-slate-200"}`} onClick={event => { event.preventDefault(); event.stopPropagation(); onToggle(); }}><svg aria-hidden="true" viewBox="0 0 20 20" fill="currentColor" className="size-3.5"><path d="M3 4.5A1.5 1.5 0 0 1 4.5 3h11a1.5 1.5 0 0 1 1.2 2.4L12 11.4V16a1 1 0 0 1-1.45.9l-2-1A1 1 0 0 1 8 15v-3.6L3.3 5.4A1.5 1.5 0 0 1 3 4.5Z" /></svg></button>; }

export function RunList({ jobId, projectId, limit = 30 }: { jobId?: string; projectId?: string; limit?: number }) {
Expand Down
7 changes: 4 additions & 3 deletions packages/app/test/jobs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -721,14 +721,15 @@ test("run table headers sort every column accessibly and persist in the URL", as
await page.goto(origin + `/jobs/${jobId}`);
const table = page.getByRole("table");
await table.getByRole("columnheader").nth(0).getByRole("button").waitFor();
assert.deepEqual(await table.locator("thead th").allTextContents(), ["Status", "Run", "Elapsed", "Created", "Execution"]);
assert.equal(await table.getByRole("columnheader", { name: /Execution/ }).count(), 1);
for (const index of [0, 1, 3, 4]) assert.equal(await table.getByRole("columnheader").nth(index).getByRole("button").count(), 1);
assert.deepEqual(await table.locator("thead th").allTextContents(), ["Status", "Run", "Elapsed", "Created"]);
assert.equal(await table.getByRole("columnheader", { name: /Execution/ }).count(), 0);
for (const index of [0, 1, 3]) assert.equal(await table.getByRole("columnheader").nth(index).getByRole("button").count(), 1);
const runButton = page.getByRole("button", { name: "Run job", exact: true }), optionsButton = page.getByRole("button", { name: "More run options", exact: true });
const runBox = await runButton.boundingBox(), optionsBox = await optionsButton.boundingBox();
assert.equal(runBox.x + runBox.width, optionsBox.x);
const runHeader = table.getByRole("button", { name: /Run, not sorted/ });
const widths = await table.locator("thead th").evaluateAll(cells => cells.map(cell => Math.round(cell.getBoundingClientRect().width)));
assert.ok(widths[1] > widths[2], "Run column is wider than Elapsed");
await runHeader.focus(); await page.keyboard.press("Enter"); await page.waitForURL(`**/jobs/${jobId}?sort=run&direction=asc`);
assert.equal(await table.getByRole("columnheader", { name: /Run/ }).getAttribute("aria-sort"), "ascending");
assert.deepEqual(await table.locator("thead th").evaluateAll(cells => cells.map(cell => Math.round(cell.getBoundingClientRect().width))), widths);
Expand Down
9 changes: 6 additions & 3 deletions packages/app/test/runs.browser.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -182,17 +182,20 @@ test("job run history restores its cursor on direct refresh and ignores legacy f
assert.equal(new URL(page.url()).searchParams.get("cursor"), "next-cursor"); assert.ok(requests.every(url => url.searchParams.get("jobId") === jobId && url.searchParams.get("limit") === "30" && !url.searchParams.has("contextQuery") && !url.searchParams.has("state"))); await context.close();
});
test("job run history keeps the table visible while sorting and puts status first", async () => {
const { context, page } = await setup(); let releaseSorted;
const { context, page } = await setup(); let releaseSorted; const createdAt = new Date(Date.now() - 5 * 60 * 1000).toISOString();
const sorted = new Promise(resolve => { releaseSorted = resolve; });
await page.route(`**/api/v1/jobs/${jobId}`, route => route.fulfill({ json: { id: jobId, name: "Job", enabled: true, model: "", agentKind: "codex", concurrencyLimit: 1, runningCount: 0, promptTemplate: "Prompt", triggers: [] } }));
await page.route("**/api/v1/runs?**", async route => {
const url = new URL(route.request().url());
if (url.searchParams.has("sort")) { await sorted; return route.fulfill({ json: { items: [{ id: runId, run_name: "Sorted run", state: "failed", created_at: time, agent_kind: "codex" }], nextCursor: null } }); }
return route.fulfill({ json: { items: [{ id: runId, run_name: "Initial run", state: "succeeded", created_at: time, agent_kind: "codex" }], nextCursor: null } });
if (url.searchParams.has("sort")) { await sorted; return route.fulfill({ json: { items: [{ id: runId, run_name: "Sorted run", state: "failed", created_at: createdAt, agent_kind: "codex" }], nextCursor: null } }); }
return route.fulfill({ json: { items: [{ id: runId, run_name: "Initial run", state: "succeeded", created_at: createdAt, agent_kind: "codex" }], nextCursor: null } });
});
await page.goto(origin + `/jobs/${jobId}`); const table = page.getByRole("region", { name: "Runs table" });
await table.getByRole("link", { name: "Initial run", exact: true }).waitFor();
assert.equal(await table.locator("thead th").first().textContent(), "Status");
assert.equal(await table.getByRole("columnheader", { name: "Execution" }).count(), 0);
assert.equal(await table.getByRole("columnheader", { name: "Created" }).count(), 1);
await table.getByText("5 minutes ago", { exact: true }).waitFor();
await table.getByRole("button", { name: /Run, not sorted/ }).click(); await page.waitForURL(`**/jobs/${jobId}?sort=run&direction=asc`);
assert.equal(await page.getByText("Loading run history…", { exact: true }).count(), 0);
assert.equal(await table.getByRole("link", { name: "Initial run", exact: true }).count(), 1);
Expand Down
Loading