Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions backend/src/artifacts/list-cursor.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
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() };
}
44 changes: 43 additions & 1 deletion backend/src/artifacts/repo.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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<ArtifactListPage> {
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<string>`${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. */
Expand Down
27 changes: 24 additions & 3 deletions backend/src/artifacts/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -117,13 +118,33 @@ const ARCHIVE_MAX_TOTAL_BYTES = 100 * 1024 * 1024;
export const artifactRoutes = new Hono<AppEnv>();
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
Expand Down
161 changes: 161 additions & 0 deletions backend/test/artifact-pages.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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<void> {
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<Page[]> {
const out: Page[] = [];
let cursor: string | null = start;
do {
const separator = path.includes("?") ? "&" : "?";
const response: { status: number; body: Page } = await json<Page>(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<Page>("/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<Page>(`/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<Page>("/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<Page>("/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<Page>("/api/artifacts?limit=0", { cookies: A.cookies })).body.artifacts).toHaveLength(1);
expect((await json<Page>("/api/artifacts?limit=500", { cookies: A.cookies })).body.artifacts).toHaveLength(100);
expect((await json<Page>("/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<Page>("/api/artifacts?limit=1", { cookies: A.cookies });
const other = await json<Page>(`/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"]);
});
});
11 changes: 10 additions & 1 deletion docs-site/docs/api/artifacts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions docs-site/docs/product/artifacts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
Loading
Loading