The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Accounts: download your own runs as a zip
Adarsh87bcdd3d72ea
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 318e969b..5d752c7d 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -118,6 +118,13 @@ An account is signed in, but it sees the owner's studio as a guest does:the sign-up form says so. An account's delete is for good (it has no Trash): a result's ⋯ menu and theLibrary's selection bar say **Delete for good…** and ask first, and its space comesback at once. The live-updates stream isn't sent to accounts: their studios poll instead.+- **It downloads its own runs as one zip.** The Library's **Download**, a result's **Download all** and Shorts'+ **Download parts** go to `GET /api/generations/zip`, which zips the account's own runs only: another account's run or+ the owner's is left out, exactly as one that doesn't exist (none of its own: 404), so the answer never says whether+ it is there. A file held for its check is left out too. One zip takes up to 200 runs and 1 GB (413 past either), and+ an account makes one zip at a time (429 while one is going; a download that stops, or stalls for 2 minutes, frees+ it). The zip is streamed from the files, so it uses no disk or memory. The Library asks first (`?check=1`), so a+ refusal shows as a message. A guest gets the sign-up card.- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, andno other account can open it. See [Uploads](#uploads).- **Results made in the browser are its own runs too.** A motion clip rendered in@@ -331,7 +338,7 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188Its shorts and the presets it makes from its own pictures are its own projects (`src/server/account-projects.ts`):its History, a short's page (`/shorts/<id>`) and its preset list show only its own, and another account's or theowner's read as not found (404). It keeps up to 50 shorts. Deleting a short deletes its runs for good (an account- has no Trash). It downloads the full video and each part; "Download parts" as one zip is the owner's for now.+ has no Trash). It downloads the full video, each part, and "Download parts" as one zip of its own runs.Enhance (`.../enhance`) isn't offered to it yet (403 `own-gpu-tool`). A guest gets the sign-up card.- **Cinema Studio.** An account makes, reopens and runs its own projects (`/api/cinema/projects/**`): up to 50,each with its folders, takes, Director settings, brief and AI Director chat, deleted with the account. Anotherdiff --git a/src/app/api/generations/zip/route.ts b/src/app/api/generations/zip/route.tsindex 85e9b67d..a8087117 100644--- a/src/app/api/generations/zip/route.ts+++ b/src/app/api/generations/zip/route.ts@@ -1,23 +1,56 @@import { connection } from "next/server";+import { GUEST_HEADER, GUEST_LIBRARY_MESSAGE } from "@/lib/guest-access";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } from "@/server/account-files";+import { accountZipBusy, accountZipStream } from "@/server/account-zip";+import { requestViewer } from "@/server/auth";import { ZIP_MAX_BYTES, zipEntries } from "@/server/library";-import { zipSize, zipStream } from "@/server/zip";+import { zipSize, zipStream, type ZipEntry } from "@/server/zip";-/** Download the finished outputs of several generations as one zip: GET ?ids=a,b,c (up to 500). */-export async function GET(request: Request) {- await connection();- const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean);- if (!ids.length) return Response.json({ error: "Pick something to download" }, { status: 400 });- const entries = zipEntries(ids);- if (!entries.length) return Response.json({ error: "Nothing finished to download yet" }, { status: 404 });- const size = zipSize(entries);- if (size > ZIP_MAX_BYTES) return Response.json({ error: "That's over 4 GB. Download fewer items at a time." }, { status: 413 });- const day = new Date().toISOString().slice(0, 10);- return new Response(zipStream(entries), {+const NOTHING = "Nothing finished to download yet";++const zipResponse = (entries: ZipEntry[], size: number, body: ReadableStream<Uint8Array>) =>+ new Response(body, {headers: {"Content-Type": "application/zip","Content-Length": String(size),- "Content-Disposition": `attachment; filename="fuobe-${day}-${entries.length}-files.zip"`,+ "Content-Disposition": `attachment; filename="fuobe-${new Date().toISOString().slice(0, 10)}-${entries.length}-files.zip"`,"Cache-Control": "no-store",},});++/**+ * Download the finished outputs of several generations as one zip: GET ?ids=a,b,c (up to 500).+ *+ * A signed-in account (public sign-up) zips its own runs only: an id that isn't its own is left out, exactly as one+ * that doesn't exist, so the answer never says whether someone else's run is there (none of its own: 404). It zips up+ * to ACCOUNT_LIMITS.zipRuns runs and zipBytes bytes, one zip at a time (429 while one is going). Its `?check=1` answers+ * {files, size} (or the refusal) without the zip, so the page can say why first. A guest gets the sign-up card.+ */+export async function GET(request: Request) {+ await connection();+ const viewer = requestViewer(request);+ if (viewer.kind === "guest") return Response.json({ error: GUEST_LIBRARY_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", "Cache-Control": "no-store" } });+ const sp = new URL(request.url).searchParams;+ const ids = (sp.get("ids") ?? "").split(",").map((s) => s.trim()).filter(Boolean);+ if (!ids.length) return Response.json({ error: "Pick something to download" }, { status: 400 });++ if (viewer.kind === "account") {+ const account = viewer.account.id;+ if (new Set(ids).size > ACCOUNT_LIMITS.zipRuns) return Response.json({ error: ACCOUNT_MESSAGES.zipTooMany }, { status: 413 });+ if (accountZipBusy(account)) return Response.json({ error: ACCOUNT_MESSAGES.zipBusy }, { status: 429, headers: { "Retry-After": "30" } });+ const entries = zipEntries(ids, { account });+ if (!entries.length) return Response.json({ error: NOTHING }, { status: 404 });+ const size = zipSize(entries);+ if (size > ACCOUNT_LIMITS.zipBytes) return Response.json({ error: ACCOUNT_MESSAGES.zipTooBig }, { status: 413 });+ if (sp.get("check") === "1") return Response.json({ files: entries.length, size });+ const body = accountZipStream(account, zipStream(entries));+ if (!body) return Response.json({ error: ACCOUNT_MESSAGES.zipBusy }, { status: 429, headers: { "Retry-After": "30" } });+ return zipResponse(entries, size, body);+ }++ const entries = zipEntries(ids);+ if (!entries.length) return Response.json({ error: NOTHING }, { status: 404 });+ const size = zipSize(entries);+ if (size > ZIP_MAX_BYTES) return Response.json({ error: "That's over 4 GB. Download fewer items at a time." }, { status: 413 });+ return zipResponse(entries, size, zipStream(entries));}diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 8fd528de..5ba22b28 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -52,6 +52,7 @@ import { starterShown, type StarterCardData } from "@/lib/starters/types";import { cn } from "@/lib/utils";import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";import { toastError } from "@/lib/refusals";+import { ACCOUNT_ZIP_MAX_RUNS } from "@/lib/guest-access";type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "shared" | "trash";@@ -856,10 +857,17 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {icon={Download}label="Download"disabled={!selectedGens.some((g) => g.status === "succeeded")}- onClick={() => {+ onClick={async () => {const done = selectedGens.filter((g) => g.status === "succeeded").map((g) => g.id);- downloadUrl(`/api/generations/zip?ids=${done.slice(0, BULK_MAX).join(",")}`);- if (done.length > BULK_MAX) toast(`The zip has the first ${BULK_MAX} of ${done.length}`, { description: "Select the rest and download them as a second zip." });+ // A signed-in account zips its own runs, fewer at a time, one zip at a time: it asks first, so a refusal is said, not a failed download.+ const max = account && !owner ? ACCOUNT_ZIP_MAX_RUNS : BULK_MAX;+ const href = `/api/generations/zip?ids=${done.slice(0, max).join(",")}`;+ if (account && !owner) {+ const r = await fetch(`${href}&check=1`).catch(() => null);+ if (!r?.ok) return toastError(new Error(((await r?.json().catch(() => null)) as { error?: string } | null)?.error ?? "Couldn't make the zip. Try again."));+ }+ downloadUrl(href);+ if (done.length > max) toast(`The zip has the first ${max} of ${done.length}`, { description: "Select the rest and download them as a second zip." });}}/>{/* The steps behind the selected results as a skill (a whole stack when its batch is selected). Stays on phones. */}diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex 732a041a..e7fd475b 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -99,7 +99,7 @@ function Session({ s }: { s: View }) {const router = useRouter();const actions = useShortsActions(s.id);const engineMode = useEngineMode();- // The studio's owner keeps a Trash and downloads the parts as one zip; a signed-in account's short is its own runs.+ // The studio's owner keeps a Trash; a signed-in account's short is its own runs (deleted for good, its parts zipped as the owner's are).const owner = useIsOwner();const [open, setOpen] = useState<Generation | null>(null);const [confirm, setConfirm] = useState(false);@@ -192,7 +192,7 @@ function Session({ s }: { s: View }) {<Download className="size-4" /> Download full video</a>)}- {owner && parts.length > 0 && (+ {parts.length > 0 && (<a href={`/api/generations/zip?ids=${parts.join(",")}`} className="inline-flex h-9 items-center gap-1.5 rounded-full border bg-background px-4 text-[13px] font-medium hover:bg-accent"><FolderDown className="size-4" /> Download parts{parts.length < s.segments.length ? ` (${parts.length})` : ""}</a>diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 59f8970d..2787a77e 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -174,8 +174,18 @@ export function accountOwnRead(pathname: string): boolean {/** An account's own canvases (src/app/api/account/canvases): the routes read and change its own boards only. */const ACCOUNT_CANVASES = /^\/api\/account\/canvases(\/[^/]+)?$/;-/** The Library's counts and its Uploads (its stored files): each route answers an account with its own only. */-const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets"]);+/**+ * The Library's counts, its Uploads (its stored files) and a zip of its runs (the Library's Download, a result's+ * Download all, Shorts' Download parts): each route answers an account with its own only.+ */+const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets", "/api/generations/zip"]);++/**+ * A signed-in account's zip of its own runs (/api/generations/zip; src/server/account-files.ts ACCOUNT_LIMITS): at most+ * this many runs and this many bytes in one zip, one zip at a time. The Library sends at most this many.+ */+export const ACCOUNT_ZIP_MAX_RUNS = 200;+export const ACCOUNT_ZIP_MAX_BYTES = 2 ** 30;/*** "Use the ComfyUI on this computer": the routes the person's own Fuobe tab runs their jobs through. Each takes whosediff --git a/src/server/account-files.ts b/src/server/account-files.tsindex 75e5ba46..c0909dcd 100644--- a/src/server/account-files.ts+++ b/src/server/account-files.ts@@ -1,5 +1,6 @@import "server-only";import fs from "node:fs";+import { ACCOUNT_ZIP_MAX_BYTES, ACCOUNT_ZIP_MAX_RUNS } from "@/lib/guest-access";import { accountById } from "./auth";import { DATA_DIR, db } from "./db";@@ -60,6 +61,10 @@ export const ACCOUNT_LIMITS = {finishesPerHour: 240,/** 3D models finished on this server (the web GLB, model3d-finish.ts) per hour; past it a model is kept as it came. */modelFinishesPerHour: 60,+ /** A zip of its own runs (streamed, nothing written to disk): runs and bytes in one zip, and how long one may sit idle. */+ zipRuns: ACCOUNT_ZIP_MAX_RUNS,+ zipBytes: ACCOUNT_ZIP_MAX_BYTES,+ zipIdleMs: 2 * 60_000,} as const;export const RETENTION_MS = { upload: ACCOUNT_LIMITS.uploadDays * DAY, run: ACCOUNT_LIMITS.runDays * DAY };@@ -87,6 +92,9 @@ export const ACCOUNT_MESSAGES = {probeRate: "Too many clip checks at once. Wait a moment, then try again.",reloadToUpload: "Reload the page, then upload again.",lengthNeeded: "That upload didn't go through. Please try again.",+ zipTooMany: `Download up to ${ACCOUNT_ZIP_MAX_RUNS} at a time.`,+ zipTooBig: "That's over 1 GB. Download fewer items at a time.",+ zipBusy: "Your last download is still going. Try again when it finishes.",} as const;/** What an account may keep in all: 3 GB, or 1 GB in its first 7 days (`created`: when it signed up, when known). */diff --git a/src/server/account-zip.ts b/src/server/account-zip.tsnew file mode 100644index 00000000..b546cb5c--- /dev/null+++ b/src/server/account-zip.ts@@ -0,0 +1,59 @@+import "server-only";+import { ACCOUNT_LIMITS } from "./account-files";++/**+ * One zip at a time per signed-in account (/api/generations/zip): a zip is streamed from the files on disk, so it+ * holds no memory or disk, but each one keeps a file open and the server sending. A zip counts as going while its+ * reader keeps pulling: it ends when the zip is sent, the download is stopped, or nothing is pulled for+ * ACCOUNT_LIMITS.zipIdleMs (a stalled download never locks the account out).+ */++interface Going {+ touched: number;+}++declare global {+ var __fuobeAccountZips: Map<string, Going> | undefined;+}++const going = (): Map<string, Going> => (globalThis.__fuobeAccountZips ??= new Map());++/** Whether this account has a zip going now. */+export function accountZipBusy(account: string, now = Date.now()): boolean {+ const g = going().get(account);+ return !!g && now - g.touched < ACCOUNT_LIMITS.zipIdleMs;+}++/**+ * Send `stream` as this account's one zip: null when it has one going. The stream returned marks the zip as going+ * while it is read, and frees the account when it ends, fails or is cancelled.+ */+export function accountZipStream(account: string, stream: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> | null {+ if (accountZipBusy(account)) return null;+ const mine: Going = { touched: Date.now() };+ going().set(account, mine);+ // A later zip may take the place of a stalled one: only this zip's own entry is removed.+ const done = () => {+ if (going().get(account) === mine) going().delete(account);+ };+ const reader = stream.getReader();+ return new ReadableStream<Uint8Array>({+ async pull(controller) {+ mine.touched = Date.now();+ try {+ const r = await reader.read();+ if (r.done) {+ done();+ controller.close();+ } else controller.enqueue(r.value);+ } catch (e) {+ done();+ controller.error(e);+ }+ },+ async cancel(reason) {+ done();+ await reader.cancel(reason);+ },+ });+}diff --git a/src/server/library.ts b/src/server/library.tsindex d766451f..4cfc9685 100644--- a/src/server/library.ts+++ b/src/server/library.ts@@ -21,6 +21,7 @@ import {type Folder,type ReviewFilter,} from "@/lib/library";+import { fileAccount, generationAccount } from "./account-library";import { db } from "./db";import { assetUses, cancelGeneration, deleteGeneration, getGeneration, type ListOptions } from "./generations";import { absolutePath, deleteAsset, getAsset } from "./storage";@@ -424,16 +425,23 @@ export const ZIP_MAX_BYTES = 4 * 1024 ** 3 - 1;/** Results a folder zip takes at most, its subfolders' included (the zip format counts entries in 16 bits). */export const FOLDER_ZIP_MAX = 5000;-/** Add the finished output files of these generations under `prefix`, with readable names unique in the zip. */-function addEntries(list: string[], prefix: string, used: Set<string>, out: ZipEntry[]): void {+/**+ * Add the finished output files of these generations under `prefix`, with readable names unique in the zip. With+ * `account` (a signed-in account's zip): only its own runs, and of their files only those it may open itself+ * (fileAccount: its own, and not held for a check). Anything else is left out, as if it didn't exist.+ */+function addEntries(list: string[], prefix: string, used: Set<string>, out: ZipEntry[], account?: string): void {for (const id of list) {+ if (account !== undefined && generationAccount(id) !== account) continue;const g = getGeneration(id, { includeDeleted: true });if (!g || g.status !== "succeeded") continue;g.outputs.forEach((o, i) => {if (!o.url.startsWith("/api/files/")) return;let file: string;try {- file = absolutePath(decodeURIComponent(o.url.slice("/api/files/".length).split("?")[0]));+ const rel = decodeURIComponent(o.url.slice("/api/files/".length).split("?")[0]);+ if (account !== undefined && fileAccount(rel) !== account) return;+ file = absolutePath(rel);} catch {return;}@@ -447,10 +455,10 @@ function addEntries(list: string[], prefix: string, used: Set<string>, out: ZipE}}-/** The finished output files of these generations, with readable, unique names. */-export function zipEntries(list: string[]): ZipEntry[] {+/** The finished output files of these generations, with readable, unique names (`account`: that account's own only). */+export function zipEntries(list: string[], opts: { account?: string } = {}): ZipEntry[] {const out: ZipEntry[] = [];- addEntries(ids(list), "", new Set(), out);+ addEntries(ids(list), "", new Set(), out, opts.account);return out;}diff --git a/tests/account-zip.test.ts b/tests/account-zip.test.tsnew file mode 100644index 00000000..76f03663--- /dev/null+++ b/tests/account-zip.test.ts@@ -0,0 +1,199 @@+import fs from "node:fs";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";+// Route handlers call connection(); outside a request scope it would throw.+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));++/**+ * A signed-in account (public sign-up) downloads its own runs as one zip (the Library's Download, a result's Download+ * all, Shorts' Download parts): never anyone else's, within its limits, one zip at a time. A guest is offered to sign up.+ */++const dir = tempDir("fuobe-account-zip-");+process.env.FUOBE_DATA_DIR = dir;+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOWED_ORIGINS;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+const auth = await import("@/server/auth");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+const { db } = await import("@/server/db");+const { FILES_DIR } = await import("@/server/storage");+const { ACCOUNT_LIMITS, ACCOUNT_MESSAGES } = await import("@/server/account-files");+const { accountZipBusy } = await import("@/server/account-zip");+const { GET } = await import("@/app/api/generations/zip/route");+afterAll(() => {+ delete process.env.FUOBE_PUBLIC_SIGNUP;+});++let a = "";+let aId = "";+let b = "";+let bId = "";+let owner = "";++/** A finished run with one output file: whose run it is (null: the owner's), and whose file (held: waiting for its check). */+function run(id: string, who: string | null, opts: { held?: boolean; fileOwner?: string | null } = {}) {+ const rel = `outputs/${id}.png`;+ fs.mkdirSync(path.join(FILES_DIR, "outputs"), { recursive: true });+ fs.writeFileSync(path.join(FILES_DIR, rel), `png of ${id}`);+ const now = Date.now();+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'm', 'open', 'comfyui', 'text-to-image', 'image', 'succeeded', ?, ?, ?, ?)",+ )+ .run(id, JSON.stringify({ feature: "image", modelId: "m", prompt: id, ...(who && { account: who }) }), JSON.stringify([{ url: `/api/files/${rel}` }]), now, now);+ db()+ .prepare("INSERT INTO assets (id, kind, rel_path, content_type, size, source, generation_id, account_id, held, created_at) VALUES (?, 'image', ?, 'image/png', ?, 'generation', ?, ?, ?, ?)")+ .run(`as-${id}`, rel, fs.statSync(path.join(FILES_DIR, rel)).size, id, opts.fileOwner === undefined ? who : opts.fileOwner, opts.held ? 1 : 0, now);+}++const get = (ids: string[], cookie?: string, extra = "") =>+ GET(new Request(`http://localhost:3000/api/generations/zip?ids=${ids.join(",")}${extra}`, cookie ? { headers: { cookie: `${auth.SESSION_COOKIE}=${cookie}` } } : undefined));++async function names(r: Response): Promise<string[]> {+ const buf = Buffer.from(await r.arrayBuffer());+ expect(buf.length).toBe(Number(r.headers.get("content-length")));+ // The central directory's names (signature 0x02014b50, name length at +28, name at +46).+ const out: string[] = [];+ for (let i = buf.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02])); i >= 0; i = buf.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]), i + 4)) {+ out.push(buf.subarray(i + 46, i + 46 + buf.readUInt16LE(i + 28)).toString("utf8"));+ }+ return out;+}++beforeAll(() => {+ auth.setPassword("install password");+ const accA = auth.createAccount("[email protected]", "long enough");+ aId = accA.id;+ a = auth.createSession(aId).value;+ const accB = auth.createAccount("[email protected]", "long enough");+ bId = accB.id;+ b = auth.createSession(bId).value;+ owner = auth.createSession().value;+ run("a-1", aId);+ run("a-2", aId);+ run("a-held", aId, { held: true });+ run("b-1", bId);+ run("owner-1", null);+ // An account's run naming a file that isn't its own (it may not open it, so it isn't zipped either).+ run("a-odd", aId, { fileOwner: bId });+});++describe("the proxy", () => {+ it("passes an account's zip to the route, and offers a guest to sign up", async () => {+ expect(proxy(new NextRequest("http://localhost:3000/api/generations/zip?ids=a-1", { headers: { cookie: `${auth.SESSION_COOKIE}=${a}` } })).headers.get("x-middleware-next")).toBe("1");+ const guest = proxy(new NextRequest("http://localhost:3000/api/generations/zip?ids=a-1"));+ expect(guest.status).toBe(401);+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");+ expect((await guest.json()).error).toBe(access.GUEST_LIBRARY_MESSAGE);+ });+});++describe("an account's zip", () => {+ it("holds its own runs", async () => {+ const r = await get(["a-1", "a-2"], a);+ expect(r.status).toBe(200);+ expect(r.headers.get("content-type")).toBe("application/zip");+ expect((await names(r)).sort()).toEqual([expect.stringMatching(/^a-1/), expect.stringMatching(/^a-2/)]);+ });++ it("leaves out anyone else's runs, as if they didn't exist", async () => {+ const mixed = await get(["a-1", "b-1", "owner-1"], a);+ expect(mixed.status).toBe(200);+ const got = await names(mixed);+ expect(got).toHaveLength(1);+ expect(got[0]).toMatch(/^a-1/);+ // Only someone else's: the same answer as an id that isn't there at all.+ const foreign = await get(["b-1", "owner-1"], a);+ const missing = await get(["no-such-run"], a);+ expect(foreign.status).toBe(404);+ expect(missing.status).toBe(404);+ expect(await foreign.json()).toEqual(await missing.json());+ // B can't zip A's either.+ expect((await get(["a-1", "a-2"], b)).status).toBe(404);+ });++ it("leaves out a file held for its check, and a file that isn't its own", async () => {+ expect((await get(["a-held", "a-odd"], a)).status).toBe(404);+ });++ it("says how big it is first, when asked", async () => {+ const r = await get(["a-1", "a-2", "b-1"], a, "&check=1");+ expect(r.status).toBe(200);+ const body = (await r.json()) as { files: number; size: number };+ expect(body.files).toBe(2);+ expect(body.size).toBeGreaterThan(0);+ expect(accountZipBusy(aId)).toBe(false);+ });++ it(`takes up to ${access.ACCOUNT_ZIP_MAX_RUNS} runs and 1 GB`, async () => {+ expect(ACCOUNT_LIMITS.zipRuns).toBe(200);+ expect(ACCOUNT_LIMITS.zipBytes).toBe(2 ** 30);+ const many = ["a-1", ...Array.from({ length: ACCOUNT_LIMITS.zipRuns }, (_, i) => `x-${i}`)];+ const tooMany = await get(many, a);+ expect(tooMany.status).toBe(413);+ expect((await tooMany.json()).error).toBe(ACCOUNT_MESSAGES.zipTooMany);+ // The same id twice counts once.+ expect((await get(["a-1", ...many.slice(1, ACCOUNT_LIMITS.zipRuns), "a-1"], a, "&check=1")).status).toBe(200);+ const limits = ACCOUNT_LIMITS as { zipBytes: number };+ const was = limits.zipBytes;+ limits.zipBytes = 100;+ try {+ const big = await get(["a-1", "a-2"], a);+ expect(big.status).toBe(413);+ expect((await big.json()).error).toBe(ACCOUNT_MESSAGES.zipTooBig);+ } finally {+ limits.zipBytes = was;+ }+ });++ it("makes one zip at a time, and frees the account when it ends, is stopped or stalls", async () => {+ const first = await get(["a-1"], a);+ expect(first.status).toBe(200);+ expect(accountZipBusy(aId)).toBe(true);+ const second = await get(["a-2"], a);+ expect(second.status).toBe(429);+ expect((await second.json()).error).toBe(ACCOUNT_MESSAGES.zipBusy);+ // Another account isn't held up.+ expect((await get(["b-1"], b)).status).toBe(200);+ await first.arrayBuffer();+ expect(accountZipBusy(aId)).toBe(false);+ // Stopped part way.+ const stopped = await get(["a-1"], a);+ await stopped.body!.cancel();+ expect(accountZipBusy(aId)).toBe(false);+ // Stalled: free after the idle time, whatever its reader does.+ const stalled = await get(["a-1"], a);+ expect(accountZipBusy(aId)).toBe(true);+ expect(accountZipBusy(aId, Date.now() + ACCOUNT_LIMITS.zipIdleMs + 1)).toBe(false);+ await stalled.body!.cancel();+ });+});++describe("the owner's zip", () => {+ it("is as it was: any run, no account limits", async () => {+ const r = await get(["a-1", "b-1", "owner-1"], owner);+ expect(r.status).toBe(200);+ expect(await names(r)).toHaveLength(3);+ const many = ["owner-1", ...Array.from({ length: 300 }, (_, i) => `x-${i}`)];+ expect((await get(many, owner)).status).toBe(200);+ // Two at once.+ const one = await get(["owner-1"], owner);+ const two = await get(["owner-1"], owner);+ expect([one.status, two.status]).toEqual([200, 200]);+ await one.arrayBuffer();+ await two.arrayBuffer();+ });+});++describe("a guest", () => {+ it("gets the sign-up card from the route too", async () => {+ const r = await get(["a-1"]);+ expect(r.status).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");+ expect((await r.json()).error).toBe(access.GUEST_LIBRARY_MESSAGE);+ });+});diff --git a/tests/public-signup.test.ts b/tests/public-signup.test.tsindex 6aebc4e8..93dfadb4 100644--- a/tests/public-signup.test.ts+++ b/tests/public-signup.test.ts@@ -270,10 +270,10 @@ describe("accounts never run on the owner's keys or GPU", () => {describe("accounts never see or change the owner's library", () => {const families: Record<string, { lists: string[]; records: string[]; changes: [string, string][] }> = {generations: {- // (/api/generations, its facets and its bulk changes go to the routes, which take only the account's own runs:- // tests/account-gpu.test.ts, tests/public-signup-visitors.test.ts.)+ // (/api/generations, its facets, its zip and its bulk changes go to the routes, which take only the account's own runs:+ // tests/account-gpu.test.ts, tests/public-signup-visitors.test.ts, tests/account-zip.test.ts.)lists: ["/api/generations/trash"],- records: ["/api/generations/g1", "/api/generations/zip?ids=g1"],+ records: ["/api/generations/g1"],changes: [["PATCH", "/api/generations/g1"], ["DELETE", "/api/generations/g1"], ["DELETE", "/api/generations/trash"], ["POST", "/api/generations/g1/cancel"]],},// (POST /api/uploads is the account's own: the route checks it, tests/account-uploads.test.ts; so is the list of its