Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions backend/src/artifacts/repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,21 @@ export async function listArtifactsForOrg(input: {
.orderBy(desc(artifacts.createdAt))
.limit(Math.max(1, Math.min(input.limit ?? 100, 100)));
}

/** 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. */
export async function listRunArtifactFilesForOrg(input: {
readonly orgId: string;
readonly runId: string;
}): Promise<Pick<ArtifactRecord, "name" | "sizeBytes" | "storageKey">[]> {
return db
.select({
name: artifacts.name,
sizeBytes: artifacts.sizeBytes,
storageKey: artifacts.storageKey,
})
.from(artifacts)
.where(and(eq(artifacts.orgId, input.orgId), eq(artifacts.runId, input.runId)))
.orderBy(desc(artifacts.createdAt));
}
14 changes: 7 additions & 7 deletions backend/src/artifacts/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
applyArtifactPdfPageRevision,
getArtifactForOrg,
listArtifactsForOrg,
listRunArtifactFilesForOrg,
seedArtifactWorkpieceStateIfMissing,
toArtifactDescriptor,
updateArtifactWorkpiece,
Expand Down Expand Up @@ -108,10 +109,9 @@ function contentHeaders(
return headers;
}

// A run's artifacts are packaged in-memory before streaming, so both the count
// and the summed byte size are bounded. The count cap matches the artifact list
// page size; a run with more artifacts archives its most recent ones.
const ARCHIVE_MAX_ARTIFACTS = 100;
// A run's artifacts are packaged in-memory before streaming, so their summed
// byte size is bounded. Every artifact of the run goes in, or the request is
// refused: an archive never leaves a file out without saying so.
const ARCHIVE_MAX_TOTAL_BYTES = 100 * 1024 * 1024;

export const artifactRoutes = new Hono<AppEnv>();
Expand All @@ -127,12 +127,12 @@ artifactRoutes.get("/", async (c) => {
});

// Download every published artifact of a run as one ZIP. Org-scoped like every
// other read; bounded in count and total size so the bundle is built safely in
// memory before streaming.
// other read; bounded in total size so the bundle is built safely in memory
// before streaming.
artifactRoutes.get("/runs/:runId/archive", async (c) => {
const orgId = c.get("orgId");
const runId = c.req.param("runId");
const rows = await listArtifactsForOrg({ orgId, runId, limit: ARCHIVE_MAX_ARTIFACTS });
const rows = await listRunArtifactFilesForOrg({ orgId, runId });
if (rows.length === 0) return c.json({ error: "no artifacts to archive" }, 404);

const totalBytes = rows.reduce((sum, row) => sum + row.sizeBytes, 0);
Expand Down
66 changes: 66 additions & 0 deletions backend/test/artifacts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1964,6 +1964,72 @@ describe("durable artifacts", () => {
expect(outside.status).toBe(404);
});

// Stores `count` small text artifacts on a run, `file-0.txt` first.
async function storeTextArtifacts(runId: string, count: number): Promise<void> {
for (let index = 0; index < count; index += 1) {
const bytes = new TextEncoder().encode(`file ${index}`);
const digest = createHash("sha256").update(bytes).digest("hex");
await storage.put(digest, bytes);
await createArtifactRecord({
orgId: owner.orgId,
userId: owner.email,
runId,
threadId: runId,
sourcePath: `/root/work/file-${index}.txt`,
name: `file-${index}.txt`,
contentType: "text/plain",
sizeBytes: bytes.byteLength,
sha256: digest,
storageKey: digest,
});
}
}

test("archives every artifact of a run with more than 100", async () => {
const runId = await createSandboxRun(owner);
await storeTextArtifacts(runId, 101);

const archive = await fetchApi(`/api/artifacts/runs/${runId}/archive`, {
cookies: owner.cookies,
});
expect(archive.status).toBe(200);
const zip = await JSZip.loadAsync(new Uint8Array(await archive.arrayBuffer()));
expect(Object.keys(zip.files)).toHaveLength(101);
// The oldest file is the one a newest-100 cap would have left out.
expect(await zip.file("file-0.txt")?.async("string")).toBe("file 0");
expect(await zip.file("file-100.txt")?.async("string")).toBe("file 100");
});

test("refuses the archive when an older artifact puts the run over the size limit", async () => {
const runId = await createSandboxRun(owner);
const bytes = new TextEncoder().encode("large");
const digest = createHash("sha256").update(bytes).digest("hex");
await storage.put(digest, bytes);
// Only the recorded size counts toward the limit, so the stored bytes stay small.
const large = await createArtifactRecord({
orgId: owner.orgId,
userId: owner.email,
runId,
threadId: runId,
sourcePath: "/root/work/large.bin",
name: "large.bin",
contentType: "application/octet-stream",
sizeBytes: 100 * 1024 * 1024,
sha256: digest,
storageKey: digest,
});
await db.update(artifacts).set({ createdAt: new Date(0) })
.where(eq(artifacts.id, large.row.id));
await storeTextArtifacts(runId, 100);

const archive = await fetchApi(`/api/artifacts/runs/${runId}/archive`, {
cookies: owner.cookies,
});
expect(archive.status).toBe(413);
expect(archive.headers.get("content-type")).toContain("application/json");
expect(await archive.json()).toEqual({ error: "run artifacts exceed the archive size limit" });
});

test("encodes non-ASCII and reserved filename characters safely", async () => {
const runId = await createSandboxRun(owner);
const published = await publish(owner, runId, "/root/work/report (final)' é.txt");
Expand Down
2 changes: 1 addition & 1 deletion docs-site/docs/api/artifacts.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ immutable bytes and authorization. All routes are org-session scoped. See
| GET | `/api/artifacts/:id/proposals` | List agent-proposed workpiece revisions. | Query `status=all` returns every status; otherwise `pending`. `{proposals}`. |
| POST | `/api/artifacts/:id/proposals/:proposalId/accept` | Fold a pending proposal into mainline as a new revision. | `{workpiece, state, proposal}`. `409 proposal already resolved` / `revision conflict`. |
| 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. | Capped at 100 artifacts / 100 MiB. `404 no artifacts to archive`, `413` over the size limit, `410` when bytes are unavailable. |
| 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. |

:::note
Workpiece proposals are agent-authored (written through the gateway) and
Expand Down
Loading