From ac628c2b25a98450c58ae7059cf7774a060b8c35 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Thu, 12 Nov 2026 09:42:52 +0000 Subject: [PATCH 1/2] Let the Artifacts page list files past the newest 100 GET /api/artifacts stopped at the newest 100 artifacts with no way to ask for more, and the Artifacts page called it without filters, so a file older than the newest 100 could never be found there. Backend (backend/src/artifacts/): - GET /api/artifacts takes `limit` (1 to 100, default 100, clamped like the runs list) and `cursor`, and answers `has_more` and `next_cursor` beside `artifacts`. Sending `next_cursor` back as `cursor` with the same filters gives the artifacts after the page. Without a cursor the first page is the same newest 100 as before, so current callers and the released web client see no change. - The cursor (list-cursor.ts) is the last artifact's created_at and id. The timestamp is Postgres' own text with microseconds, cast back with ::timestamptz, as the execution graph cursor does, because a JavaScript Date rounds to milliseconds and would repeat or skip files published within one millisecond. "After the cursor" is one row-value comparison over (created_at, id), and the list is now ordered by id after created_at, so a page cut between equal timestamps keeps a stable order. A malformed cursor answers 400 {"error":"cursor is invalid"}; the query stays scoped to the caller's org. Frontend: - The server snapshot (lib/fetch-artifacts.ts) carries the cursor, and the Artifacts page shows "Show older files" under the list while the backend reports more. Each click adds the next page without repeating a file already shown; a second click while a page loads sends nothing. - The newest page stays live as before. Once an older page is loaded, a refresh puts the newest page in front of the loaded files and keeps the rest, since artifacts are only ever added, and the cursor of the next older page is kept. A failed page says "Couldn't load older files." and the button becomes Try again with the same cursor. - With a type filter and more to load, the empty message says there are none "among the loaded files". Docs: the GET /api/artifacts row and a Paging section on the Artifacts API page, and the hub's Show older files on the Artifacts page. Tests: test/artifact-pages.test.ts seeds 150 artifacts where ten share one timestamp exactly and eight sit one microsecond apart, and checks through the real route that the 101st newest is on page two, that pages of 50 and of 7 match Postgres' own order with no gap or repeat, a run filter, a file published mid-paging, the limit bounds, twelve bad cursors, and that a cursor carries nothing across workspaces. With the cursor at millisecond precision three of them fail. The page's interaction test covers appending pages, the duplicate, refresh with and without older pages loaded, a failed page and Try again, and the double click; fetch-artifacts.test.ts covers the helpers. Fixes #210 --- backend/src/artifacts/list-cursor.ts | 63 +++++++ backend/src/artifacts/repo.ts | 44 ++++- backend/src/artifacts/routes.ts | 27 ++- backend/test/artifact-pages.test.ts | 161 ++++++++++++++++++ docs-site/docs/api/artifacts.mdx | 11 +- docs-site/docs/product/artifacts.mdx | 5 + .../live-artifacts.interaction.test.tsx | 140 ++++++++++++++- .../agent/artifacts/live-artifacts.tsx | 82 ++++++++- .../app/(library)/agent/artifacts/page.tsx | 1 + frontend/app/(library)/artifacts/page.tsx | 6 +- frontend/lib/fetch-artifacts.test.ts | 73 ++++++++ frontend/lib/fetch-artifacts.ts | 57 ++++++- 12 files changed, 641 insertions(+), 29 deletions(-) create mode 100644 backend/src/artifacts/list-cursor.ts create mode 100644 backend/test/artifact-pages.test.ts create mode 100644 frontend/lib/fetch-artifacts.test.ts diff --git a/backend/src/artifacts/list-cursor.ts b/backend/src/artifacts/list-cursor.ts new file mode 100644 index 000000000..203bc53b7 --- /dev/null +++ b/backend/src/artifacts/list-cursor.ts @@ -0,0 +1,63 @@ +/** + * The cursor `GET /api/artifacts` hands back as `next_cursor`: the sort key of + * the last artifact on a page (newest first, then id). The timestamp keeps + * Postgres' own text form, microseconds included; a JavaScript Date would + * round it to milliseconds and repeat or skip artifacts published within one + * millisecond of each other. + */ +export interface ArtifactListCursor { + readonly createdAt: string; + readonly id: string; +} + +export class InvalidArtifactCursorError extends Error { + constructor() { + super("cursor is invalid"); + this.name = "InvalidArtifactCursorError"; + } +} + +const MAX_CURSOR_LENGTH = 512; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const POSTGRES_TIMESTAMP = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d{1,6})?[+-]\d{2}(?::?\d{2})?$/; + +/** Postgres rejects a calendar date or clock time that does not exist (and + * `Date.parse` may roll it over), so the parts are checked before the query. */ +function isRealTimestamp(value: string): boolean { + if (!POSTGRES_TIMESTAMP.test(value)) return false; + const [year, month, day, hour, minute, second] = value.split(/[- :.+]/, 6).map(Number) as [number, number, number, number, number, number]; + const date = new Date(Date.UTC(year, month - 1, day)); + return ( + date.getUTCFullYear() === year && + date.getUTCMonth() === month - 1 && + date.getUTCDate() === day && + hour <= 23 && + minute <= 59 && + second <= 59 + ); +} + +export function encodeArtifactCursor(cursor: ArtifactListCursor): string { + return Buffer.from(JSON.stringify({ v: 1, created_at: cursor.createdAt, id: cursor.id }), "utf8").toString("base64url"); +} + +/** Read a cursor from `encodeArtifactCursor`; anything else throws `InvalidArtifactCursorError`. */ +export function parseArtifactCursor(value: string): ArtifactListCursor { + if (!value || value.length > MAX_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) throw new InvalidArtifactCursorError(); + const decoded = Buffer.from(value, "base64url"); + if (decoded.toString("base64url") !== value) throw new InvalidArtifactCursorError(); + let parsed: unknown; + try { + parsed = JSON.parse(decoded.toString("utf8")); + } catch { + throw new InvalidArtifactCursorError(); + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new InvalidArtifactCursorError(); + const wire = parsed as Record; + const keys = Object.keys(wire).sort(); + if (keys.join(",") !== "created_at,id,v" || wire.v !== 1) throw new InvalidArtifactCursorError(); + const { created_at: createdAt, id } = wire; + if (typeof createdAt !== "string" || !isRealTimestamp(createdAt)) throw new InvalidArtifactCursorError(); + if (typeof id !== "string" || !UUID.test(id)) throw new InvalidArtifactCursorError(); + return { createdAt, id: id.toLowerCase() }; +} diff --git a/backend/src/artifacts/repo.ts b/backend/src/artifacts/repo.ts index bdd787b86..2238c4c1b 100644 --- a/backend/src/artifacts/repo.ts +++ b/backend/src/artifacts/repo.ts @@ -1,4 +1,4 @@ -import { and, desc, eq, isNull, sql } from "drizzle-orm"; +import { and, desc, eq, getTableColumns, isNull, sql } from "drizzle-orm"; import { db, type Executor } from "../db/client"; import { ARTIFACT_LEGACY_WORKPIECE_ACTIONS, @@ -10,6 +10,7 @@ import { } from "@useagent/artifact-workspace"; import { artifacts } from "../db/schema"; import { stableJson } from "../github/publication-repo-input"; +import { type ArtifactListCursor, encodeArtifactCursor } from "./list-cursor"; import { inferWorkpieceKind } from "./workpiece"; export type ArtifactRecord = typeof artifacts.$inferSelect; @@ -333,6 +334,47 @@ export async function listArtifactsForOrg(input: { .limit(Math.max(1, Math.min(input.limit ?? 100, 100))); } +export interface ArtifactListPage { + readonly artifacts: ArtifactRecord[]; + /** Pass back as `cursor` for the next page; null on the last page. */ + readonly nextCursor: string | null; +} + +/** + * One page of the org's artifacts (optionally one run's or one thread's), + * newest first with the id breaking ties, starting after `cursor`. A keyset + * page: an artifact published while someone pages lands on the newest page and + * never shifts the later ones. One row past `limit` is read to know whether + * another page follows. + */ +export async function listArtifactPageForOrg(input: { + readonly orgId: string; + readonly runId?: string; + readonly threadId?: string; + readonly limit: number; + readonly cursor: ArtifactListCursor | null; +}): Promise { + const limit = Math.max(1, Math.min(input.limit, 100)); + const filters = [eq(artifacts.orgId, input.orgId)]; + if (input.runId) filters.push(eq(artifacts.runId, input.runId)); + if (input.threadId) filters.push(eq(artifacts.threadId, input.threadId)); + if (input.cursor) { + filters.push(sql`(${artifacts.createdAt}, ${artifacts.id}) < (${input.cursor.createdAt}::timestamptz, ${input.cursor.id}::uuid)`); + } + const rows = await db + .select({ ...getTableColumns(artifacts), cursorCreatedAt: sql`${artifacts.createdAt}::text` }) + .from(artifacts) + .where(and(...filters)) + .orderBy(desc(artifacts.createdAt), desc(artifacts.id)) + .limit(limit + 1); + const page = rows.slice(0, limit); + const last = page.at(-1); + return { + artifacts: page.map(({ cursorCreatedAt: _cursorCreatedAt, ...row }) => row), + nextCursor: rows.length > limit && last ? encodeArtifactCursor({ createdAt: last.cursorCreatedAt, id: last.id }) : null, + }; +} + /** Every artifact of one run, newest first, with only the columns an archive * reads. Not capped: the archive bounds the total bytes it will read, so no * file is left out silently. */ diff --git a/backend/src/artifacts/routes.ts b/backend/src/artifacts/routes.ts index ccd164c8f..a2ac6afc8 100644 --- a/backend/src/artifacts/routes.ts +++ b/backend/src/artifacts/routes.ts @@ -25,11 +25,12 @@ import { exportWorkpieceState, stateFromNativeArtifact, } from "./authoring"; +import { type ArtifactListCursor, InvalidArtifactCursorError, parseArtifactCursor } from "./list-cursor"; import { canPreviewInline } from "./mime"; import { applyArtifactPdfPageRevision, getArtifactForOrg, - listArtifactsForOrg, + listArtifactPageForOrg, listRunArtifactFilesForOrg, seedArtifactWorkpieceStateIfMissing, toArtifactDescriptor, @@ -117,13 +118,33 @@ const ARCHIVE_MAX_TOTAL_BYTES = 100 * 1024 * 1024; export const artifactRoutes = new Hono(); artifactRoutes.use("*", orgScope); +// Newest first, `limit` (1 to 100, default 100) at a time. `next_cursor` goes +// back as `?cursor=`, with the same filters and limit, for the page after it. artifactRoutes.get("/", async (c) => { - const rows = await listArtifactsForOrg({ + const requestedLimit = Number.parseInt(c.req.query("limit") ?? "100", 10); + const limit = Number.isFinite(requestedLimit) ? Math.min(100, Math.max(1, requestedLimit)) : 100; + const rawCursor = c.req.query("cursor"); + let cursor: ArtifactListCursor | null = null; + if (rawCursor !== undefined) { + try { + cursor = parseArtifactCursor(rawCursor); + } catch (error) { + if (error instanceof InvalidArtifactCursorError) return c.json({ error: error.message }, 400); + throw error; + } + } + const page = await listArtifactPageForOrg({ orgId: c.get("orgId"), runId: c.req.query("run_id") || undefined, threadId: c.req.query("thread_id") || undefined, + limit, + cursor, + }); + return c.json({ + artifacts: page.artifacts.map(toArtifactDescriptor), + has_more: page.nextCursor !== null, + next_cursor: page.nextCursor, }); - return c.json({ artifacts: rows.map(toArtifactDescriptor) }); }); // Download every published artifact of a run as one ZIP. Org-scoped like every diff --git a/backend/test/artifact-pages.test.ts b/backend/test/artifact-pages.test.ts new file mode 100644 index 000000000..4757739bf --- /dev/null +++ b/backend/test/artifact-pages.test.ts @@ -0,0 +1,161 @@ +import { beforeAll, describe, expect, test } from "bun:test"; +import { sql } from "drizzle-orm"; +import { db } from "../src/db/client"; +import { artifacts } from "../src/db/schema"; +import { createRun } from "../src/runs/repo"; +import { createOrgSession, json, type OrgSession } from "./helpers"; + +// GET /api/artifacts pages through the real route and database. 150 artifacts +// are seeded one second apart, except indices 45 to 54, which share one +// timestamp exactly (only the id orders them), and 98 to 105, which sit one +// microsecond apart, so page cuts land inside both groups. The expected order +// comes from Postgres directly, not from the code under test. + +interface Page { + artifacts: { id: string; run_id: string; name: string }[]; + has_more: boolean; + next_cursor: string | null; +} + +let A: OrgSession; +let B: OrgSession; +let runOne: string; +let runTwo: string; +let newestFirst: string[]; +const BASE = "2026-10-01 12:00:00.000000+00"; + +async function run(orgId: string): Promise { + const id = crypto.randomUUID(); + await createRun({ id, prompt: "publish files", model: "test", engine: "mock", orgId, userId: null, parentRunId: null, threadId: id, repos: [], memoryScope: "org" }); + return id; +} + +function createdAt(index: number) { + if (index >= 45 && index <= 54) return sql`${BASE}::timestamptz - interval '45 seconds'`; + if (index >= 98 && index <= 105) return sql`${BASE}::timestamptz - interval '98 seconds' - ${index - 98}::int * interval '1 microsecond'`; + return sql`${BASE}::timestamptz - ${index}::int * interval '1 second'`; +} + +async function seed(orgId: string, runId: string, index: number, name: string): Promise { + await db.insert(artifacts).values({ + orgId, + runId, + threadId: runId, + sourcePath: `/sandbox/${name}`, + name, + contentType: "text/plain", + sizeBytes: 1, + sha256: "a".repeat(64), + storageKey: `test/${runId}/${name}`, + createdAt: createdAt(index) as unknown as Date, + }); +} + +async function pages(path: string, cookies: string, start: string | null = null): Promise { + const out: Page[] = []; + let cursor: string | null = start; + do { + const separator = path.includes("?") ? "&" : "?"; + const response: { status: number; body: Page } = await json(cursor ? `${path}${separator}cursor=${cursor}` : path, { cookies }); + expect(response.status).toBe(200); + out.push(response.body); + cursor = response.body.next_cursor; + expect(response.body.has_more).toBe(cursor !== null); + } while (cursor && out.length < 100); + return out; +} + +const ids = (list: Page[]) => list.flatMap((page) => page.artifacts.map((artifact) => artifact.id)); + +beforeAll(async () => { + A = await createOrgSession("artifact-pages"); + B = await createOrgSession("artifact-pages-other"); + runOne = await run(A.orgId); + runTwo = await run(A.orgId); + for (let index = 0; index < 150; index += 1) await seed(A.orgId, index % 3 === 0 ? runTwo : runOne, index, `file-${index}.txt`); + // Older than A's newest artifact, so A's first cursor would reach it if it leaked. + await seed(B.orgId, await run(B.orgId), 5, "other.txt"); + const rows = await db.execute<{ id: string }>(sql`select id from artifacts where org_id = ${A.orgId} order by created_at desc, id desc`); + newestFirst = [...rows].map((row) => row.id); +}); + +describe("GET /api/artifacts pages", () => { + test("the first page is the newest 100, and the 101st newest is on the next one", async () => { + const first = await json("/api/artifacts", { cookies: A.cookies }); + expect(first.status).toBe(200); + expect(first.body.artifacts.map((artifact) => artifact.id)).toEqual(newestFirst.slice(0, 100)); + expect(first.body.has_more).toBe(true); + expect(first.body.next_cursor).toBeString(); + + const second = await json(`/api/artifacts?cursor=${first.body.next_cursor}`, { cookies: A.cookies }); + expect(second.body.artifacts.map((artifact) => artifact.id)).toEqual(newestFirst.slice(100)); + expect(second.body).toMatchObject({ has_more: false, next_cursor: null }); + }); + + test("pages of 50 and of 7 cut inside equal and microsecond-apart timestamps without a gap or a repeat", async () => { + const fifty = await pages("/api/artifacts?limit=50", A.cookies); + expect(fifty.map((page) => page.artifacts.length)).toEqual([50, 50, 50]); + expect(ids(fifty)).toEqual(newestFirst); + + const seven = await pages("/api/artifacts?limit=7", A.cookies); + expect(seven).toHaveLength(22); + expect(ids(seven)).toEqual(newestFirst); + }); + + test("a run's artifacts page with the same filter", async () => { + const expected = ( + await db.execute<{ id: string }>(sql`select id from artifacts where org_id = ${A.orgId} and run_id = ${runTwo} order by created_at desc, id desc`) + ).map((row) => row.id); + expect(expected).toHaveLength(50); + const byRun = await pages(`/api/artifacts?run_id=${runTwo}&limit=20`, A.cookies); + expect(byRun.map((page) => page.artifacts.length)).toEqual([20, 20, 10]); + expect(ids(byRun)).toEqual(expected); + expect(byRun.flatMap((page) => page.artifacts.map((artifact) => artifact.run_id))).toEqual(Array(50).fill(runTwo)); + }); + + test("an artifact published after the first page is on the newest page, not a later one", async () => { + const first = await json("/api/artifacts?limit=50", { cookies: A.cookies }); + const fresh = await run(A.orgId); + await seed(A.orgId, fresh, -10, "fresh.txt"); + const rest = await pages("/api/artifacts?limit=50", A.cookies, first.body.next_cursor); + expect(ids(rest)).toEqual(newestFirst.slice(50)); + const newest = await json("/api/artifacts?limit=1", { cookies: A.cookies }); + expect(newest.body.artifacts.map((artifact) => artifact.name)).toEqual(["fresh.txt"]); + await db.execute(sql`delete from artifacts where run_id = ${fresh}`); + }); + + test("limit is held between 1 and 100", async () => { + expect((await json("/api/artifacts?limit=0", { cookies: A.cookies })).body.artifacts).toHaveLength(1); + expect((await json("/api/artifacts?limit=500", { cookies: A.cookies })).body.artifacts).toHaveLength(100); + expect((await json("/api/artifacts?limit=many", { cookies: A.cookies })).body.artifacts).toHaveLength(100); + }); + + test("a cursor that is not one answers 400", async () => { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url"); + const id = crypto.randomUUID(); + for (const cursor of [ + "", + "not a cursor", + "%%%", + encode([1]), + encode({ v: 2, created_at: "2026-10-01 12:00:00+00", id }), + encode({ v: 1, created_at: "2026-10-01 12:00:00+00" }), + encode({ v: 1, created_at: "2026-10-01 12:00:00+00", id, extra: 1 }), + encode({ v: 1, created_at: "2026-10-01 12:00:00+00", id: "abc" }), + encode({ v: 1, created_at: "yesterday", id }), + encode({ v: 1, created_at: "2026-02-30 12:00:00+00", id }), + encode({ v: 1, created_at: "2026-10-01 25:00:00+00", id }), + `${encode({ v: 1, created_at: "2026-10-01 12:00:00+00", id })}=`, + ]) { + const refused = await json<{ error: string }>(`/api/artifacts?cursor=${encodeURIComponent(cursor)}`, { cookies: A.cookies }); + expect([cursor, refused.status, refused.body]).toEqual([cursor, 400, { error: "cursor is invalid" }]); + } + }); + + test("a cursor carries nothing across workspaces", async () => { + const first = await json("/api/artifacts?limit=1", { cookies: A.cookies }); + const other = await json(`/api/artifacts?cursor=${first.body.next_cursor}`, { cookies: B.cookies }); + expect(other.status).toBe(200); + expect(other.body.artifacts.map((artifact) => artifact.name)).toEqual(["other.txt"]); + }); +}); diff --git a/docs-site/docs/api/artifacts.mdx b/docs-site/docs/api/artifacts.mdx index acbb049de..75e4afdc3 100644 --- a/docs-site/docs/api/artifacts.mdx +++ b/docs-site/docs/api/artifacts.mdx @@ -14,7 +14,7 @@ immutable bytes and authorization. All routes are org-session scoped. See | Method | Path | Description | Notes | | --- | --- | --- | --- | -| GET | `/api/artifacts` | List artifacts for the org, optionally filtered. | Query `run_id`, `thread_id`. Returns `{artifacts}`. | +| GET | `/api/artifacts` | List artifacts for the org, newest first, optionally filtered. | Query `run_id`, `thread_id`, `limit` (1 to 100, default 100), `cursor`. Returns `{artifacts, has_more, next_cursor}`; see [Paging](#paging). `400 cursor is invalid` for a cursor this route did not hand out. | | POST | `/api/artifacts` | Create an authored artifact. | Body: `run_id` (required), `thread_id`, `kind` (`document`/`spreadsheet`/`presentation`/`pdf`), `name`, `upload_id`, `state`. `201` created or `200` existing; `409` on upload-claim conflict. | | GET | `/api/artifacts/:id` | Fetch an artifact descriptor. | `{artifact}`. `404 not found`. | | GET | `/api/artifacts/:id/content` | Stream artifact bytes (range-capable). | Query `download=1` forces attachment. Honors `Range`; `200` or `206`, `416` on a bad range, `410` when bytes are unavailable. `HEAD` is also served (headers only). | @@ -29,6 +29,15 @@ immutable bytes and authorization. All routes are org-session scoped. See | POST | `/api/artifacts/:id/proposals/:proposalId/dismiss` | Drop a pending proposal, recording the dismissal. | `{proposal}`. `409 proposal already resolved`. | | GET | `/api/artifacts/runs/:runId/archive` | Download every published artifact of a run as one ZIP. | Includes every artifact of the run, up to 100 MiB in total. `404 no artifacts to archive`, `413` over the size limit (no partial ZIP), `410` when bytes are unavailable. | +### Paging + +`GET /api/artifacts` answers one page at a time. When `has_more` is true, send +`next_cursor` back as `cursor`, with the same `run_id`, `thread_id` and `limit`, +to get the artifacts that come after the page; on the last page `next_cursor` +is `null`. The cursor holds the last artifact's creation time and id, so an +artifact published while you page shows up on the newest page and never shifts +the later ones. Treat it as opaque. + :::note Workpiece proposals are agent-authored (written through the gateway) and human-reviewed through the accept/dismiss routes above; they are still ordinary diff --git a/docs-site/docs/product/artifacts.mdx b/docs-site/docs/product/artifacts.mdx index 3a778a233..68b755ed0 100644 --- a/docs-site/docs/product/artifacts.mdx +++ b/docs-site/docs/product/artifacts.mdx @@ -15,6 +15,11 @@ also stream into the [session view](/product/session-view). streams them live filtered to a run. Opening one at `/agent/artifacts/:id` shows its detail and, for a workpiece, an inline editor. +The hub shows the newest 100 files first. **Show older files** under the list +loads the next 100, as many times as there are more. Older files stay listed +while new ones arrive at the top, and the type filter applies to every file +loaded so far. + | Operation | Endpoint | | --- | --- | | List, create | `GET`, `POST /api/artifacts` | diff --git a/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx b/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx index 31bc12c37..a97563572 100644 --- a/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx +++ b/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx @@ -2,7 +2,9 @@ // under happy-dom with a held fetch and a stand-in org change stream: it sets // no timer, reads once each time the stream opens, on an artifact change and // when the tab comes back, folds a burst of changes into one follow-up read, -// and spins the refresh icon only for a click. +// and spins the refresh icon only for a click. Past the newest page, Show +// older files reads the page after the backend's cursor and keeps it loaded +// while the newest page refreshes. import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import type { ArtifactDescriptor } from "@/components/artifacts/model"; @@ -51,7 +53,10 @@ function artifact(id: string, name: string): ArtifactDescriptor { const originalFetch = globalThis.fetch; const originalSetInterval = globalThis.setInterval; -let reads: Array<(artifacts: ArtifactDescriptor[]) => void> = []; +let reads: Array<(artifacts: ArtifactDescriptor[], nextCursor?: string | null) => void> = []; +/** Older pages by cursor; a missing cursor answers 503. */ +let olderPages: Record = {}; +let requested: string[] = []; let intervals: number[] = []; let root: ReturnType | null = null; let container: HTMLElement | null = null; @@ -59,12 +64,22 @@ let container: HTMLElement | null = null; beforeEach(() => { reads = []; intervals = []; + olderPages = {}; + requested = []; globalThis.fetch = ((input: RequestInfo | URL) => { - if (String(input) !== "/api/artifacts") { + const path = String(input); + requested.push(path); + if (path.startsWith("/api/artifacts?cursor=")) { + const page = olderPages[decodeURIComponent(path.slice("/api/artifacts?cursor=".length))]; + return Promise.resolve(page ? Response.json(page) : Response.json({ error: "unavailable" }, { status: 503 })); + } + if (path !== "/api/artifacts") { return Promise.resolve(new Response("{}", { status: 404 })); } return new Promise((resolve) => { - reads.push((artifacts) => resolve(Response.json({ artifacts }))); + reads.push((artifacts, nextCursor = null) => + resolve(Response.json({ artifacts, has_more: nextCursor !== null, next_cursor: nextCursor })), + ); }); }) as typeof fetch; globalThis.setInterval = ((handler: TimerHandler, timeout?: number, ...args: unknown[]) => { @@ -86,13 +101,20 @@ afterAll(() => { (globalThis as { EventSource?: unknown }).EventSource = originalEventSource; }); -async function mount() { +async function mount( + initialArtifacts = [artifact("a1", "first.txt")], + initialNextCursor: string | null = null, +) { container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); await act(async () => { root?.render( - , + , ); }); } @@ -114,9 +136,9 @@ function artifactChange(artifactId: string) { return emit("change", { type: "artifact", action: "created", artifactId, runId: "r1", threadId: "t1" }); } -async function answer(artifacts: ArtifactDescriptor[]) { +async function answer(artifacts: ArtifactDescriptor[], nextCursor: string | null = null) { await act(async () => { - reads.shift()?.(artifacts); + reads.shift()?.(artifacts, nextCursor); await new Promise((resolve) => setTimeout(resolve, 0)); }); } @@ -215,3 +237,105 @@ describe("LiveArtifacts reads", () => { expect(button.disabled).toBe(false); }); }); + +function button(label: string): HTMLButtonElement | null { + return ( + [...(container?.querySelectorAll("button") ?? [])].find( + (candidate) => candidate.textContent?.trim() === label, + ) ?? null + ); +} + +async function click(label: string) { + const target = button(label); + if (!target) throw new Error(`no ${label} button`); + await act(async () => { + target.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); +} + +function names(): string[] { + return [...(container?.querySelectorAll("li") ?? [])].map( + (row) => row.textContent?.match(/[a-z-]+\.txt/)?.[0] ?? "", + ); +} + +describe("LiveArtifacts older pages", () => { + test("Show older files appends the next pages until the backend has no more", async () => { + olderPages.c1 = { artifacts: [artifact("a2", "second.txt"), artifact("a3", "third.txt")], next_cursor: "c2" }; + olderPages.c2 = { artifacts: [artifact("a3", "third.txt"), artifact("a4", "fourth.txt")], next_cursor: null }; + await mount([artifact("a1", "first.txt")], "c1"); + expect(names()).toEqual(["first.txt"]); + + await click("Show older files"); + expect(requested).toEqual(["/api/artifacts?cursor=c1"]); + expect(names()).toEqual(["first.txt", "second.txt", "third.txt"]); + + await click("Show older files"); + expect(requested).toEqual(["/api/artifacts?cursor=c1", "/api/artifacts?cursor=c2"]); + // third.txt came on both pages and is listed once. + expect(names()).toEqual(["first.txt", "second.txt", "third.txt", "fourth.txt"]); + expect(button("Show older files")).toBeNull(); + }); + + test("a second click while a page loads sends no second request", async () => { + olderPages.c1 = { artifacts: [artifact("a2", "second.txt")], next_cursor: "c2" }; + await mount([artifact("a1", "first.txt")], "c1"); + const target = button("Show older files"); + await act(async () => { + target?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); + target?.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(requested).toEqual(["/api/artifacts?cursor=c1"]); + expect(names()).toEqual(["first.txt", "second.txt"]); + }); + + test("no button when the newest page is the only one", async () => { + await mount([artifact("a1", "first.txt")], null); + expect(button("Show older files")).toBeNull(); + }); + + test("a refresh of the newest page keeps the older pages and their cursor", async () => { + olderPages.c1 = { artifacts: [artifact("a2", "second.txt")], next_cursor: "c2" }; + olderPages.c2 = { artifacts: [artifact("a3", "third.txt")], next_cursor: null }; + await mount([artifact("a1", "first.txt")], "c1"); + await click("Show older files"); + + // A new file arrives; the newest page now leads with it and still holds first.txt. + await artifactChange("a0"); + await answer([artifact("a0", "zero.txt"), artifact("a1", "first.txt")], "fresh-cursor"); + expect(names()).toEqual(["zero.txt", "first.txt", "second.txt"]); + + // The next older page is still the one after second.txt, not the newest page's cursor. + await click("Show older files"); + expect(requested.at(-1)).toBe("/api/artifacts?cursor=c2"); + expect(names()).toEqual(["zero.txt", "first.txt", "second.txt", "third.txt"]); + }); + + test("a refresh before any older page is loaded takes the newest page's cursor", async () => { + olderPages.c9 = { artifacts: [artifact("a2", "second.txt")], next_cursor: null }; + await mount([artifact("a1", "first.txt")], "c1"); + await artifactChange("a0"); + await answer([artifact("a0", "zero.txt")], "c9"); + expect(names()).toEqual(["zero.txt"]); + + await click("Show older files"); + expect(requested.at(-1)).toBe("/api/artifacts?cursor=c9"); + expect(names()).toEqual(["zero.txt", "second.txt"]); + }); + + test("a failed page says so and Try again sends the same cursor", async () => { + await mount([artifact("a1", "first.txt")], "c1"); + await click("Show older files"); + expect(container?.querySelector('[role="alert"]')?.textContent).toBe("Couldn't load older files."); + expect(names()).toEqual(["first.txt"]); + + olderPages.c1 = { artifacts: [artifact("a2", "second.txt")], next_cursor: null }; + await click("Try again"); + expect(requested).toEqual(["/api/artifacts?cursor=c1", "/api/artifacts?cursor=c1"]); + expect(container?.querySelector('[role="alert"]')).toBeNull(); + expect(names()).toEqual(["first.txt", "second.txt"]); + }); +}); diff --git a/frontend/app/(library)/agent/artifacts/live-artifacts.tsx b/frontend/app/(library)/agent/artifacts/live-artifacts.tsx index ded780ad8..7f2e617fb 100644 --- a/frontend/app/(library)/agent/artifacts/live-artifacts.tsx +++ b/frontend/app/(library)/agent/artifacts/live-artifacts.tsx @@ -16,7 +16,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { artifactViewFor, extractArtifactResult, - extractArtifacts, type ArtifactCategory, type ArtifactDescriptor, } from "@/components/artifacts/model"; @@ -32,6 +31,12 @@ import { import { Select, SelectItem } from "@/components/base/select/select"; import { useOrgChanges } from "@/hooks/use-org-changes"; import { backendFetch } from "@/lib/backend-fetch"; +import { + appendOlderPage, + artifactPagePath, + mergeNewestPage, + readArtifactPage, +} from "@/lib/fetch-artifacts"; import { ArtifactCard, ArtifactRow } from "./artifact-card"; type Filter = "all" | ArtifactCategory; @@ -243,17 +248,30 @@ function UnavailableState({ onRetry }: { onRetry: () => void }) { * The list re-reads on artifact changes from the org stream, never on a timer. * Changes missed while the stream was down are covered by a read each time it * opens (which also covers the gap after the server-rendered snapshot), and - * changes made in another tab by a read when this one comes back to view. */ + * changes made in another tab by a read when this one comes back to view. + * + * Files past the newest page load on request, a page at a time. Those older + * pages stay loaded while the newest page refreshes, which then never moves + * the cursor of the next older page. */ export function LiveArtifacts({ initialArtifacts, + initialNextCursor = null, initialAvailable, initialRunId, }: { initialArtifacts: ArtifactDescriptor[]; + initialNextCursor?: string | null; initialAvailable: boolean; initialRunId?: string; }) { const [artifacts, setArtifacts] = useState(initialArtifacts); + const [nextCursor, setNextCursor] = useState(initialNextCursor); + const [loadingOlder, setLoadingOlder] = useState(false); + const [olderFailed, setOlderFailed] = useState(false); + // Set once an older page is loaded: a refresh then keeps it and its cursor. + const pagedOlder = useRef(false); + // One older page at a time, even for a second click before the button disables. + const loadingOlderRef = useRef(false); const [available, setAvailable] = useState(initialAvailable); const [filter, setFilter] = useState("all"); const [refreshing, setRefreshing] = useState(false); @@ -261,14 +279,19 @@ export function LiveArtifacts({ const fetchSnapshot = useCallback(async (signal?: AbortSignal) => { try { - const response = await backendFetch("/api/artifacts", { signal, cache: "no-store" }); + const response = await backendFetch(artifactPagePath(), { signal, cache: "no-store" }); if (!response.ok) { setAvailable(false); return; } - const parsed = extractArtifacts(await response.json()); - if (parsed) { - setArtifacts(parsed); + const page = readArtifactPage(await response.json()); + if (page) { + if (pagedOlder.current) { + setArtifacts((current) => mergeNewestPage(page.artifacts, current)); + } else { + setArtifacts(page.artifacts); + setNextCursor(page.nextCursor); + } setAvailable(true); } else { setAvailable(false); @@ -309,6 +332,32 @@ export function LiveArtifacts({ [fetchSnapshot], ); + const loadOlder = async () => { + if (!nextCursor || loadingOlderRef.current) return; + loadingOlderRef.current = true; + setLoadingOlder(true); + setOlderFailed(false); + try { + const response = await backendFetch(artifactPagePath(nextCursor), { + signal: lifetime.current?.signal, + cache: "no-store", + }); + const page = response.ok ? readArtifactPage(await response.json()) : null; + if (!page) { + setOlderFailed(true); + return; + } + pagedOlder.current = true; + setArtifacts((current) => appendOlderPage(current, page.artifacts)); + setNextCursor(page.nextCursor); + } catch { + if (!lifetime.current?.signal.aborted) setOlderFailed(true); + } finally { + loadingOlderRef.current = false; + setLoadingOlder(false); + } + }; + useOrgChanges( (change) => { if (change.type === "artifact") void load(); @@ -471,9 +520,28 @@ export function LiveArtifacts({ ) : (

