diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index ab539f12..1ed8b48d 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1537,11 +1537,12 @@ export interface components { created_at: string; updated_at: string; started_at: string | null; - estimated_time?: { + elapsed_time?: ({ + duration: number; + } | { low: number; - median: number; high: number; - } | null; + }) | null; } & { [key: string]: unknown; }; @@ -1571,11 +1572,12 @@ export interface components { created_at: string; updated_at: string; started_at: string | null; - estimated_time?: { + elapsed_time?: ({ + duration: number; + } | { low: number; - median: number; high: number; - } | null; + }) | null; }[]; nextCursor: string | null; }; diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 4f6830e5..1c7d03a6 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -32,7 +32,11 @@ export class RunQueryRepository { } values.push(limit + 1); const order = sort ? `CASE WHEN ${sortExpressions[sort]} IS NULL THEN 1 ELSE 0 END ASC, ${sortExpressions[sort]} ${direction} NULLS LAST, r.id ${direction}` : "r.created_at DESC,r.id DESC"; - const result = await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,r.state,r.provider,r.execution_backend_kind backend_kind,r.execution_capabilities capabilities,r.destination_url,r.artifact_state,r.artifact_error,r.created_at,r.updated_at,jr.started_at,e.estimated_time + const result = await this.database.pool.query(`SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,r.state,r.provider,r.execution_backend_kind backend_kind,r.execution_capabilities capabilities,r.destination_url,r.artifact_state,r.artifact_error,r.created_at,r.updated_at,jr.started_at, + CASE WHEN r.state IN ('succeeded','failed','stopped') AND jr.started_at IS NOT NULL AND jr.updated_at >= jr.started_at + THEN json_build_object('duration', round(EXTRACT(EPOCH FROM (jr.updated_at - jr.started_at)))) + WHEN r.state NOT IN ('succeeded','failed','stopped') THEN e.elapsed_time + END elapsed_time FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id LEFT JOIN LATERAL ( WITH durations AS ( @@ -40,12 +44,11 @@ export class RunQueryRepository { FROM app.job_runs completed WHERE completed.tenant_id=r.tenant_id AND completed.job_id=r.job_id AND completed.state IN ('succeeded','failed','stopped') AND completed.started_at IS NOT NULL AND completed.updated_at >= completed.started_at - ), stats AS (SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY duration) median FROM durations) - SELECT CASE WHEN stats.median IS NULL THEN NULL ELSE json_build_object( - 'low', round(avg(durations.duration) FILTER (WHERE durations.duration <= stats.median)), - 'median', round(stats.median), - 'high', round(avg(durations.duration) FILTER (WHERE durations.duration >= stats.median)) - ) END estimated_time FROM durations CROSS JOIN stats GROUP BY stats.median + ) + SELECT CASE WHEN count(durations.duration) = 0 THEN NULL ELSE json_build_object( + 'low', round(min(durations.duration)), + 'high', round(max(durations.duration)) + ) END elapsed_time FROM durations ) e ON true WHERE ${clauses.join(" AND ")} ORDER BY ${order} LIMIT $${values.length}`, values); const rows = result.rows.slice(0, limit), hasMore = result.rows.length > limit; diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index 9c5c9203..d88ceb6b 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -18,7 +18,10 @@ export const revisionTracePage = z.object({ items: z.array(traceEventResponse), export const traceRevisionSql = "jsonb_build_array(c.generation,p.source_kind,p.artifact_sha256,p.parser_version,p.updated_at)::text"; export const runSummaryResponse = z.object({ id: z.string(), job_id: z.string(), project_id: z.string().optional(), project_name: z.string().optional(), job_name: z.string(), issue_id: z.string(), issue_url: z.string().nullable(), issue_title: z.string(), run_name: z.string(), agent_name: z.string(), workspace_name: z.string(), agent_kind: z.string(), state: z.enum([...executionState.options, "done", "ignored"]), provider: z.string(), backend_kind: z.string(), capabilities: z.array(z.string()), destination_url: z.string().nullable(), artifact_state: z.enum(["pending", "collecting", "stored", "partial", "failed"]), artifact_error: z.string().nullable(), created_at: z.string(), updated_at: z.string(), started_at: z.string().nullable(), - estimated_time: z.object({ low: z.number(), median: z.number(), high: z.number() }).nullable().optional(), + elapsed_time: z.union([ + z.object({ duration: z.number() }), + z.object({ low: z.number(), high: z.number() }), + ]).nullable().optional(), }); export const runPageResponse = z.object({ items: z.array(runSummaryResponse), nextCursor: z.string().nullable() }); // Public JSON after serialization: enumerate known safe fields and keep opaque diff --git a/packages/app/src/features/runs/history.tsx b/packages/app/src/features/runs/history.tsx index 8a065b83..1738ceca 100644 --- a/packages/app/src/features/runs/history.tsx +++ b/packages/app/src/features/runs/history.tsx @@ -2,7 +2,7 @@ import { Button, RunStatusDot, buttonClasses, SortableHeader, StatusHeader, type import { Link, useNavigate, useSearch } from "@tanstack/react-router"; import { useQuery } from "@tanstack/react-query"; import { historyQuery } from "./queries"; -import { formatEstimatedTime } from "../../shared/estimated-time"; +import { formatElapsedTime } from "../../shared/elapsed-time"; export type HistorySort = "run" | "status" | "created" | "agent"; export type HistorySearch = { cursor?: string; previous?: string; states?: RunStatus[]; sort?: HistorySort; direction?: "asc" | "desc" }; export function RunHistory({ jobId }: { jobId: string }) { @@ -23,11 +23,11 @@ export function RunHistory({ jobId }: { jobId: string }) { return
{runs.isPending &&

Loading run history…

}{runs.error &&

{runs.error.message}

} {runs.data && <> - {columns.slice(1, 2).map(([column, label]) => sortColumn(column)} />)}{columns.slice(2).map(([column, label]) => sortColumn(column)} />)} + {columns.slice(1, 2).map(([column, label]) => sortColumn(column)} />)}{columns.slice(2).map(([column, label]) => sortColumn(column)} />)}{runs.data.items.map(run => - + )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
Estimated
Elapsed
{run.run_name || run.issue_title || "Run"}{run.estimated_time ? `${formatEstimatedTime(run.estimated_time.low)}–${formatEstimatedTime(run.estimated_time.median)}–${formatEstimatedTime(run.estimated_time.high)}` : "—"}{run.agent_kind}{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}{run.agent_kind}
{search.states?.length ? <>

No runs match the selected statuses.

: "No runs found."}
} ; return
{runs.isPending &&

Loading runs…

}{runs.error &&

{runs.error.message}

} - {runs.data && <>{statusHeader}{sortableHeader("job", "Job name")}{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
Project nameEstimated
{run.project_id && run.project_name ? {run.project_name} : —}{run.job_name}{run.run_name || "Run"}{run.estimated_time ? `${formatEstimatedTime(run.estimated_time.low)}–${formatEstimatedTime(run.estimated_time.median)}–${formatEstimatedTime(run.estimated_time.high)}` : "—"}
{search.states?.length ? <>

No runs match the selected statuses.

: jobId ? "No runs found." : "No runs yet"}
} + {runs.data && <>{statusHeader}{sortableHeader("job", "Job name")}{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => )}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
Project nameElapsed
{run.project_id && run.project_name ? {run.project_name} : —}{run.job_name}{run.run_name || "Run"}{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}
{search.states?.length ? <>

No runs match the selected statuses.

: jobId ? "No runs found." : "No runs yet"}
} {pagination}
; } diff --git a/packages/app/src/shared/estimated-time.ts b/packages/app/src/shared/elapsed-time.ts similarity index 53% rename from packages/app/src/shared/estimated-time.ts rename to packages/app/src/shared/elapsed-time.ts index 3826748e..7def802e 100644 --- a/packages/app/src/shared/estimated-time.ts +++ b/packages/app/src/shared/elapsed-time.ts @@ -1,7 +1,13 @@ -export const formatEstimatedTime = (seconds: number) => { +type ElapsedTime = { duration: number } | { low: number; high: number }; + +const formatSeconds = (seconds: number) => { if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60), remainder = seconds % 60; if (minutes < 60) return remainder ? `${minutes}m ${remainder}s` : `${minutes}m`; const hours = Math.floor(minutes / 60), remainingMinutes = minutes % 60; return remainingMinutes ? `${hours}h ${remainingMinutes}m` : `${hours}h`; }; + +export const formatElapsedTime = (elapsed: ElapsedTime) => "duration" in elapsed + ? formatSeconds(elapsed.duration) + : `${formatSeconds(elapsed.low)}–${formatSeconds(elapsed.high)}`; diff --git a/packages/app/test/jobs.browser.test.mjs b/packages/app/test/jobs.browser.test.mjs index 5187cf6d..84e9803e 100644 --- a/packages/app/test/jobs.browser.test.mjs +++ b/packages/app/test/jobs.browser.test.mjs @@ -350,7 +350,7 @@ 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", "Estimated", "Created", "Agent"]); + assert.deepEqual(await table.locator("thead th").allTextContents(), ["Status", "Run", "Elapsed", "Created", "Agent"]); assert.equal(await table.getByRole("columnheader", { name: /Agent/ }).count(), 1); for (const index of [0, 1, 3, 4]) 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 }); diff --git a/packages/app/test/runs.browser.test.mjs b/packages/app/test/runs.browser.test.mjs index 9c3fc1c0..1cf886cb 100644 --- a/packages/app/test/runs.browser.test.mjs +++ b/packages/app/test/runs.browser.test.mjs @@ -10,12 +10,12 @@ after(async () => { await browser?.close(); if (server) await new Promise(resolv async function setup() { const context = await browser.newContext(), page = await context.newPage(); page.setDefaultTimeout(10000); await page.route("**/api/v1/session", route => route.fulfill({ json: { authenticated: true, user: { id: "owner", email: "owner@example.test" }, workspace: { id: "tenant", name: "Workspace" }, capabilities: [], expiresAt: "2026-10-10T00:00:00Z" } })); return { context, page }; } test("all-jobs runs index uses a tenant-scoped page, navigation, refresh, and created time", async () => { const { context, page } = await setup(); const requests = []; let refreshes = 0; - const runs = Array.from({ length: 21 }, (_, index) => ({ id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, project_id: projectId, project_name: "Project Alpha", job_id: jobId, job_name: "Review builds", run_name: `Run ${index}`, state: index === 0 ? "running" : "succeeded", created_at: time, updated_at: time, started_at: index === 0 ? time : null, agent_kind: "codex", estimated_time: { low: 60, median: 120, high: 180 } })); +const runs = Array.from({ length: 21 }, (_, index) => ({ id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, project_id: projectId, project_name: "Project Alpha", job_id: jobId, job_name: "Review builds", run_name: `Run ${index}`, state: index === 0 ? "running" : "succeeded", created_at: time, updated_at: time, started_at: index === 0 ? time : null, agent_kind: "codex", elapsed_time: index === 0 ? { low: 60, high: 180 } : { duration: 120 } })); await page.route("**/api/v1/runs?**", route => { const url = new URL(route.request().url()); requests.push(url); refreshes++; const second = url.searchParams.has("cursor"); return route.fulfill({ json: { items: second ? [runs[20]] : runs.slice(0, 20), nextCursor: second ? null : "page-2" } }); }); await page.goto(origin + "/job-runs"); await page.getByRole("heading", { name: "Job Runs", exact: true }).waitFor(); await page.getByRole("link", { name: "Run 0", exact: true }).waitFor(); assert.equal(await page.getByRole("link", { name: "Jobs", exact: true }).count(), 0); assert.equal(await page.getByRole("link", { name: "Runs", exact: true }).evaluate(el => el.className.includes("border-factorize-500")), true); - const table = page.getByRole("table"); assert.deepEqual(await table.locator("thead th").allTextContents(), ["Status", "Project name", "Job name", "Run", "Estimated", "Created"]); assert.equal(await page.getByText("Run 0", { exact: true }).count(), 1); assert.equal(await page.getByRole("link", { name: "Project Alpha", exact: true }).first().getAttribute("href"), `/projects/${projectId}`); assert.equal(await page.locator("td time").count(), 20); assert.equal(await page.locator("td time").first().getAttribute("datetime"), time); - const firstRowCells = await table.locator("tbody tr").first().locator("td").all(); const estimatedBox = await firstRowCells[4].boundingBox(); const createdBox = await firstRowCells[5].boundingBox(); assert.ok(estimatedBox && createdBox && estimatedBox.x + estimatedBox.width <= createdBox.x, "Estimated and Created columns must not overlap"); + const table = page.getByRole("table"); assert.deepEqual(await table.locator("thead th").allTextContents(), ["Status", "Project name", "Job name", "Run", "Elapsed", "Created"]); assert.equal(await page.getByText("Run 0", { exact: true }).count(), 1); assert.equal(await page.getByText("1m–3m", { exact: true }).count(), 1); assert.equal(await page.getByText("2m", { exact: true }).count(), 19); assert.equal(await page.getByRole("link", { name: "Project Alpha", exact: true }).first().getAttribute("href"), `/projects/${projectId}`); assert.equal(await page.locator("td time").count(), 20); assert.equal(await page.locator("td time").first().getAttribute("datetime"), time); + const firstRowCells = await table.locator("tbody tr").first().locator("td").all(); const elapsedBox = await firstRowCells[4].boundingBox(); const createdBox = await firstRowCells[5].boundingBox(); assert.ok(elapsedBox && createdBox && elapsedBox.x + elapsedBox.width <= createdBox.x, "Elapsed and Created columns must not overlap"); assert.ok(requests.every(url => url.searchParams.get("limit") === "20" && !url.searchParams.has("jobId"))); await page.getByRole("link", { name: "Next page" }).click(); await page.getByRole("link", { name: "Run 20", exact: true }).waitFor(); await page.reload(); await page.getByRole("link", { name: "Run 20", exact: true }).waitFor(); assert.ok(refreshes >= 2); await context.close(); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 9830605b..b8f11e5a 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -110,21 +110,26 @@ components: type: - string - "null" - estimated_time: + elapsed_time: anyOf: - - type: object - properties: - low: - type: number - median: - type: number - high: - type: number - required: - - low - - median - - high - additionalProperties: false + - anyOf: + - type: object + properties: + duration: + type: number + required: + - duration + additionalProperties: false + - type: object + properties: + low: + type: number + high: + type: number + required: + - low + - high + additionalProperties: false - type: "null" required: - id @@ -228,21 +233,26 @@ components: type: - string - "null" - estimated_time: + elapsed_time: anyOf: - - type: object - properties: - low: - type: number - median: - type: number - high: - type: number - required: - - low - - median - - high - additionalProperties: false + - anyOf: + - type: object + properties: + duration: + type: number + required: + - duration + additionalProperties: false + - type: object + properties: + low: + type: number + high: + type: number + required: + - low + - high + additionalProperties: false - type: "null" required: - id