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: 5 additions & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +1175,9 @@ export interface paths {
};
/**
* List runs
* @description Requires the runs:read scope.
* @description Returns tenant-authorized runs. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, runs remain newest-created first.
*
* Requires the runs:read scope.
*
* Accepts a scoped bearer token or interactive owner session.
*/
Expand Down Expand Up @@ -4895,6 +4897,8 @@ export interface operations {
jobId?: string;
state?: "queued" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "succeeded" | "stopping" | "stopped";
contextQuery?: string;
sort?: "run" | "status" | "created" | "agent";
direction?: "asc" | "desc";
limit?: number;
cursor?: string;
};
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,7 @@ export const API_ROUTES: RouteContract[] = [
"runs:read",
{
summary: "List runs",
description: "Returns tenant-authorized runs. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, runs remain newest-created first.",
responses: {
"200": {
description: "Paginated runs",
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ export const matchRuleSchema = z.object({
export const listRunsSchema = z.object({
jobId: z.string().min(1).optional(), state: runStateSchema.optional(),
contextQuery: z.string().min(1).max(50_000).optional(),
sort: z.enum(["run", "status", "created", "agent"]).optional(),
direction: z.enum(["asc", "desc"]).optional(),
limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(),
});
}).refine(value => !value.direction || value.sort, { message: "direction requires sort" });
export const runIdSchema = z.object({ runId: z.string().min(1) });

const webhookCommonSchema = z.object({ conditions: conditionsSchema.optional() });
Expand Down
33 changes: 27 additions & 6 deletions packages/api/src/postgres/run-query-repository.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
import { traceRevisionSql } from "../run-read-contracts";
import type { Database } from "./database";

const encodeCursor = (createdAt: Date, id: string) => btoa(JSON.stringify([createdAt.toISOString(), id])).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
const decodeCursor = (value?: string | null): [string, string] | null => { if (!value) return null; try { const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4), parsed = JSON.parse(atob(padded)); return Array.isArray(parsed) && parsed.length === 2 ? [String(parsed[0]), String(parsed[1])] : null; } catch { return null; } };
const encodeCursor = (value: unknown[]) => btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
const decodeCursor = (value?: string | null): unknown[] | null => { if (!value) return null; try { const padded = value.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((value.length + 3) % 4), parsed = JSON.parse(atob(padded)); return Array.isArray(parsed) ? parsed : null; } catch { return null; } };

const sortExpressions = {
run: "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run')",
status: "r.state",
created: "r.created_at",
agent: "r.agent_kind",
} as const;
type RunSort = keyof typeof sortExpressions;

export class RunQueryRepository {
constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); }
async list(query: URLSearchParams) {
const limit = Math.max(1, Math.min(100, Number(query.get("limit") ?? 50))), cursor = decodeCursor(query.get("cursor")), values: unknown[] = [this.tenantId], clauses = ["r.tenant_id=$1"];
const limit = Math.max(1, Math.min(100, Number(query.get("limit") ?? 50))), cursor = decodeCursor(query.get("cursor")), sortParam = query.get("sort"), sort = sortParam && Object.hasOwn(sortExpressions, sortParam) ? sortParam as RunSort : null, direction = sort ? (query.get("direction") === "desc" ? "DESC" : "ASC") : "DESC", values: unknown[] = [this.tenantId], clauses = ["r.tenant_id=$1"];
if (query.get("jobId")) { values.push(query.get("jobId")); clauses.push(`r.job_id=$${values.length}`); }
if (query.get("state")) { values.push(query.get("state") === "done" ? ["done", "succeeded"] : [query.get("state")]); clauses.push(`r.state=ANY($${values.length}::text[])`); }
if (query.get("contextQuery")) { values.push(`%${query.get("contextQuery")}%`); clauses.push(`i.context::text ILIKE $${values.length}`); }
if (cursor) { values.push(cursor[0], cursor[1]); clauses.push(`(r.created_at,r.id)<($${values.length - 1}::timestamptz,$${values.length}::uuid)`); }
if (sort && cursor?.length === 5 && cursor[0] === sort && cursor[1] === direction.toLowerCase()) {
const expression = sortExpressions[sort], nullFlag = `(CASE WHEN ${expression} IS NULL THEN 1 ELSE 0 END)`, after = direction === "ASC" ? ">" : "<";
values.push(Number(cursor[2]), cursor[3] ?? null, cursor[4]);
const valuePlaceholder = sort === "created" ? `$${values.length - 1}::timestamptz` : `$${values.length - 1}`;
clauses.push(`(${nullFlag} > $${values.length - 2} OR (${nullFlag} = $${values.length - 2} AND ((${expression} ${after} ${valuePlaceholder}) OR (${expression} IS NOT DISTINCT FROM ${valuePlaceholder} AND r.id ${after} $${values.length}::uuid))))`);
} else if (!sort && cursor?.length === 2) {
values.push(cursor[0], cursor[1]); clauses.push(`(r.created_at,r.id)<($${values.length - 1}::timestamptz,$${values.length}::uuid)`);
}
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<any>(`SELECT r.id,r.job_id,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
FROM app.runs r 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 WHERE ${clauses.join(" AND ")} ORDER BY r.created_at DESC,r.id DESC LIMIT $${values.length}`, values);
FROM app.runs r 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 WHERE ${clauses.join(" AND ")} ORDER BY ${order} LIMIT $${values.length}`, values);
const rows = result.rows.slice(0, limit), hasMore = result.rows.length > limit;
return { items: rows, nextCursor: hasMore && rows.length ? encodeCursor(rows.at(-1).created_at, rows.at(-1).id) : null };
const last = rows.at(-1);
const nextCursor = hasMore && last ? sort ? (() => {
const value = sort === "run" ? (last.run_name || last.issue_title || "Run") : last[sort === "status" ? "state" : sort === "created" ? "created_at" : "agent_kind"];
return encodeCursor([sort, direction.toLowerCase(), sort === "run" || value != null ? 0 : 1, value, last.id]);
})() : encodeCursor([last.created_at, last.id]) : null;
return { items: rows, nextCursor };
}
async get(runId: string) {
return (await this.database.pool.query<any>(`SELECT r.*,j.name job_name,jr.started_at,jr.encrypted_prompt,i.source invocation_source,i.claim_key invocation_claim_key,i.trigger_id invocation_trigger_id,i.context,i.occurrence,i.created_at invocation_created_at
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function createMcpServer(service: ApiService): McpServer {
});
tool("list_exe_connections", "List safe metadata for saved exe.dev connections. API tokens are never returned.", z.object({}), () => service.listExeConnections());
tool("list_github_installations", "List connected GitHub App installations, including the installation IDs needed by GitHub Job triggers. Credentials are never returned.", z.object({}), () => service.listGitHubInstallations());
tool("list_runs", "List authoritative job runs by job ID, state, and an optional case-insensitive literal substring of triggered context. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("list_runs", "List authoritative job runs by job ID, state, an optional case-insensitive literal substring of triggered context, and validated sort field/direction. Sorting is applied before cursor pagination with deterministic ID tie-breaking. Automatic webhook, schedule, and lifecycle signals coalesce, so query runs and the provider API for authoritative work. Context matches include only a bounded excerpt.", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("get_run", "Get a run with its rendered prompt, full triggered context, invocation metadata, execution metadata, output, and activity. For manual invocations, invocation.idempotency_key is the client-reusable value; invocation.claim_key is internal.", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("get_run_diagnostics", "Get credential-safe launch, prompt delivery, output capture, claim release, cleanup, and activity diagnostics for a run.", runIdSchema, ({ runId }: any) => service.getRunDiagnostics(runId));
tool("stop_run", "Stop an active run", runIdSchema, ({ runId }: any) => service.stopRun(runId));
Expand Down
6 changes: 4 additions & 2 deletions packages/api/test/api-boundary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,15 @@ describe("Worker OpenAPI request/response boundaries", () => {
.spyOn(ApiService.prototype, "listRuns")
.mockResolvedValue({ items: [], nextCursor: null });
await assertResponse(
await request("GET", "/api/v1/runs?limit=100"),
await request("GET", "/api/v1/runs?limit=100&sort=agent&direction=desc"),
"GET",
"/api/v1/runs",
200,
);
expect(list.mock.calls[0][0].get("limit")).toBe("100");
for (const query of ["limit=0", "limit=101", "limit=NaN", "state=invalid"])
expect(list.mock.calls[0][0].get("sort")).toBe("agent");
expect(list.mock.calls[0][0].get("direction")).toBe("desc");
for (const query of ["limit=0", "limit=101", "limit=NaN", "state=invalid", "sort=invalid", "direction=asc"])
await assertResponse(
await request("GET", "/api/v1/runs?" + query),
"GET",
Expand Down
6 changes: 6 additions & 0 deletions packages/api/test/api-contract.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
isDeclaredApiOperation,
matchApiOperation,
} from "../src/api-contract";
import { listRunsSchema } from "../src/flow-schemas";

export const openapi = parse(
readFileSync(new URL("../../docs/openapi.yaml", import.meta.url), "utf8"),
Expand All @@ -24,6 +25,11 @@ const methods = new Set([
]);

describe("versioned API contract", () => {
it("validates run sorting fields and directions", () => {
expect(listRunsSchema.safeParse({ sort: "agent", direction: "desc" }).success).toBe(true);
expect(listRunsSchema.safeParse({ sort: "not-a-column" }).success).toBe(false);
expect(listRunsSchema.safeParse({ direction: "asc" }).success).toBe(false);
});
it("has full bidirectional method/path equality with the executable catalog", () => {
const documented = Object.entries(openapi.paths).flatMap(([path, item]) =>
Object.keys(item as object)
Expand Down
30 changes: 30 additions & 0 deletions packages/api/test/postgres-run-query-repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,34 @@ describe("run timing queries", () => {
expect(sql).toContain("jr.tenant_id=r.tenant_id AND jr.id=r.id");
}
});

it.each([
["run", "asc", "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run') ASC"],
["run", "desc", "COALESCE(NULLIF(r.run_name, ''), NULLIF(r.issue_title, ''), 'Run') DESC"],
["status", "asc", "r.state ASC"],
["status", "desc", "r.state DESC"],
["created", "asc", "r.created_at ASC"],
["created", "desc", "r.created_at DESC"],
["agent", "asc", "r.agent_kind ASC"],
["agent", "desc", "r.agent_kind DESC"],
] as const)("sorts %s %s before pagination with ID tie-breaking", async (sort, direction, ordering) => {
const rows = [{ id: "00000000-0000-4000-8000-000000000001", run_name: "Alpha", issue_title: "", state: "failed", agent_kind: "codex", created_at: new Date("2026-09-18T12:00:00Z") }, { id: "00000000-0000-4000-8000-000000000002", run_name: "Beta", issue_title: "", state: "succeeded", agent_kind: "claude", created_at: new Date("2026-09-18T12:01:00Z") }];
const query = vi.fn(async () => ({ rows }));
const result = await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams({ sort, direction, limit: "1" }));
const [sql, values] = query.mock.calls[0] as unknown as [string, unknown[]];
expect(sql).toContain(`ORDER BY CASE WHEN`);
expect(sql).toContain(ordering);
expect(sql).toContain("r.id");
expect(values).toEqual(["tenant", 2]);
expect(result.nextCursor).toBeTruthy();
});

it("uses a sort-aware cursor so the next page cannot restart or cross sort orders", async () => {
const query = vi.fn(async () => ({ rows: [{ id: "00000000-0000-4000-8000-000000000002", run_name: "Beta", issue_title: "", state: "succeeded", agent_kind: "codex", created_at: new Date("2026-09-18T12:01:00Z") }] }));
const cursor = btoa(JSON.stringify(["run", "asc", 0, "Alpha", "00000000-0000-4000-8000-000000000001"]));
await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams({ sort: "run", direction: "asc", cursor }));
const [sql, values] = query.mock.calls[0] as unknown as [string, unknown[]];
expect(sql).toContain("IS NOT DISTINCT FROM");
expect(values).toEqual(["tenant", 0, "Alpha", "00000000-0000-4000-8000-000000000001", 51]);
});
});
2 changes: 1 addition & 1 deletion packages/app/src/features/jobs/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function jobsRoutes(root: AnyRootRoute) {
component: lazyRouteComponent(() => import("./list"), "JobsList"),
});
const job = createRoute({ getParentRoute: () => root, path: "/jobs/$jobId", beforeLoad: guard,
validateSearch: (s: Record<string, unknown>) => ({ cursor: typeof s.cursor === "string" ? s.cursor : undefined, previous: typeof s.previous === "string" ? s.previous.slice(0, 20_000) : undefined }),
validateSearch: (s: Record<string, unknown>) => ({ cursor: typeof s.cursor === "string" ? s.cursor : undefined, previous: typeof s.previous === "string" ? s.previous.slice(0, 20_000) : undefined, sort: ["run", "status", "created", "agent"].includes(String(s.sort)) ? s.sort as "run" | "status" | "created" | "agent" : undefined, direction: s.direction === "asc" || s.direction === "desc" ? s.direction : undefined }),
loader: ({ params }) => queryClient.ensureQueryData(jobQuery(params.jobId)),
component: lazyRouteComponent(() => import("./detail"), "JobDetail"),
});
Expand Down
Loading
Loading