From a8cafa2e6efa54efeca6d01f0cd88f5e071351b1 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Fri, 13 Nov 2026 10:52:13 +0530 Subject: [PATCH] Show every task on the Tasks board, not just the first 100 GET /api/tasks returned at most 100 tasks in board order (column position, then newest first), with no way to ask for more. New tasks get the highest position, so once a workspace had more than 100 tasks, archived ones included, a new task vanished from the board after a reload and the column counts were short. The list now pages, and the board reads every page: - listTaskPageForOrg (backend/src/tasks/repo.ts) reads one page after a cursor that carries the last task's full sort key: order_key, created_at as whole microseconds, and id. order_key sorts up and the rest down, so "after the cursor" is a later position, or the same position and an older (created_at, id). It reads one row past the limit to know whether another page follows. listTasksForOrg, which the agent's task_list tool uses, keeps its shape on top of it. - GET /api/tasks takes cursor and exclude_archived=1 and answers has_more and next_cursor next to tasks. A malformed cursor answers 400 "cursor is invalid" (backend/src/tasks/page-cursor.ts). Without a cursor the first page is the same as before. - fetchTasks (frontend/app/(library)/tasks/tasks-api.ts) asks for pages of 500 without archived tasks, which have no column, and follows next_cursor to the end. A failed page fails the read, so the board shows its error instead of part of the tasks. A task moved between two pages is shown once, and a repeated cursor stops the loop. An old backend ignores the new parameters and sends no next_cursor, so the new board reads one page as before. An old board ignores the new fields. Docs: the GET /api/tasks row in docs-site/docs/api/skills.mdx. --- backend/src/tasks/page-cursor.test.ts | 40 ++++++ backend/src/tasks/page-cursor.ts | 43 ++++++ backend/src/tasks/repo.test.ts | 132 ++++++++++++++++++ backend/src/tasks/repo.ts | 77 ++++++++-- backend/src/tasks/routes.ts | 26 +++- backend/test/tasks.test.ts | 49 +++++++ docs-site/docs/api/skills.mdx | 2 +- .../app/(library)/tasks/tasks-api.test.ts | 89 ++++++++++++ frontend/app/(library)/tasks/tasks-api.ts | 36 ++++- 9 files changed, 470 insertions(+), 24 deletions(-) create mode 100644 backend/src/tasks/page-cursor.test.ts create mode 100644 backend/src/tasks/page-cursor.ts create mode 100644 backend/src/tasks/repo.test.ts create mode 100644 frontend/app/(library)/tasks/tasks-api.test.ts diff --git a/backend/src/tasks/page-cursor.test.ts b/backend/src/tasks/page-cursor.test.ts new file mode 100644 index 000000000..ab25d954b --- /dev/null +++ b/backend/src/tasks/page-cursor.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, test } from "bun:test"; +import { encodeTaskPageCursor, parseTaskPageCursor } from "./page-cursor"; + +const CURSOR = { + orderKey: 2.5, + createdAtMicros: "1793865600123456", + id: "0b6f6bb4-4a7e-4a55-9a37-2f1b0a1b9f10", +}; + +function encodeRaw(value: unknown): string { + return Buffer.from(JSON.stringify(value), "utf8").toString("base64url"); +} + +describe("task page cursor", () => { + test("round-trips a page's last sort key, fractional and negative positions included", () => { + expect(parseTaskPageCursor(encodeTaskPageCursor(CURSOR))).toEqual(CURSOR); + const negative = { ...CURSOR, orderKey: -0.123456789012345 }; + expect(parseTaskPageCursor(encodeTaskPageCursor(negative))).toEqual(negative); + }); + + test("refuses anything that is not a cursor it made", () => { + for (const value of [ + "", + "not base64!", + "a".repeat(600), + encodeRaw({ orderKey: 1 }), + encodeRaw([1, "1793865600123456"]), + encodeRaw(["1", CURSOR.createdAtMicros, CURSOR.id]), + encodeRaw([null, CURSOR.createdAtMicros, CURSOR.id]), + encodeRaw([1, 1793865600123456, CURSOR.id]), + encodeRaw([1, "-5", CURSOR.id]), + encodeRaw([1, "1.5", CURSOR.id]), + encodeRaw([1, "999999999999999999", CURSOR.id]), + encodeRaw([1, CURSOR.createdAtMicros, "not-a-uuid"]), + Buffer.from("[1,", "utf8").toString("base64url"), + ]) { + expect(parseTaskPageCursor(value)).toBeNull(); + } + }); +}); diff --git a/backend/src/tasks/page-cursor.ts b/backend/src/tasks/page-cursor.ts new file mode 100644 index 000000000..a9f3398a9 --- /dev/null +++ b/backend/src/tasks/page-cursor.ts @@ -0,0 +1,43 @@ +/** + * The `cursor` of `GET /api/tasks`: a task page's last sort key, as opaque + * base64url text. The key is the board order, column position then newest + * first (see `listTaskPageForOrg` in ./repo). + */ +import type { TaskPageCursor } from "./repo"; + +const MAX_CURSOR_LENGTH = 512; +/** 9999-12-31T23:59:59.999999Z, the last instant Postgres timestamps reach in this form. */ +const MAX_CURSOR_MICROSECONDS = 253_402_300_799_999_999n; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function encodeTaskPageCursor(cursor: TaskPageCursor): string { + return Buffer.from( + JSON.stringify([cursor.orderKey, cursor.createdAtMicros, cursor.id]), + "utf8", + ).toString("base64url"); +} + +/** Decode a cursor from `encodeTaskPageCursor`; null for anything else. */ +export function parseTaskPageCursor(value: string): TaskPageCursor | null { + if (!value || value.length > MAX_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) return null; + let decoded: unknown; + try { + decoded = JSON.parse(Buffer.from(value, "base64url").toString("utf8")); + } catch { + return null; + } + if (!Array.isArray(decoded) || decoded.length !== 3) return null; + const [orderKey, createdAtMicros, id] = decoded as unknown[]; + if ( + typeof orderKey !== "number" || + !Number.isFinite(orderKey) || + typeof createdAtMicros !== "string" || + !/^[0-9]{1,18}$/.test(createdAtMicros) || + BigInt(createdAtMicros) > MAX_CURSOR_MICROSECONDS || + typeof id !== "string" || + !UUID_RE.test(id) + ) { + return null; + } + return { orderKey, createdAtMicros, id }; +} diff --git a/backend/src/tasks/repo.test.ts b/backend/src/tasks/repo.test.ts new file mode 100644 index 000000000..8309e9163 --- /dev/null +++ b/backend/src/tasks/repo.test.ts @@ -0,0 +1,132 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { eq, sql } from "drizzle-orm"; +import "../index"; // side-effect: run committed migrations before DB assertions +import { db } from "../db/client"; +import { tasks } from "../db/schema"; +import { createTask, listTaskPageForOrg, listTasksForOrg, type TaskPageCursor } from "./repo"; + +// Paging the task list through `listTaskPageForOrg` against the real database: +// past 100 tasks, through ties the cursor has to break, and without archived +// tasks taking places on a page. + +const orgIds: string[] = []; + +function newOrg(label: string): string { + const orgId = `org-tasks-${label}-${crypto.randomUUID()}`; + orgIds.push(orgId); + return orgId; +} + +afterAll(async () => { + for (const orgId of orgIds) await db.delete(tasks).where(eq(tasks.orgId, orgId)); +}); + +async function readAll( + orgId: string, + options: { limit: number; excludeArchived?: boolean }, +): Promise<{ titles: string[]; pages: number }> { + const titles: string[] = []; + let cursor: TaskPageCursor | null = null; + let pages = 0; + do { + const page = await listTaskPageForOrg(orgId, { scope: "all" }, { ...options, cursor }); + titles.push(...page.tasks.map((task) => task.title)); + cursor = page.nextCursor; + pages += 1; + expect(pages).toBeLessThanOrEqual(50); + } while (cursor); + return { titles, pages }; +} + +describe("task pages", () => { + test("the newest of 101 tasks is on the second page, and every task is read once", async () => { + const orgId = newOrg("101"); + for (let index = 0; index < 101; index += 1) { + await createTask({ orgId, title: `task ${index}` }); + } + + // One page of 100, in board order, stops short of the newest task. + const first = await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 100 }); + expect(first.tasks.map((task) => task.title)).toEqual( + Array.from({ length: 100 }, (_, index) => `task ${index}`), + ); + expect(first.nextCursor).not.toBeNull(); + const second = await listTaskPageForOrg( + orgId, + { scope: "all" }, + { limit: 100, cursor: first.nextCursor }, + ); + expect(second.tasks.map((task) => task.title)).toEqual(["task 100"]); + expect(second.nextCursor).toBeNull(); + + // The old one-shot read still answers its first 100 for the agent's tools. + expect(await listTasksForOrg(orgId, { scope: "all" }, 100)).toHaveLength(100); + }); + + test("a page cut inside tasks with one position and one creation time keeps the id order", async () => { + const orgId = newOrg("ties"); + const at = new Date(Date.now() - 60_000); + // Twelve tasks share position 1 and the exact creation instant, so only the + // id orders them; three more one microsecond apart share position 2. + await db.insert(tasks).values( + Array.from({ length: 12 }, (_, index) => ({ + orgId, + title: `tie ${index}`, + orderKey: 1, + createdAt: at, + updatedAt: at, + })), + ); + await db.insert(tasks).values( + [0, 1, 2].map((index) => ({ + orgId, + title: `micro ${index}`, + orderKey: 2, + createdAt: sql`${at.toISOString()}::timestamptz + ${index}::int * interval '1 microsecond'`, + updatedAt: at, + })), + ); + // A fractional position from a drag between two cards. + await db.insert(tasks).values({ orgId, title: "between", orderKey: 1.5 }); + + const oneShot = (await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 500 })).tasks.map( + (task) => task.title, + ); + expect(oneShot).toHaveLength(16); + expect(oneShot.slice(12)).toEqual(["between", "micro 2", "micro 1", "micro 0"]); + for (const limit of [1, 5, 7]) { + const { titles } = await readAll(orgId, { limit }); + expect(titles).toEqual(oneShot); + } + }); + + test("archived tasks are left out of the pages when asked", async () => { + const orgId = newOrg("archived"); + for (let index = 0; index < 120; index += 1) { + await createTask({ + orgId, + title: `task ${index}`, + status: index < 110 ? "archived" : "todo", + }); + } + + const board = await listTaskPageForOrg(orgId, { scope: "all" }, { limit: 100, excludeArchived: true }); + expect(board.tasks.map((task) => task.title)).toEqual( + Array.from({ length: 10 }, (_, index) => `task ${110 + index}`), + ); + expect(board.nextCursor).toBeNull(); + + const everything = await readAll(orgId, { limit: 100 }); + expect(everything.titles).toHaveLength(120); + expect(everything.pages).toBe(2); + }); + + test("a page never reaches another workspace's tasks", async () => { + const mine = newOrg("mine"); + const theirs = newOrg("theirs"); + await createTask({ orgId: mine, title: "mine" }); + await createTask({ orgId: theirs, title: "theirs" }); + const page = await listTaskPageForOrg(mine, { scope: "all" }, { limit: 100 }); + expect(page.tasks.map((task) => task.title)).toEqual(["mine"]); + }); +}); diff --git a/backend/src/tasks/repo.ts b/backend/src/tasks/repo.ts index a9e1b595a..1d5f22536 100644 --- a/backend/src/tasks/repo.ts +++ b/backend/src/tasks/repo.ts @@ -1,11 +1,11 @@ -import { and, asc, desc, eq, sql } from "drizzle-orm"; +import { and, asc, desc, eq, ne, sql } from "drizzle-orm"; import { db } from "../db/client"; import { tasks, type TaskStatus } from "../db/schema"; import { ensureProject, getProjectForOrg } from "../projects/repo"; // --------------------------------------------------------------------------- // Tasks data access. Every function is ORG-SCOPED and fail-closed: a cross-org -// (or missing) id resolves to null. The board reads through `listTasksForOrg` +// (or missing) id resolves to null. The board pages through `listTaskPageForOrg` // (optionally filtered to one project); the gateway tools and REST routes share // this one module so there is a single place tenancy is enforced. // --------------------------------------------------------------------------- @@ -96,7 +96,38 @@ export async function listTasksForOrg( selection: TaskListScope = { projectKey: null }, requestedLimit = 100, ): Promise { - const limit = Math.min(Math.max(requestedLimit, 1), 500); + return (await listTaskPageForOrg(orgId, selection, { limit: requestedLimit })).tasks; +} + +/** Where a page of the task list stopped: the last row's full sort key. The + * creation time is whole microseconds since the epoch (a decimal string), the + * precision Postgres stores, so tasks created in the same millisecond are + * neither repeated nor skipped. */ +export interface TaskPageCursor { + readonly orderKey: number; + readonly createdAtMicros: string; + readonly id: string; +} + +export interface TaskPage { + readonly tasks: TaskRecord[]; + /** Pass back as `cursor` for the next page; null on the last page. */ + readonly nextCursor: TaskPageCursor | null; +} + +/** One page of org-scoped tasks in board order (column position, then newest + * first), after `cursor` when given. `excludeArchived` leaves archived tasks + * out, so they never take a place on a page of the board. */ +export async function listTaskPageForOrg( + orgId: string, + selection: TaskListScope = { projectKey: null }, + options: { + limit?: number; + cursor?: TaskPageCursor | null; + excludeArchived?: boolean; + } = {}, +): Promise { + const limit = Math.min(Math.max(options.limit ?? 100, 1), 500); const projectScope = "scope" in selection ? undefined @@ -105,15 +136,41 @@ export async function listTasksForOrg( : selection.projectKey === null || selection.projectKey === "" ? sql`${tasks.projectId} is null` : eq(tasks.projectKey, selection.projectKey); - const scope = projectScope - ? and(eq(tasks.orgId, orgId), projectScope) - : eq(tasks.orgId, orgId); - return db - .select() + const cursor = options.cursor ?? null; + // order_key sorts up and the rest down, so "after the cursor" is a later + // position, or the same position and an older (created_at, id). + const afterCursor = cursor + ? sql`(${tasks.orderKey} > ${cursor.orderKey}::double precision + or (${tasks.orderKey} = ${cursor.orderKey}::double precision + and (${tasks.createdAt}, ${tasks.id}) + < ('epoch'::timestamptz + ${cursor.createdAtMicros}::bigint * interval '1 microsecond', + ${cursor.id}::uuid)))` + : undefined; + const rows = await db + .select({ + task: tasks, + createdAtMicros: sql`((extract(epoch from ${tasks.createdAt}) * 1000000)::bigint)::text`, + }) .from(tasks) - .where(scope) + .where( + and( + eq(tasks.orgId, orgId), + projectScope, + options.excludeArchived ? ne(tasks.status, "archived") : undefined, + afterCursor, + ), + ) .orderBy(asc(tasks.orderKey), desc(tasks.createdAt), desc(tasks.id)) - .limit(limit); + .limit(limit + 1); + const page = rows.slice(0, limit); + const last = page.at(-1); + return { + tasks: page.map((row) => row.task), + nextCursor: + rows.length > limit && last + ? { orderKey: last.task.orderKey, createdAtMicros: last.createdAtMicros, id: last.task.id } + : null, + }; } /** Org-scoped fetch - a cross-org (or missing) id resolves to null. */ diff --git a/backend/src/tasks/routes.ts b/backend/src/tasks/routes.ts index 5c9e50b21..928ef0445 100644 --- a/backend/src/tasks/routes.ts +++ b/backend/src/tasks/routes.ts @@ -5,10 +5,11 @@ import { orgScope } from "../middleware/org"; import { createTask, deleteTask, - listTasksForOrg, + listTaskPageForOrg, updateTask, type TaskRecord, } from "./repo"; +import { encodeTaskPageCursor, parseTaskPageCursor } from "./page-cursor"; export const tasksRoutes = new Hono(); @@ -38,22 +39,35 @@ function isTaskStatus(v: unknown): v is TaskStatus { return typeof v === "string" && (TASK_STATUSES as readonly string[]).includes(v); } -// List tasks for the active org. `?project=` or `?project_id=` scopes -// to one project; the default is unfiled, and `?scope=all` is the explicit -// bounded cross-project read. +// List tasks for the active org in board order. `?project=` or +// `?project_id=` scopes to one project; the default is unfiled, and +// `?scope=all` is the explicit cross-project read. Pages: pass `next_cursor` +// back as `?cursor=` with the same filters and limit for the next page. +// `?exclude_archived=1` leaves archived tasks out (the board shows none). tasksRoutes.get("/", async (c) => { const project = c.req.query("project"); const projectId = c.req.query("project_id"); const rawLimit = Number(c.req.query("limit") ?? 100); const limit = Number.isFinite(rawLimit) ? Math.trunc(rawLimit) : 100; + const rawCursor = c.req.query("cursor"); + const cursor = rawCursor === undefined ? null : parseTaskPageCursor(rawCursor); + if (rawCursor !== undefined && !cursor) return c.json({ error: "cursor is invalid" }, 400); const selection = c.req.query("scope") === "all" ? ({ scope: "all" } as const) : projectId ? ({ projectId } as const) : ({ projectKey: project ?? null } as const); - const rows = await listTasksForOrg(c.get("orgId"), selection, limit); - return c.json({ tasks: rows.map(toTask) }); + const page = await listTaskPageForOrg(c.get("orgId"), selection, { + limit, + cursor, + excludeArchived: c.req.query("exclude_archived") === "1", + }); + return c.json({ + tasks: page.tasks.map(toTask), + has_more: page.nextCursor !== null, + next_cursor: page.nextCursor ? encodeTaskPageCursor(page.nextCursor) : null, + }); }); // Create a task (org-scoped). `title` is required; `status` defaults to "todo". diff --git a/backend/test/tasks.test.ts b/backend/test/tasks.test.ts index c3799f5b7..430c28b6b 100644 --- a/backend/test/tasks.test.ts +++ b/backend/test/tasks.test.ts @@ -120,4 +120,53 @@ describe("tasks CRUD (org-scoped) + project filter", () => { const del = await json(`/api/tasks/${missing}`, { method: "DELETE" }); expect(del.status).toBe(404); }); + + test("pages past 100 tasks with next_cursor, and leaves archived tasks out on request", async () => { + const session = await createOrgSession("tasks-pages"); + const created: string[] = []; + for (let index = 0; index < 103; index += 1) { + const task = await json("/api/tasks", { + method: "POST", + cookies: session.cookies, + body: { title: `Task ${index}`, status: index < 2 ? "archived" : "todo" }, + }); + expect(task.status).toBe(201); + created.push(task.body.id); + } + const newest = created.at(-1); + + const first = await json("/api/tasks?scope=all", { cookies: session.cookies }); + expect(first.body.tasks).toHaveLength(100); + expect(first.body.tasks.map((task: any) => task.id)).not.toContain(newest); + expect(first.body.has_more).toBe(true); + expect(typeof first.body.next_cursor).toBe("string"); + const second = await json( + `/api/tasks?scope=all&cursor=${encodeURIComponent(first.body.next_cursor)}`, + { cookies: session.cookies }, + ); + expect(second.body.tasks.map((task: any) => task.title)).toEqual(["Task 100", "Task 101", "Task 102"]); + expect(second.body).toMatchObject({ has_more: false, next_cursor: null }); + + // Without the two archived tasks, the board's 101 open tasks still need two pages. + const board = await json("/api/tasks?scope=all&exclude_archived=1", { cookies: session.cookies }); + expect(board.body.tasks[0].title).toBe("Task 2"); + expect(board.body.tasks.every((task: any) => task.status !== "archived")).toBe(true); + const boardRest = await json( + `/api/tasks?scope=all&exclude_archived=1&cursor=${encodeURIComponent(board.body.next_cursor)}`, + { cookies: session.cookies }, + ); + expect(boardRest.body.tasks.map((task: any) => task.id)).toEqual([newest]); + expect(boardRest.body.has_more).toBe(false); + }); + + test("an invalid cursor is a 400", async () => { + const session = await createOrgSession("tasks-cursor"); + for (const cursor of ["", "nope!", Buffer.from("[1]").toString("base64url")]) { + const response = await json(`/api/tasks?scope=all&cursor=${encodeURIComponent(cursor)}`, { + cookies: session.cookies, + }); + expect(response.status).toBe(400); + expect(response.body.error).toBe("cursor is invalid"); + } + }); }); diff --git a/docs-site/docs/api/skills.mdx b/docs-site/docs/api/skills.mdx index 1af23d04b..5c6dd3564 100644 --- a/docs-site/docs/api/skills.mdx +++ b/docs-site/docs/api/skills.mdx @@ -55,7 +55,7 @@ composer](/product/task-composer). | Method | Path | Description | Notes | | --- | --- | --- | --- | -| GET | `/api/tasks` | List org tasks, scoped by project or all. | Query `project` (key), `project_id` (uuid), `scope=all` (cross-project), `limit` (default 100). Returns `{tasks}`. | +| GET | `/api/tasks` | List org tasks in board order (column position, then newest first), scoped by project or all. | Query `project` (key), `project_id` (uuid), `scope=all` (cross-project), `limit` (1-500, default 100), `exclude_archived=1`, `cursor`. Returns `{tasks, has_more, next_cursor}`: send `next_cursor` back as `cursor`, with the same other query, for the next page; it is `null` on the last page. `400 cursor is invalid`. | | POST | `/api/tasks` | Create a task. | Body: `title` (required), `status` (default `todo`), `project_id`, `project_key`, `body`, `priority`. `201`. `404 project not found`. | | PATCH | `/api/tasks/:id` | Partial update. | Body (any subset): `title`, `body`, `status`, `priority`, `order`. `404 task not found`. | | DELETE | `/api/tasks/:id` | Delete a task. | `{deleted: true, id}`. `404 task not found`. | diff --git a/frontend/app/(library)/tasks/tasks-api.test.ts b/frontend/app/(library)/tasks/tasks-api.test.ts new file mode 100644 index 000000000..c05dc041f --- /dev/null +++ b/frontend/app/(library)/tasks/tasks-api.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, test } from "bun:test"; +import { fetchTasks } from "./tasks-api"; +import type { Task } from "./tasks-data"; + +function task(index: number): Task { + return { + id: `task-${index}`, + project_key: null, + title: `Task ${index}`, + body: null, + status: "todo", + priority: 0, + order: index, + created_at: "2026-11-01T10:00:00.000Z", + updated_at: "2026-11-01T10:00:00.000Z", + }; +} + +/** Answers each request with the next of `pages`, recording the paths asked for. */ +function pagedFetcher(pages: ReadonlyArray<{ status?: number; body: unknown }>) { + const paths: string[] = []; + const fetcher = async (path: string) => { + const page = pages[paths.length]; + paths.push(path); + if (!page) throw new Error(`unexpected request ${path}`); + return new Response(JSON.stringify(page.body), { status: page.status ?? 200 }); + }; + return { paths, fetcher: fetcher as never }; +} + +describe("fetchTasks", () => { + test("reads every page, so a task past the first page is on the board", async () => { + const first = Array.from({ length: 500 }, (_, index) => task(index)); + const { paths, fetcher } = pagedFetcher([ + { body: { tasks: first, has_more: true, next_cursor: "c1" } }, + { body: { tasks: [task(500)], has_more: false, next_cursor: null } }, + ]); + const tasks = await fetchTasks(undefined, fetcher); + expect(tasks).toHaveLength(501); + expect(tasks.at(-1)?.id).toBe("task-500"); + expect(paths).toEqual([ + "/api/tasks?scope=all&exclude_archived=1&limit=500", + "/api/tasks?scope=all&exclude_archived=1&limit=500&cursor=c1", + ]); + }); + + test("scopes every page to the chosen project", async () => { + const { paths, fetcher } = pagedFetcher([ + { body: { tasks: [task(1)], has_more: true, next_cursor: "a/b" } }, + { body: { tasks: [task(2)], has_more: false, next_cursor: null } }, + ]); + await fetchTasks("acme/web app", fetcher); + expect(paths).toEqual([ + "/api/tasks?project=acme%2Fweb%20app&exclude_archived=1&limit=500", + "/api/tasks?project=acme%2Fweb%20app&exclude_archived=1&limit=500&cursor=a%2Fb", + ]); + }); + + test("an answer without a cursor is the last page", async () => { + const { paths, fetcher } = pagedFetcher([{ body: { tasks: [task(1)] } }]); + expect(await fetchTasks(undefined, fetcher)).toHaveLength(1); + expect(paths).toHaveLength(1); + }); + + test("a failed page fails the read instead of showing part of the board", async () => { + const { fetcher } = pagedFetcher([ + { body: { tasks: [task(1)], has_more: true, next_cursor: "c1" } }, + { status: 503, body: { error: "unavailable" } }, + ]); + await expect(fetchTasks(undefined, fetcher)).rejects.toThrow("tasks 503"); + }); + + test("shows a task once when a move between pages returns it twice", async () => { + const { fetcher } = pagedFetcher([ + { body: { tasks: [task(1), task(2)], next_cursor: "c1" } }, + { body: { tasks: [task(2), task(3)], next_cursor: null } }, + ]); + const tasks = await fetchTasks(undefined, fetcher); + expect(tasks.map((item) => item.id)).toEqual(["task-1", "task-2", "task-3"]); + }); + + test("stops when the same cursor comes back", async () => { + const { fetcher } = pagedFetcher([ + { body: { tasks: [task(1)], next_cursor: "loop" } }, + { body: { tasks: [task(2)], next_cursor: "loop" } }, + ]); + await expect(fetchTasks(undefined, fetcher)).rejects.toThrow("cursor repeated"); + }); +}); diff --git a/frontend/app/(library)/tasks/tasks-api.ts b/frontend/app/(library)/tasks/tasks-api.ts index ea4005450..a9d1de0b8 100644 --- a/frontend/app/(library)/tasks/tasks-api.ts +++ b/frontend/app/(library)/tasks/tasks-api.ts @@ -10,13 +10,35 @@ import type { Task, TaskStatus } from "./tasks-data"; const jsonHeaders = { "content-type": "application/json" } as const; -/** List org tasks, optionally scoped to one project key. */ -export async function fetchTasks(project?: string): Promise { - const qs = project ? `?project=${encodeURIComponent(project)}` : "?scope=all"; - const res = await backendFetch(`/api/tasks${qs}`, { cache: "no-store" }); - if (!res.ok) throw new Error(`tasks ${res.status}`); - const data = (await res.json()) as { tasks?: Task[] }; - return data.tasks ?? []; +/** The most tasks one request asks for; the backend caps a page at 500. */ +const TASKS_PAGE_LIMIT = 500; + +/** List org tasks, optionally scoped to one project key: every page, so the + * board and its column counts hold every open task. Archived tasks have no + * column and are left out by the backend. */ +export async function fetchTasks( + project?: string, + fetcher: typeof backendFetch = backendFetch, +): Promise { + const scope = project ? `project=${encodeURIComponent(project)}` : "scope=all"; + const base = `/api/tasks?${scope}&exclude_archived=1&limit=${TASKS_PAGE_LIMIT}`; + const tasks = new Map(); + const cursors = new Set(); + let cursor: string | null = null; + do { + const path: string = cursor ? `${base}&cursor=${encodeURIComponent(cursor)}` : base; + const res = await fetcher(path, { cache: "no-store" }); + if (!res.ok) throw new Error(`tasks ${res.status}`); + const data = (await res.json()) as { tasks?: Task[]; next_cursor?: string | null }; + // A card moved while the pages are read can come back on a later page; + // the board shows it once, where it was first read. + for (const task of data.tasks ?? []) if (!tasks.has(task.id)) tasks.set(task.id, task); + cursor = typeof data.next_cursor === "string" ? data.next_cursor : null; + // A cursor answered twice would never end the loop. + if (cursor !== null && cursors.has(cursor)) throw new Error("tasks: cursor repeated"); + if (cursor !== null) cursors.add(cursor); + } while (cursor !== null); + return [...tasks.values()]; } /** The org's durable project identities, used as board filter options. A failed