- No {FILTERS.find((item) => item.id === filter)?.label.toLowerCase()} artifacts yet. + No {FILTERS.find((item) => item.id === filter)?.label.toLowerCase()} artifacts{" "} + {nextCursor ? "among the loaded files." : "yet."}

)} + + {artifacts.length > 0 && nextCursor && ( +
+ {olderFailed && ( +

+ Couldn't load older files. +

+ )} + +
+ )} ); } diff --git a/frontend/app/(library)/agent/artifacts/page.tsx b/frontend/app/(library)/agent/artifacts/page.tsx index c4dc997d2..c9e712457 100644 --- a/frontend/app/(library)/agent/artifacts/page.tsx +++ b/frontend/app/(library)/agent/artifacts/page.tsx @@ -20,6 +20,7 @@ export default async function LiveArtifactsPage({ return ( diff --git a/frontend/app/(library)/artifacts/page.tsx b/frontend/app/(library)/artifacts/page.tsx index b69c96178..55b30075e 100644 --- a/frontend/app/(library)/artifacts/page.tsx +++ b/frontend/app/(library)/artifacts/page.tsx @@ -12,6 +12,10 @@ export default async function ArtifactsPage() { const snapshot = await fetchArtifactSnapshot(); return ( - + ); } diff --git a/frontend/lib/fetch-artifacts.test.ts b/frontend/lib/fetch-artifacts.test.ts new file mode 100644 index 000000000..f6a40bf3d --- /dev/null +++ b/frontend/lib/fetch-artifacts.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, test } from "bun:test"; +import type { ArtifactDescriptor } from "@/components/artifacts/model"; +import { + appendOlderPage, + artifactPagePath, + mergeNewestPage, + readArtifactPage, +} from "./fetch-artifacts"; + +function artifact(id: string): ArtifactDescriptor { + return { + id, + run_id: "r1", + thread_id: "t1", + name: `${id}.txt`, + source_path: `/root/work/${id}.txt`, + content_type: "text/plain", + size_bytes: 1, + sha256: "abc", + created_at: "2026-01-01T00:00:00Z", + preview_url: `/api/artifacts/${id}/content`, + download_url: `/api/artifacts/${id}/content?download=1`, + preview_pdf_url: null, + workpiece: null, + }; +} + +const ids = (list: readonly ArtifactDescriptor[]) => list.map((item) => item.id); + +describe("artifact pages", () => { + test("asks for the newest page, or the page after a cursor", () => { + expect(artifactPagePath()).toBe("/api/artifacts"); + expect(artifactPagePath("eyJ2IjoxfQ")).toBe("/api/artifacts?cursor=eyJ2IjoxfQ"); + expect(artifactPagePath("a+b/c=")).toBe("/api/artifacts?cursor=a%2Bb%2Fc%3D"); + }); + + test("reads the cursor, and a missing or malformed one as the last page", () => { + const artifacts = [artifact("a1")]; + expect(readArtifactPage({ artifacts, has_more: true, next_cursor: "c1" })).toEqual({ + artifacts, + nextCursor: "c1", + }); + expect(readArtifactPage({ artifacts })).toEqual({ artifacts, nextCursor: null }); + expect(readArtifactPage({ artifacts, next_cursor: "" })).toEqual({ + artifacts, + nextCursor: null, + }); + expect(readArtifactPage({ artifacts, next_cursor: 7 })).toEqual({ + artifacts, + nextCursor: null, + }); + expect(readArtifactPage({ next_cursor: "c1" })).toBeNull(); + expect(readArtifactPage(null)).toBeNull(); + }); + + test("a refreshed newest page leads, and loaded files it no longer holds follow in order", () => { + const loaded = [artifact("a1"), artifact("a2"), artifact("a3"), artifact("a4")]; + expect(ids(mergeNewestPage([artifact("a0"), artifact("a1"), artifact("a2")], loaded))).toEqual([ + "a0", + "a1", + "a2", + "a3", + "a4", + ]); + expect(ids(mergeNewestPage([], loaded))).toEqual(["a1", "a2", "a3", "a4"]); + }); + + test("an older page is added after what is loaded, without repeats", () => { + expect( + ids(appendOlderPage([artifact("a1"), artifact("a2")], [artifact("a2"), artifact("a3")])), + ).toEqual(["a1", "a2", "a3"]); + }); +}); diff --git a/frontend/lib/fetch-artifacts.ts b/frontend/lib/fetch-artifacts.ts index 256ae2e33..56b464d6e 100644 --- a/frontend/lib/fetch-artifacts.ts +++ b/frontend/lib/fetch-artifacts.ts @@ -1,22 +1,63 @@ import { extractArtifacts, type ArtifactDescriptor } from "@/components/artifacts/model"; import { backendFetch } from "@/lib/backend-fetch"; -export interface ArtifactSnapshot { +export interface ArtifactPage { readonly artifacts: ArtifactDescriptor[]; + /** Cursor for the page after this one; null on the last page, or from a backend that does not page. */ + readonly nextCursor: string | null; +} + +export interface ArtifactSnapshot extends ArtifactPage { readonly available: boolean; } +/** The request for one page of GET /api/artifacts: the newest page, or the one after `cursor`. */ +export function artifactPagePath(cursor: string | null = null): string { + return cursor ? `/api/artifacts?cursor=${encodeURIComponent(cursor)}` : "/api/artifacts"; +} + +/** Read a GET /api/artifacts answer; null when it holds no valid artifact list. */ +export function readArtifactPage(value: unknown): ArtifactPage | null { + const artifacts = extractArtifacts(value); + if (!artifacts) return null; + const cursor = (value as { next_cursor?: unknown }).next_cursor; + return { artifacts, nextCursor: typeof cursor === "string" && cursor.length > 0 ? cursor : null }; +} + +/** + * Put a refreshed newest page in front of what is already loaded. Artifacts + * are only ever added, so one that left the newest page is older than all of + * it: the loaded rows it no longer holds follow in their order, and none drops + * out of view. + */ +export function mergeNewestPage( + newest: readonly ArtifactDescriptor[], + loaded: readonly ArtifactDescriptor[], +): ArtifactDescriptor[] { + const ids = new Set(newest.map((artifact) => artifact.id)); + return [...newest, ...loaded.filter((artifact) => !ids.has(artifact.id))]; +} + +/** Add an older page after what is loaded, without repeating an artifact already shown. */ +export function appendOlderPage( + loaded: readonly ArtifactDescriptor[], + older: readonly ArtifactDescriptor[], +): ArtifactDescriptor[] { + const ids = new Set(loaded.map((artifact) => artifact.id)); + return [...loaded, ...older.filter((artifact) => !ids.has(artifact.id))]; +} + /** Server-side seed for both product shells. Availability is explicit so an * API outage never masquerades as a genuinely empty artifact collection. */ export async function fetchArtifactSnapshot(): Promise { try { - const response = await backendFetch("/api/artifacts", { cache: "no-store" }); - if (!response.ok) return { artifacts: [], available: false }; - const artifacts = extractArtifacts(await response.json()); - return artifacts - ? { artifacts, available: true } - : { artifacts: [], available: false }; + const response = await backendFetch(artifactPagePath(), { cache: "no-store" }); + if (!response.ok) return { artifacts: [], nextCursor: null, available: false }; + const page = readArtifactPage(await response.json()); + return page + ? { ...page, available: true } + : { artifacts: [], nextCursor: null, available: false }; } catch { - return { artifacts: [], available: false }; + return { artifacts: [], nextCursor: null, available: false }; } } From f608e3c0900d8b3b42004db87179522072271ffb Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Thu, 12 Nov 2026 21:34:00 +0530 Subject: [PATCH 2/2] Keep loaded files when a refresh lands during an older page fetch --- .../live-artifacts.interaction.test.tsx | 29 ++++++++++++++++++- .../agent/artifacts/live-artifacts.tsx | 5 ++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx b/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx index a97563572..77a071a4c 100644 --- a/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx +++ b/frontend/app/(library)/agent/artifacts/live-artifacts.interaction.test.tsx @@ -57,6 +57,8 @@ let reads: Array<(artifacts: ArtifactDescriptor[], nextCursor?: string | null) = /** Older pages by cursor; a missing cursor answers 503. */ let olderPages: Record = {}; let requested: string[] = []; +/** When set, older pages wait for it before answering. */ +let olderGate: Promise | null = null; let intervals: number[] = []; let root: ReturnType | null = null; let container: HTMLElement | null = null; @@ -66,12 +68,14 @@ beforeEach(() => { intervals = []; olderPages = {}; requested = []; + olderGate = null; globalThis.fetch = ((input: RequestInfo | URL) => { const path = String(input); requested.push(path); if (path.startsWith("/api/artifacts?cursor=")) { const page = olderPages[decodeURIComponent(path.slice("/api/artifacts?cursor=".length))]; - return Promise.resolve(page ? Response.json(page) : Response.json({ error: "unavailable" }, { status: 503 })); + const response = page ? Response.json(page) : Response.json({ error: "unavailable" }, { status: 503 }); + return olderGate ? olderGate.then(() => response) : Promise.resolve(response); } if (path !== "/api/artifacts") { return Promise.resolve(new Response("{}", { status: 404 })); @@ -314,6 +318,29 @@ describe("LiveArtifacts older pages", () => { expect(names()).toEqual(["zero.txt", "first.txt", "second.txt", "third.txt"]); }); + test("a refresh that lands while an older page loads keeps the files already shown", async () => { + olderPages.c1 = { artifacts: [artifact("a3", "third.txt")], next_cursor: null }; + let release: () => void = () => {}; + olderGate = new Promise((resolve) => { + release = resolve; + }); + await mount([artifact("a1", "first.txt"), artifact("a2", "second.txt")], "c1"); + await click("Show older files"); + + // The newest page moves on and no longer holds second.txt. + await artifactChange("a0"); + await answer([artifact("a0", "zero.txt"), artifact("a1", "first.txt")], "fresh-cursor"); + expect(names()).toEqual(["zero.txt", "first.txt", "second.txt"]); + + await act(async () => { + release(); + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(requested).toEqual(["/api/artifacts?cursor=c1", "/api/artifacts"]); + expect(names()).toEqual(["zero.txt", "first.txt", "second.txt", "third.txt"]); + expect(button("Show older files")).toBeNull(); + }); + test("a refresh before any older page is loaded takes the newest page's cursor", async () => { olderPages.c9 = { artifacts: [artifact("a2", "second.txt")], next_cursor: null }; await mount([artifact("a1", "first.txt")], "c1"); diff --git a/frontend/app/(library)/agent/artifacts/live-artifacts.tsx b/frontend/app/(library)/agent/artifacts/live-artifacts.tsx index 7f2e617fb..78db4ea77 100644 --- a/frontend/app/(library)/agent/artifacts/live-artifacts.tsx +++ b/frontend/app/(library)/agent/artifacts/live-artifacts.tsx @@ -268,7 +268,7 @@ export function LiveArtifacts({ const [nextCursor, setNextCursor] = useState(initialNextCursor); const [loadingOlder, setLoadingOlder] = useState(false); const [olderFailed, setOlderFailed] = useState(false); - // Set once an older page is loaded: a refresh then keeps it and its cursor. + // Set once an older page is requested: a refresh then keeps what is loaded and its cursor. const pagedOlder = useRef(false); // One older page at a time, even for a second click before the button disables. const loadingOlderRef = useRef(false); @@ -335,6 +335,8 @@ export function LiveArtifacts({ const loadOlder = async () => { if (!nextCursor || loadingOlderRef.current) return; loadingOlderRef.current = true; + // Mark it before the fetch: a refresh landing meanwhile must keep the loaded files. + pagedOlder.current = true; setLoadingOlder(true); setOlderFailed(false); try { @@ -347,7 +349,6 @@ export function LiveArtifacts({ setOlderFailed(true); return; } - pagedOlder.current = true; setArtifacts((current) => appendOlderPage(current, page.artifacts)); setNextCursor(page.nextCursor); } catch {