From 020fae315cf8ef69761ce9c905cba8495533a7c0 Mon Sep 17 00:00:00 2001 From: "exe.dev user" Date: Tue, 10 Nov 2026 22:28:58 +0000 Subject: [PATCH] Bound job summary pagination with server sorting --- packages/api-client/src/schema.d.ts | 8 +- packages/api/src/api-contract.ts | 2 +- packages/api/src/flow-service.ts | 4 +- packages/api/src/job-contracts.ts | 15 +- .../src/postgres/job-summary-repository.ts | 129 ++++++++++++++---- packages/api/test/api-boundary.test.ts | 1 + .../api/test/job-summaries.postgres.test.ts | 36 ++++- packages/app/src/features/jobs/queries.ts | 32 +---- packages/app/src/features/jobs/routes.tsx | 3 +- packages/app/src/features/projects/routes.tsx | 4 +- packages/app/test/jobs.browser.test.mjs | 71 +++++++++- packages/docs/openapi.yaml | 46 +++++-- 12 files changed, 267 insertions(+), 84 deletions(-) diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 95dc0a55..5d5a4880 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -931,7 +931,7 @@ export interface paths { }; /** * List bounded job summaries - * @description Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. + * @description Additive bounded list representation. Omitted sort preserves legacy immutable UUID descending; updated preserves updated time descending with UUID descending ties. active sorts jobs with live runs first, then name and UUID ascending; running sorts numeric live-run counts in direction with name and UUID ascending ties; title sorts name in direction with UUID ascending ties. Name ordering uses the PostgreSQL en-US ICU collation. Non-ID sorts return opaque cursors bound to their sort and direction; keep filters and sort unchanged between pages. Live run-count changes can move jobs between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. * * Requires the jobs:read scope. * @@ -4308,7 +4308,8 @@ export interface operations { cursor?: string; q?: string; enabled?: "true" | "false"; - sort?: "id" | "updated"; + sort?: "id" | "updated" | "active" | "running" | "title"; + direction?: "asc" | "desc"; }; header?: never; path?: never; @@ -4364,7 +4365,8 @@ export interface operations { cursor?: string; q?: string; enabled?: "true" | "false"; - sort?: "id" | "updated"; + sort?: "id" | "updated" | "active" | "running" | "title"; + direction?: "asc" | "desc"; }; header?: never; path?: never; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index dfeaf460..cf0c6c99 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -645,7 +645,7 @@ export const API_ROUTES: RouteContract[] = [ ), route("GET", "/api/v1/job-summaries", "flows:read", { summary: "List bounded job summaries", - description: "Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.", + description: "Additive bounded list representation. Omitted sort preserves legacy immutable UUID descending; updated preserves updated time descending with UUID descending ties. active sorts jobs with live runs first, then name and UUID ascending; running sorts numeric live-run counts in direction with name and UUID ascending ties; title sorts name in direction with UUID ascending ties. Name ordering uses the PostgreSQL en-US ICU collation. Non-ID sorts return opaque cursors bound to their sort and direction; keep filters and sort unchanged between pages. Live run-count changes can move jobs between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array.", responses: { "200": { description: "Summary page", content: { "application/json": { schema: jsonSchema(jobSummaryPage, "output") } } } }, }, (service, { query }) => service.listJobSummaries(query), { query: jobPageQuery }), route("GET", "/api/v1/job-selector", "flows:read", { diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index 48858d1a..f5bb9bc4 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -11,7 +11,7 @@ import { nextOccurrence, validateScheduleConfig } from "./schedule"; import { databaseFor } from "./postgres/database"; import { IdentityRepository } from "./postgres/identity-repository"; import { AccessTokenRepository } from "./postgres/access-token-repository"; -import { JobSummaryRepository } from "./postgres/job-summary-repository"; +import { InvalidJobSummaryCursor, JobSummaryRepository } from "./postgres/job-summary-repository"; import { jobResponse } from "./job-contracts"; import type { JobPageQuery } from "./job-contracts"; import { PostgresJobRepository, StaleJobEdit } from "./postgres/job-repository"; @@ -260,7 +260,7 @@ export class ApiService { } async stopRun(runId: string) { await this.authorize("runs:cancel"); const stopped = await new RunQueryRepository(databaseFor(this.env), this.auth.tenantId).stop(runId); if (!stopped) throw new ServiceError(409, "operation_failed", "Run is not active"); if (this.env.SCHEDULER) await this.env.SCHEDULER.get(this.env.SCHEDULER.idFromName("global")).fetch("https://scheduler/wake", { method: "POST" }); return stopped; } killRun(runId: string) { return this.stopRun(runId); } - async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); return new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } + async listJobSummaries(input: JobPageQuery, selector = false) { await this.authorize("jobs:read"); try { return await new JobSummaryRepository(databaseFor(this.env), this.auth.tenantId).page(input, selector); } catch (error) { if (error instanceof InvalidJobSummaryCursor) throw new ServiceError(400, "invalid_request", error.message); throw error; } } async listJobs() { await this.authorize("jobs:read"); const jobs = await this.jobs().list(), stats = await this.jobStatistics(jobs.map(job => job.id)); return Promise.all(jobs.map(job => this.presentJob(job, stats.get(job.id) ?? { running_count: "0", last_run_state: null }))); } async getJob(jobId: string) { await this.authorize("jobs:read"); const job = await this.jobs().getJob(jobId); if (!job) throw new ServiceError(404, "not_found", "Job not found"); return this.presentJob(job); } async listProjects(options?: { limit?: number; sort?: "name" | "updated" }) { await this.authorize("projects:read"); return this.projects().list(options); } diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index f2dac38f..fe83d482 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -4,10 +4,17 @@ import { jobInputSchema, scopeSchema, triggerSchema, webhookTriggerConfigSchema export const jobPageQuery = z.object({ projectId: z.guid().optional(), limit: z.coerce.number().int().min(1).max(100).default(30), - cursor: z.guid().optional(), + cursor: z.string().max(512).optional(), q: z.string().trim().max(120).default(""), enabled: z.enum(["true", "false"]).optional(), - sort: z.enum(["id", "updated"]).optional(), + sort: z.enum(["id", "updated", "active", "running", "title"]).optional(), + direction: z.enum(["asc", "desc"]).optional(), +}).superRefine((query, context) => { + if (!query.cursor) return; + const legacySort = query.sort === undefined || query.sort === "id" || query.sort === "updated"; + if (z.guid().safeParse(query.cursor).success !== legacySort) { + context.addIssue({ code: "custom", path: ["cursor"], message: "Cursor format does not match the selected sort" }); + } }); export type JobPageQuery = z.infer; export const jobSelectorItem = z.object({ id: z.guid(), name: z.string(), slug: z.string(), enabled: z.boolean() }); @@ -17,8 +24,8 @@ export const jobSummary = jobSelectorItem.extend({ concurrencyLimit: z.number().int(), runningCount: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(), }); -export const jobSummaryPage = z.object({ items: z.array(jobSummary), nextCursor: z.guid().nullable() }); -export const jobSelectorPage = z.object({ items: z.array(jobSelectorItem), nextCursor: z.guid().nullable() }); +export const jobSummaryPage = z.object({ items: z.array(jobSummary), nextCursor: z.string().nullable() }); +export const jobSelectorPage = z.object({ items: z.array(jobSelectorItem), nextCursor: z.string().nullable() }); const triggerIdentity = { id: z.guid(), jobId: z.guid(), slug: z.string(), createdAt: z.string(), updatedAt: z.string() }; const webhookResponse = z.discriminatedUnion("provider", [ webhookTriggerConfigSchema.options[0].extend({ secretConfigured: z.boolean().optional() }).strip(), diff --git a/packages/api/src/postgres/job-summary-repository.ts b/packages/api/src/postgres/job-summary-repository.ts index 9f04e814..0dd07e98 100644 --- a/packages/api/src/postgres/job-summary-repository.ts +++ b/packages/api/src/postgres/job-summary-repository.ts @@ -3,10 +3,23 @@ import type { JobPageQuery } from "../job-contracts"; interface SummaryRow { id: string; project_id: string; name: string; slug: string; enabled: boolean; model: string; effort: string; - agent_kind: string; execution_type: string | null; concurrency_limit: number; running_count: string; last_run_state: string | null; - created_at: Date; updated_at: Date; + agent_kind: string; execution_type: string | null; concurrency_limit: number; running_count: string; active: boolean; + last_run_state: string | null; created_at: Date; updated_at: Date; } +const nameOrder = `name COLLATE "en-US-x-icu"`; +const encodeCursor = (tuple: unknown[]) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(tuple)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); +const decodeCursor = (cursor: string) => { + try { + const padded = cursor.replaceAll("-", "+").replaceAll("_", "/") + "===".slice((cursor.length + 3) % 4); + const parsed: unknown = JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(padded), char => char.charCodeAt(0)))); + return Array.isArray(parsed) ? parsed : null; + } + catch { return null; } +}; +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +export class InvalidJobSummaryCursor extends Error {} + /** Never reads/decrypts prompts or loads triggers. One bounded query per page. */ export class JobSummaryRepository { constructor(private database: Database, private tenantId: string) { @@ -14,34 +27,104 @@ export class JobSummaryRepository { } async page(input: JobPageQuery, selector = false) { const sort = input.sort ?? "id"; + const direction = sort === "active" ? "desc" : input.direction ?? "asc"; + const legacyCursor = input.cursor && uuid.test(input.cursor) ? input.cursor : null; + const cursorTuple = input.cursor && !legacyCursor ? decodeCursor(input.cursor) : null; + const values: unknown[] = [this.tenantId]; + const clauses = ["j.tenant_id=$1", "($2='' OR strpos(lower(j.name),lower($2))>0 OR strpos(lower(j.slug),lower($2))>0)"]; + let cursorClause = "TRUE"; + values.push(input.q); + values.push(input.enabled === undefined ? null : input.enabled === "true"); + clauses.push(`($3::boolean IS NULL OR j.enabled=$3)`); + values.push(input.projectId ?? null); + clauses.push(`($4::uuid IS NULL OR j.project_id=$4)`); + if (legacyCursor && (sort === "id" || sort === "updated")) { + values.push(legacyCursor); + cursorClause = `j.id<$${values.length}::uuid`; + } else if (input.cursor) { + const expectedLength = sort === "active" || sort === "running" ? 5 : sort === "title" ? 4 : 0; + const tupleValid = !!cursorTuple && (sort === "active" + ? typeof cursorTuple[2] === "boolean" && typeof cursorTuple[3] === "string" + : sort === "running" ? Number.isInteger(cursorTuple[2]) && typeof cursorTuple[3] === "string" + : sort === "title" && typeof cursorTuple[2] === "string"); + if (!cursorTuple || !tupleValid || cursorTuple.length !== expectedLength || cursorTuple[0] !== sort || cursorTuple[1] !== direction || !uuid.test(String(cursorTuple.at(-1)))) { + throw new InvalidJobSummaryCursor("Invalid job summary cursor for sort or direction"); + } + if (sort === "active") { + values.push(Number(cursorTuple[2]), String(cursorTuple[3]), String(cursorTuple[4])); + cursorClause = `(coalesce(c.active,false) < $5::boolean OR (coalesce(c.active,false)=$5::boolean AND (${nameOrder} > $6 COLLATE "en-US-x-icu" OR (${nameOrder}=$6 COLLATE "en-US-x-icu" AND j.id>$7::uuid))))`; + } else if (sort === "running") { + values.push(Number(cursorTuple[2]), String(cursorTuple[3]), String(cursorTuple[4])); + const op = direction === "asc" ? ">" : "<"; + cursorClause = `(c.running_count ${op} $5::integer OR (c.running_count=$5::integer AND (${nameOrder} > $6 COLLATE "en-US-x-icu" OR (${nameOrder}=$6 COLLATE "en-US-x-icu" AND j.id>$7::uuid))))`; + } else if (sort === "title") { + values.push(String(cursorTuple[2]), String(cursorTuple[3])); + const op = direction === "asc" ? ">" : "<"; + cursorClause = `(${nameOrder} ${op} $5 COLLATE "en-US-x-icu" OR (${nameOrder}=$5 COLLATE "en-US-x-icu" AND j.id>$6::uuid))`; + } + } + values.push(input.limit + 1); + const sortOrder = sort === "active" + ? `coalesce(c.active,false) DESC, ${nameOrder} ASC, j.id ASC` + : sort === "running" + ? `coalesce(c.running_count,0) ${direction.toUpperCase()}, ${nameOrder} ASC, j.id ASC` + : sort === "title" + ? `${nameOrder} ${direction.toUpperCase()}, j.id ASC` + : sort === "updated" + ? "j.updated_at DESC,j.id DESC" + : "j.id DESC"; + const sortsByRunCount = sort === "active" || sort === "running"; + const lastRunState = selector ? "NULL::text" : "(array_agg(r.state ORDER BY r.created_at DESC,r.id DESC))[1]"; + const summaryPages = sortsByRunCount + ? `counts AS MATERIALIZED ( + SELECT f.id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::integer running_count, + bool_or(r.state IN ('reserved','starting','running','blocked','stopping')) active, + ${lastRunState} last_run_state + FROM filtered f LEFT JOIN app.job_runs r ON r.tenant_id=$1 AND r.job_id=f.id GROUP BY f.id + ), page AS MATERIALIZED ( + SELECT j.*,coalesce(c.running_count,0) running_count,coalesce(c.active,false) active,c.last_run_state + FROM filtered j LEFT JOIN counts c ON c.id=j.id WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length} + )` + : selector + ? `page AS MATERIALIZED ( + SELECT j.*,0::integer running_count,false active,NULL::text last_run_state + FROM filtered j WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length} + )` + : `page_core AS MATERIALIZED ( + SELECT j.* FROM filtered j WHERE ${cursorClause} ORDER BY ${sortOrder} LIMIT $${values.length} + ), counts AS MATERIALIZED ( + SELECT p.id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::integer running_count, + bool_or(r.state IN ('reserved','starting','running','blocked','stopping')) active, + ${lastRunState} last_run_state + FROM page_core p LEFT JOIN app.job_runs r ON r.tenant_id=$1 AND r.job_id=p.id GROUP BY p.id + ), page AS MATERIALIZED ( + SELECT p.*,coalesce(c.running_count,0) running_count,coalesce(c.active,false) active,c.last_run_state + FROM page_core p LEFT JOIN counts c ON c.id=p.id + )`; const result = await this.database.pool.query(` - WITH page AS MATERIALIZED ( - SELECT id,project_id project_id,name,slug,enabled,model,effort,execution_config->>'agentKind' agent_kind,execution_config->>'executionType' execution_type, - concurrency_limit,created_at,updated_at - FROM app.jobs WHERE tenant_id=$1 AND ($2::uuid IS NULL OR ($7='updated' OR id<$2)) - AND ($3='' OR strpos(lower(name),lower($3))>0 OR strpos(lower(slug),lower($3))>0) - AND ($4::boolean IS NULL OR enabled=$4) - AND ($5::uuid IS NULL OR project_id=$5) - ORDER BY ${sort === "updated" ? "updated_at DESC,id DESC" : "id DESC"} LIMIT $6 - ) - SELECT p.*,s.running_count,s.last_run_state FROM page p - ${selector ? "LEFT JOIN LATERAL (SELECT '0'::text running_count,NULL::text last_run_state) s ON true" : `LEFT JOIN LATERAL ( - SELECT - (SELECT count(*)::text FROM app.job_runs active - WHERE active.tenant_id=$1 AND active.job_id=p.id - AND active.state IN ('reserved','starting','running','blocked','stopping')) running_count, - (SELECT latest.state FROM app.job_runs latest - WHERE latest.tenant_id=$1 AND latest.job_id=p.id - ORDER BY latest.created_at DESC,latest.id DESC LIMIT 1) last_run_state - ) s ON true`} - ORDER BY ${sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.id DESC"}`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.projectId ?? null, input.limit + 1, sort]); + WITH filtered AS ${sortsByRunCount ? "MATERIALIZED" : ""} ( + SELECT j.id,j.project_id,j.name,j.slug,j.enabled,j.model,j.effort,j.execution_config->>'agentKind' agent_kind, + j.execution_config->>'executionType' execution_type,j.concurrency_limit,j.created_at,j.updated_at + FROM app.jobs j WHERE ${clauses.join(" AND ")} + ), ${summaryPages} + SELECT p.* FROM page p ORDER BY ${sort === "active" ? `p.active DESC, p.name COLLATE "en-US-x-icu" ASC, p.id ASC` : sort === "running" ? `p.running_count ${direction.toUpperCase()}, p.name COLLATE "en-US-x-icu" ASC, p.id ASC` : sort === "title" ? `p.name COLLATE "en-US-x-icu" ${direction.toUpperCase()}, p.id ASC` : sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.id DESC"}`, values); const rows = result.rows.slice(0, input.limit); + const last = rows.at(-1); + const nextCursor = result.rows.length <= input.limit || !last ? null : sort === "active" + ? encodeCursor([sort, direction, last.active, last.name, last.id]) + : sort === "running" + ? encodeCursor([sort, direction, Number(last.running_count), last.name, last.id]) + : sort === "title" + ? encodeCursor([sort, direction, last.name, last.id]) + : sort === "updated" + ? last.id + : last.id; return { items: rows.map(row => ({ id: row.id, projectId: row.project_id, name: row.name, slug: row.slug, enabled: row.enabled, ...(selector ? {} : { model: row.model, effort: row.effort, agentKind: row.agent_kind, executionType: row.execution_type ?? "agent", concurrencyLimit: row.concurrency_limit, runningCount: Number(row.running_count ?? 0), lastRunState: row.last_run_state ?? null, createdAt: row.created_at.toISOString(), updatedAt: row.updated_at.toISOString() }) })), - nextCursor: result.rows.length > input.limit ? rows.at(-1)!.id : null, + nextCursor, }; } } diff --git a/packages/api/test/api-boundary.test.ts b/packages/api/test/api-boundary.test.ts index a05f376f..b88e3f7f 100644 --- a/packages/api/test/api-boundary.test.ts +++ b/packages/api/test/api-boundary.test.ts @@ -339,6 +339,7 @@ describe("Worker OpenAPI request/response boundaries", () => { await assertResponse(await request("GET", path + "?limit=2&q=Review&enabled=true"), "GET", path, 200); await assertResponse(await request("GET", path + "?limit=101"), "GET", path, 400); await assertResponse(await request("GET", path + "?cursor=broken"), "GET", path, 400); + await assertResponse(await request("GET", path + "?sort=title&cursor=00000000-0000-4000-8000-000000000001"), "GET", path, 400); await assertResponse(await request("GET", path, undefined, { auth: { ...auth, scopes: ["runs:read"] } }), "GET", path, 403); } expect(summaries).toHaveBeenCalledWith({ limit: 2, q: "Review", enabled: "true" }, true); diff --git a/packages/api/test/job-summaries.postgres.test.ts b/packages/api/test/job-summaries.postgres.test.ts index 2ba956da..7469aadd 100644 --- a/packages/api/test/job-summaries.postgres.test.ts +++ b/packages/api/test/job-summaries.postgres.test.ts @@ -6,6 +6,7 @@ import { PostgresJobRepository, StaleJobEdit } from "../src/postgres/job-reposit import { jobSummaryPage, jobSelectorPage } from "../src/job-contracts"; const url = process.env.AUTH_TEST_DATABASE_URL; +const uuidPattern = /^[0-9a-f-]{36}$/i; describe.skipIf(!url)("bounded job reads and conditional editing (PostgreSQL)", () => { let db: Database, admin: Database; const name = `summaries_test_${crypto.randomUUID().replaceAll("-", "")}`; @@ -21,6 +22,16 @@ describe.skipIf(!url)("bounded job reads and conditional editing (PostgreSQL)", await db.pool.query("INSERT INTO app.projects(tenant_id,id,name) VALUES ($1,md5(($1::uuid)::text || ':default')::uuid,'Default'),($2,md5(($2::uuid)::text || ':default')::uuid,'Default')", [tenant, other]); await db.pool.query(`INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) SELECT $1,md5(i::text)::uuid,md5(($1::uuid)::text || ':default')::uuid,'Job '||i,'job-'||i,repeat('p',50000),'{"connectionId":"local","agentKind":"codex","workspace":"ephemeral","cwd":"/home/exedev/workspace"}'::jsonb,1 FROM generate_series(1,205) i`, [tenant]); + const lateJob = "00000000-0000-4000-8000-000000000001", trigger = "00000000-0000-4000-8000-000000000002", invocation = "00000000-0000-4000-8000-000000000003", run = "00000000-0000-4000-8000-000000000004"; + await db.pool.query(`INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) VALUES ($1,$2,md5(($1::uuid)::text || ':default')::uuid,'Zulu active','zulu-active','prompt','{"connectionId":"local","agentKind":"codex"}',1)`, [tenant, lateJob]); + await db.pool.query(`INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) + VALUES ($1,'00000000-0000-4000-8000-000000000010',md5(($1::uuid)::text || ':default')::uuid,'apple','apple-lower','prompt','{"agentKind":"codex"}',1), + ($1,'00000000-0000-4000-8000-000000000011',md5(($1::uuid)::text || ':default')::uuid,'Apple','apple-upper','prompt','{"agentKind":"codex"}',1), + ($1,'00000000-0000-4000-8000-000000000012',md5(($1::uuid)::text || ':default')::uuid,'Ápple','apple-accent','prompt','{"agentKind":"codex"}',1)`, [tenant]); + await db.pool.query("UPDATE app.jobs SET name='Tie' WHERE tenant_id=$1 AND id IN (md5('204')::uuid,md5('205')::uuid)", [tenant]); + await db.pool.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,$2,$3,'manual','manual')", [tenant, trigger, lateJob]); + await db.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','test',$4,'{}')", [tenant, invocation, lateJob, trigger]); + await db.pool.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,'running','prompt')", [tenant, run, lateJob, invocation]); await db.pool.query(`INSERT INTO app.jobs(tenant_id,id,project_id,name,slug,encrypted_prompt_template,execution_config,concurrency_limit) VALUES ($1,md5('1')::uuid,md5(($1::uuid)::text || ':default')::uuid,'Private Job','private-job','secret','{}',1)`, [other]); }); @@ -40,10 +51,33 @@ describe.skipIf(!url)("bounded job reads and conditional editing (PostgreSQL)", expect(JSON.stringify(page).length).toBeLessThan(16000); ids.push(...page.items.map(item => item.id)); cursor = page.nextCursor ?? undefined; } while (cursor); - expect(ids.length).toBe(205); expect(new Set(ids).size).toBe(205); + expect(ids.length).toBe(209); expect(new Set(ids).size).toBe(209); expect(ids).toEqual([...ids].sort().reverse()); } finally { query.mockRestore(); } }); + it("orders active, running, and title pages with stable full-tuple cursors", async () => { + const repo = new JobSummaryRepository(db, tenant); + const active = await repo.page({ limit: 30, q: "", sort: "active" }); + expect(active.items[0]).toMatchObject({ name: "Zulu active", runningCount: 1 }); + expect(active.nextCursor).not.toMatch(uuidPattern); + for (const [sort, direction] of [["running", "asc"], ["running", "desc"], ["title", "asc"], ["title", "desc"], ["active", "desc"]] as const) { + const ids: string[] = []; + let cursor: string | undefined; + do { + const page = await repo.page({ limit: 30, q: "", sort, direction, cursor }); + ids.push(...page.items.map(item => item.id)); cursor = page.nextCursor ?? undefined; + } while (cursor); + expect(ids).toHaveLength(209); expect(new Set(ids).size).toBe(209); + if (sort === "title" && direction === "asc") { + expect(ids.slice(0, 3)).toEqual(["00000000-0000-4000-8000-000000000010", "00000000-0000-4000-8000-000000000011", "00000000-0000-4000-8000-000000000012"]); + const tieIds = (await db.pool.query<{ id: string }>("SELECT id FROM app.jobs WHERE tenant_id=$1 AND name='Tie'", [tenant])).rows.map(row => row.id); + expect(ids.filter(id => tieIds.includes(id))).toEqual([...tieIds].sort()); + } + } + const first = await repo.page({ limit: 2, q: "", sort: "running", direction: "asc" }); + await expect(repo.page({ limit: 2, q: "", sort: "running", direction: "desc", cursor: first.nextCursor! })).rejects.toThrow(/Invalid job summary cursor/); + await expect(repo.page({ limit: 2, q: "", sort: "title", cursor: first.nextCursor! })).rejects.toThrow(/Invalid job summary cursor/); + }); it("searches literal case-insensitive names/slugs and bounds selector data", async () => { const repo = new JobSummaryRepository(db, tenant); const page = await repo.page({ limit: 3, q: "JOB-20" }, true); diff --git a/packages/app/src/features/jobs/queries.ts b/packages/app/src/features/jobs/queries.ts index 65c8fa8b..5e197da4 100644 --- a/packages/app/src/features/jobs/queries.ts +++ b/packages/app/src/features/jobs/queries.ts @@ -5,34 +5,14 @@ export type JobsSort = "running" | "title"; export type JobsOrder = "asc" | "desc"; export type JobsSearch = { q?: string; projectId?: string; cursor?: string; enabled?: "true" | "false"; sort?: JobsSort; order?: JobsOrder }; export const jobsQuery = (search: JobsSearch) => queryOptions({ - queryKey: ["jobs", "summaries", { projectId: search.projectId, q: search.q, enabled: search.enabled, sort: search.sort, order: search.order }], + queryKey: ["jobs", "summaries", { projectId: search.projectId, q: search.q ?? "", enabled: search.enabled, cursor: search.cursor, sort: search.sort ?? "active", direction: search.sort === "running" || search.sort === "title" ? search.order ?? "asc" : undefined, limit: 30 }], queryFn: async ({ signal }) => { - // The API's UUID pages do not reflect running/title order. Collect lightweight - // summaries before paginating so active jobs on later API pages come first. - const items = []; - let cursor: string | undefined; - do { - const { data, error } = await api.GET("/api/v1/job-summaries", { signal, params: { query: { projectId: search.projectId, q: search.q ?? "", enabled: search.enabled, cursor, limit: 100 } } }); - if (!data || error) throw new Error(messageOf(error)); - items.push(...data.items); - cursor = data.nextCursor ?? undefined; - } while (cursor); - items.sort((a, b) => { - if (!search.sort) return Number(b.runningCount > 0) - Number(a.runningCount > 0) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id); - const direction = search.order === "desc" ? -1 : 1; - const comparison = search.sort === "running" - ? a.runningCount - b.runningCount - : a.name.localeCompare(b.name); - return direction * comparison || a.name.localeCompare(b.name) || a.id.localeCompare(b.id); - }); - return items; + const sort = search.sort === "running" ? "running" : search.sort === "title" ? "title" : "active"; + const { data, error } = await api.GET("/api/v1/job-summaries", { signal, params: { query: { projectId: search.projectId, q: search.q ?? "", enabled: search.enabled, cursor: search.cursor, limit: 30, sort, direction: sort === "active" ? undefined : search.order ?? "asc" } } }); + if (!data || error) throw new Error(messageOf(error)); + return data; }, - select: items => { - const cursorIndex = search.cursor ? items.findIndex(job => job.id === search.cursor) : -1; - const start = cursorIndex + 1; - const page = items.slice(start, start + 30); - return { items: page, nextCursor: start + 30 < items.length ? page.at(-1)!.id : null }; - }, staleTime: 10_000, + staleTime: 10_000, }); export const recentJobsQuery = queryOptions({ queryKey: ["jobs", "recent"], queryFn: async ({ signal }) => { const { data, error } = await api.GET("/api/v1/job-summaries", { signal, params: { query: { limit: 5, sort: "updated", q: "" } } }); if (!data || error) throw new Error(messageOf(error)); return data; }, staleTime: 10_000 }); export const jobQuery = (jobId: string) => queryOptions({ diff --git a/packages/app/src/features/jobs/routes.tsx b/packages/app/src/features/jobs/routes.tsx index 3928c3d4..a74df9b5 100644 --- a/packages/app/src/features/jobs/routes.tsx +++ b/packages/app/src/features/jobs/routes.tsx @@ -13,7 +13,8 @@ export function jobsRoutes(root: AnyRootRoute) { if (!(await queryClient.ensureQueryData(sessionQuery)).authenticated) throw redirect({ to: "/auth/login", search: { returnTo: location.href, token: undefined } }); }; const jobs = createRoute({ getParentRoute: () => root, path: "/jobs", beforeLoad: guard, - validateSearch: (s: Record) => ({ q: typeof s.q === "string" ? s.q.slice(0, 120) : "", projectId: typeof s.projectId === "string" ? s.projectId : undefined, cursor: typeof s.cursor === "string" ? s.cursor : undefined, sort: s.sort === "running" || s.sort === "title" ? s.sort : undefined, order: s.order === "asc" || s.order === "desc" ? s.order : undefined }), + validateSearch: (s: Record) => ({ q: typeof s.q === "string" ? s.q.slice(0, 120) : "", projectId: typeof s.projectId === "string" ? s.projectId : undefined, cursor: typeof s.cursor === "string" ? s.cursor : undefined, enabled: s.enabled === "true" || s.enabled === true ? "true" : s.enabled === "false" || s.enabled === false ? "false" : undefined, sort: s.sort === "running" || s.sort === "title" ? s.sort : undefined, order: s.order === "asc" || s.order === "desc" ? s.order : undefined }), + loaderDeps: ({ search }) => ({ q: search.q, projectId: search.projectId, cursor: search.cursor, enabled: search.enabled, sort: search.sort, order: search.order }), loader: ({ deps }) => queryClient.ensureQueryData(jobsQuery(deps)), component: lazyRouteComponent(() => import("./list"), "GlobalJobsList"), }); diff --git a/packages/app/src/features/projects/routes.tsx b/packages/app/src/features/projects/routes.tsx index 5eb401e3..08765184 100644 --- a/packages/app/src/features/projects/routes.tsx +++ b/packages/app/src/features/projects/routes.tsx @@ -1,4 +1,4 @@ import { createRoute, lazyRouteComponent, redirect, type AnyRootRoute } from "@tanstack/react-router"; import { queryClient } from "../../shared/query-client"; import { sessionQuery } from "../auth/session"; import { projectsQuery, projectQuery } from "./queries"; -import type { JobsSearch } from "../jobs/queries"; -export function projectsRoutes(root: AnyRootRoute) { const guard=async({location}:{location:{href:string}})=>{if(!(await queryClient.ensureQueryData(sessionQuery)).authenticated)throw redirect({to:"/auth/login",search:{returnTo:location.href,token:undefined}});}; const list=createRoute({getParentRoute:()=>root,path:"/projects",beforeLoad:guard,loader:()=>queryClient.ensureQueryData(projectsQuery),component:lazyRouteComponent(()=>import("./list"),"ProjectsList")}); const create=createRoute({getParentRoute:()=>root,path:"/projects/new",beforeLoad:guard,component:lazyRouteComponent(()=>import("./create"),"ProjectCreate")}); const validateJobsSearch = (s: Record): JobsSearch => ({ q: typeof s.q === "string" ? s.q.slice(0, 120) : "", cursor: typeof s.cursor === "string" ? s.cursor : undefined, sort: s.sort === "running" || s.sort === "title" ? s.sort : undefined, order: s.order === "asc" || s.order === "desc" ? s.order : undefined }); const detail=createRoute({getParentRoute:()=>root,path:"/projects/$projectId",beforeLoad:guard,validateSearch:validateJobsSearch,loader:({params})=>queryClient.ensureQueryData(projectQuery(params.projectId)),component:lazyRouteComponent(()=>import("./detail"),"ProjectDetail")}); const projectRuns=createRoute({getParentRoute:()=>root,path:"/projects/$projectId/runs",beforeLoad:guard,validateSearch:(s: Record) => ({cursor:typeof s.cursor === "string" ? s.cursor : undefined, previous:typeof s.previous === "string" ? s.previous : undefined, projects:undefined, jobs:undefined, states:Array.isArray(s.states) ? s.states : undefined, sort:typeof s.sort === "string" ? s.sort : undefined, direction:s.direction === "asc" || s.direction === "desc" ? s.direction : undefined}),loader:({params})=>queryClient.ensureQueryData(projectQuery(params.projectId)),component:lazyRouteComponent(()=>import("./runs"),"ProjectRuns")}); const settings=createRoute({getParentRoute:()=>root,path:"/projects/$projectId/settings",beforeLoad:guard,loader:({params})=>queryClient.ensureQueryData(projectQuery(params.projectId)),component:lazyRouteComponent(()=>import("./settings"),"ProjectSettings")}); return [list,create,detail,projectRuns,settings]; } +import { jobsQuery, type JobsSearch } from "../jobs/queries"; +export function projectsRoutes(root: AnyRootRoute) { const guard=async({location}:{location:{href:string}})=>{if(!(await queryClient.ensureQueryData(sessionQuery)).authenticated)throw redirect({to:"/auth/login",search:{returnTo:location.href,token:undefined}});}; const list=createRoute({getParentRoute:()=>root,path:"/projects",beforeLoad:guard,loader:()=>queryClient.ensureQueryData(projectsQuery),component:lazyRouteComponent(()=>import("./list"),"ProjectsList")}); const create=createRoute({getParentRoute:()=>root,path:"/projects/new",beforeLoad:guard,component:lazyRouteComponent(()=>import("./create"),"ProjectCreate")}); const validateJobsSearch = (s: Record): JobsSearch => ({ q: typeof s.q === "string" ? s.q.slice(0, 120) : "", cursor: typeof s.cursor === "string" ? s.cursor : undefined, enabled: s.enabled === "true" || s.enabled === true ? "true" : s.enabled === "false" || s.enabled === false ? "false" : undefined, sort: s.sort === "running" || s.sort === "title" ? s.sort : undefined, order: s.order === "asc" || s.order === "desc" ? s.order : undefined }); const detail=createRoute({getParentRoute:()=>root,path:"/projects/$projectId",beforeLoad:guard,validateSearch:validateJobsSearch,loaderDeps:({search})=>({q:search.q,cursor:search.cursor,enabled:search.enabled,sort:search.sort,order:search.order}),loader:({params,deps})=>{void queryClient.prefetchQuery(jobsQuery({...deps,projectId:params.projectId})).catch(()=>undefined);return queryClient.ensureQueryData(projectQuery(params.projectId));},component:lazyRouteComponent(()=>import("./detail"),"ProjectDetail")}); const projectRuns=createRoute({getParentRoute:()=>root,path:"/projects/$projectId/runs",beforeLoad:guard,validateSearch:(s: Record) => ({cursor:typeof s.cursor === "string" ? s.cursor : undefined, previous:typeof s.previous === "string" ? s.previous : undefined, projects:undefined, jobs:undefined, states:Array.isArray(s.states) ? s.states : undefined, sort:typeof s.sort === "string" ? s.sort : undefined, direction:s.direction === "asc" || s.direction === "desc" ? s.direction : undefined}),loader:({params})=>queryClient.ensureQueryData(projectQuery(params.projectId)),component:lazyRouteComponent(()=>import("./runs"),"ProjectRuns")}); const settings=createRoute({getParentRoute:()=>root,path:"/projects/$projectId/settings",beforeLoad:guard,loader:({params})=>queryClient.ensureQueryData(projectQuery(params.projectId)),component:lazyRouteComponent(()=>import("./settings"),"ProjectSettings")}); return [list,create,detail,projectRuns,settings]; } diff --git a/packages/app/test/jobs.browser.test.mjs b/packages/app/test/jobs.browser.test.mjs index 9c11e5f1..c391ab88 100644 --- a/packages/app/test/jobs.browser.test.mjs +++ b/packages/app/test/jobs.browser.test.mjs @@ -35,7 +35,7 @@ test("global jobs use the Runs-style project filter", async () => { await page.route("**/api/v1/job-summaries?**", route => { return route.fulfill({ json: { items: [{ ...summary, projectId }], nextCursor: null } }); }); - await page.goto(origin + "/jobs"); + await page.goto(origin + "/jobs?cursor=old-cursor"); const table = page.getByRole("table", { name: "Jobs", exact: true }); const projectFilter = table.getByRole("button", { name: "Filter by project Release project" }); await projectFilter.waitFor(); @@ -47,11 +47,59 @@ test("global jobs use the Runs-style project filter", async () => { await page.waitForURL(/projectId=/); const filtered = await filteredRequest; assert.equal(new URL(filtered.url()).searchParams.get("projectId"), projectId); - await table.getByRole("button", { name: /Project/ }).click(); - await page.getByRole("dialog", { name: "Project filter" }).getByRole("button", { name: "Clear project filters" }).click(); + assert.equal(new URL(filtered.url()).searchParams.has("cursor"), false); + await dialog.getByRole("button", { name: "Clear project filters" }).click(); await page.waitForFunction(() => !new URL(location.href).searchParams.has("projectId")); await context.close(); }); +test("a 1,000-job workspace loads one bounded first page and one request on Next", async () => { + const { page, context } = await contextFor({ viewport: { width: 1280, height: 844 } }); + const fixtures = Array.from({ length: 1000 }, (_, index) => ({ ...summary, id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`, name: `Job ${String(index + 1).padStart(4, "0")}` })); + fixtures[900] = { ...fixtures[900], name: "Active beyond old first 100", runningCount: 2 }; + const serverOrder = [fixtures[900], ...fixtures.filter((_, index) => index !== 900).sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id))]; + const requests = []; + await page.route("**/api/v1/job-summaries?**", route => { + const url = new URL(route.request().url()); requests.push(url); + const offset = url.searchParams.has("cursor") ? 30 : 0; + return route.fulfill({ json: { items: serverOrder.slice(offset, offset + 30), nextCursor: offset + 30 < serverOrder.length ? "server-cursor-30" : null } }); + }); + await page.goto(origin + "/jobs"); + const table = page.getByRole("table", { name: "Jobs", exact: true }); + await table.getByRole("link", { name: "Active beyond old first 100", exact: true }).waitFor(); + assert.equal(requests.length, 1); + assert.equal(requests[0].searchParams.get("limit"), "30"); + assert.equal(requests[0].searchParams.get("sort"), "active"); + assert.equal(await table.locator("tbody tr").count(), 30); + await page.getByRole("link", { name: "Next page" }).click(); + await table.getByRole("link", { name: "Job 0030", exact: true }).waitFor(); + assert.equal(requests.length, 2); + assert.equal(requests[1].searchParams.get("cursor"), "server-cursor-30"); + assert.equal(requests[1].searchParams.get("limit"), "30"); + await context.close(); +}); +test("jobs carry search and enabled filters and reset the cursor when sorting changes", async () => { + const { page, context } = await contextFor({ viewport: { width: 1280, height: 844 } }); + const requests = []; + await page.route("**/api/v1/job-summaries?**", route => { + const url = new URL(route.request().url()); requests.push(url); + return route.fulfill({ json: { items: [{ ...summary, id: jobId, name: "Filtered job" }], nextCursor: null } }); + }); + await page.goto(origin + "/jobs?q=needle&enabled=false&cursor=old-cursor&sort=running&order=desc"); + const table = page.getByRole("table", { name: "Jobs", exact: true }); + await table.getByRole("link", { name: "Filtered job", exact: true }).waitFor(); + assert.equal(requests[0].searchParams.get("q"), "needle"); + assert.equal(requests[0].searchParams.get("enabled"), "false", requests[0].href); + assert.equal(requests[0].searchParams.get("cursor"), "old-cursor"); + const nextRequest = page.waitForRequest(request => { + const url = new URL(request.url()); return url.pathname === "/api/v1/job-summaries" && url.searchParams.get("sort") === "title"; + }); + await table.getByRole("button", { name: /Title sort/ }).click(); + const sorted = new URL((await nextRequest).url()); + assert.equal(sorted.searchParams.get("q"), "needle"); + assert.equal(sorted.searchParams.get("enabled"), "false", sorted.href); + assert.equal(sorted.searchParams.has("cursor"), false); + await context.close(); +}); test("project settings can rename and describe a project", async () => { const { page, context } = await contextFor({ viewport: { width: 1280, height: 844 } }); const saved = []; @@ -140,7 +188,9 @@ for (const width of [1280, 390, 320]) for (const theme of ["light", "dark"]) tes const requests = []; await page.route("**/api/v1/job-summaries?**", route => { const url = new URL(route.request().url()); requests.push(url); - return route.fulfill({ json: { items: url.searchParams.has("cursor") ? fixtures.slice(30) : fixtures.slice(0, 30), nextCursor: url.searchParams.has("cursor") ? null : fixtures[29].id } }); + const serverOrder = [...fixtures].sort((a, b) => Number(b.runningCount > 0) - Number(a.runningCount > 0) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id)); + const offset = url.searchParams.has("cursor") ? 30 : 0; + return route.fulfill({ json: { items: serverOrder.slice(offset, offset + 30), nextCursor: offset + 30 < serverOrder.length ? "server-cursor-30" : null } }); }); await page.route(`**/api/v1/jobs/${fixtures[30].id}`, route => route.fulfill({ json: { ...fixtures[30], promptTemplate: "Template", runNameTemplate: "", executionConfigId: "local", executionConfig: { connectionId: "local", workspace: "ephemeral", cwd: "/workspace", agentKind: "codex" }, triggers: [], currentRuns: 2, maxConcurrency: 10 } })); await page.goto(origin + `/projects/${projectId}?q=Review`); @@ -171,7 +221,7 @@ for (const width of [1280, 390, 320]) for (const theme of ["light", "dark"]) tes await page.getByRole("link", { name: "Next page" }).click(); await table.getByRole("link", { name: "Idle 29", exact: true }).waitFor(); await page.reload(); await table.getByRole("link", { name: "Idle 29", exact: true }).waitFor(); await page.getByRole("link", { name: "First page" }).click(); await table.getByRole("link", { name: "Alpha running", exact: true }).waitFor(); - assert.ok(requests.every(url => url.searchParams.get("limit") === "100" && url.searchParams.get("q") === "Review")); + assert.ok(requests.every(url => url.searchParams.get("limit") === "30" && url.searchParams.get("q") === "Review" && url.searchParams.get("sort") === "active")); await table.getByRole("link", { name: "Alpha running", exact: true }).focus(); await page.keyboard.press("Enter"); await page.waitForURL(`**/jobs/${fixtures[30].id}`); await page.getByRole("heading", { name: "Alpha running", exact: true }).waitFor(); @@ -205,7 +255,16 @@ test("jobs can sort running and title in both directions with accessible state", { ...summary, id: "job-b", name: "Beta", runningCount: 3 }, { ...summary, id: "job-i", name: "Idle", runningCount: 0 }, ]; - await page.route("**/api/v1/job-summaries?**", route => route.fulfill({ json: { items: fixtures, nextCursor: null } })); + await page.route("**/api/v1/job-summaries?**", route => { + const url = new URL(route.request().url()); + const sort = url.searchParams.get("sort"), direction = url.searchParams.get("direction") ?? "asc"; + const rows = [...fixtures].sort((a, b) => { + if (sort === "running") return (Number(a.runningCount) - Number(b.runningCount)) * (direction === "asc" ? 1 : -1) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id); + if (sort === "title") return a.name.localeCompare(b.name) * (direction === "asc" ? 1 : -1) || a.id.localeCompare(b.id); + return Number(b.runningCount > 0) - Number(a.runningCount > 0) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id); + }); + return route.fulfill({ json: { items: rows, nextCursor: null } }); + }); await page.goto(origin + `/projects/${projectId}`); const table = page.getByRole("table", { name: "Jobs", exact: true }); await table.getByRole("link", { name: "Zulu", exact: true }).waitFor(); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index f65f11bd..c3032ba9 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -5127,7 +5127,7 @@ paths: get: summary: List bounded job summaries description: |- - Additive list representation, ordered by immutable UUID descending. Cursor is the last ID; filters must remain the same between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. + Additive bounded list representation. Omitted sort preserves legacy immutable UUID descending; updated preserves updated time descending with UUID descending ties. active sorts jobs with live runs first, then name and UUID ascending; running sorts numeric live-run counts in direction with name and UUID ascending ties; title sorts name in direction with UUID ascending ties. Name ordering uses the PostgreSQL en-US ICU collation. Non-ID sorts return opaque cursors bound to their sort and direction; keep filters and sort unchanged between pages. Live run-count changes can move jobs between pages. Literal case-insensitive name/slug search. No prompts or trigger configuration; statistics are batched. Existing GET /jobs remains an array. Requires the jobs:read scope. @@ -5215,11 +5215,9 @@ paths: - updatedAt additionalProperties: false nextCursor: - anyOf: - - type: string - format: uuid - pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ - - type: "null" + type: + - string + - "null" required: - items - nextCursor @@ -5269,8 +5267,7 @@ paths: required: false schema: type: string - format: uuid - pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + maxLength: 512 - name: q in: query required: false @@ -5294,6 +5291,17 @@ paths: enum: - id - updated + - active + - running + - title + - name: direction + in: query + required: false + schema: + type: string + enum: + - asc + - desc /api/v1/job-selector: get: summary: Search bounded lifecycle job options @@ -5327,11 +5335,9 @@ paths: - enabled additionalProperties: false nextCursor: - anyOf: - - type: string - format: uuid - pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ - - type: "null" + type: + - string + - "null" required: - items - nextCursor @@ -5385,8 +5391,7 @@ paths: required: false schema: type: string - format: uuid - pattern: ^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$ + maxLength: 512 - name: q in: query required: false @@ -5410,6 +5415,17 @@ paths: enum: - id - updated + - active + - running + - title + - name: direction + in: query + required: false + schema: + type: string + enum: + - asc + - desc /api/v1/projects: get: summary: List projects