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
Downloads: zips of results ask first and say why when they can't start
Adarshbd000812a5f2
diff --git a/src/app/api/generations/zip/route.ts b/src/app/api/generations/zip/route.tsindex a8087117..64c54319 100644--- a/src/app/api/generations/zip/route.ts+++ b/src/app/api/generations/zip/route.ts@@ -23,8 +23,9 @@ const zipResponse = (entries: ZipEntry[], size: number, body: ReadableStream<Uin** 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.+ * to ACCOUNT_LIMITS.zipRuns runs and zipBytes bytes, one zip at a time (429 while one is going). `?check=1` (anyone+ * signed in) answers {files, size} (or the refusal) without the zip, so the page can say why first+ * (src/lib/zip-download.ts). A guest gets the sign-up card.*/export async function GET(request: Request) {await connection();@@ -52,5 +53,6 @@ export async function GET(request: Request) {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 });+ if (sp.get("check") === "1") return Response.json({ files: entries.length, size });return zipResponse(entries, size, zipStream(entries));}diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 5ba22b28..930aab00 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -18,7 +18,7 @@ import { PageShell } from "@/components/page-shell";import { useShare } from "@/components/share/share-provider";import { SharedLinks } from "@/components/share/shared-links";import { useSkillBuilder } from "@/components/skills/skill-builder-provider";-import { downloadUrl, ForeverConfirmProvider, useConfirmForever } from "@/components/studio/result-actions";+import { ForeverConfirmProvider, useConfirmForever } from "@/components/studio/result-actions";import { Viewer } from "@/components/studio/viewer";import {AlertDialog,@@ -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 { downloadZip } from "@/lib/zip-download";import { ACCOUNT_ZIP_MAX_RUNS } from "@/lib/guest-access";type TabId = "all" | "images" | "videos" | "audio" | "text" | "3d" | "favorites" | "uploads" | "shared" | "trash";@@ -859,14 +860,9 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {disabled={!selectedGens.some((g) => g.status === "succeeded")}onClick={async () => {const done = selectedGens.filter((g) => g.status === "succeeded").map((g) => g.id);- // 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.+ // 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 (!(await downloadZip(`/api/generations/zip?ids=${done.slice(0, max).join(",")}`))) return;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." });}}/>diff --git a/src/components/photodump/results.tsx b/src/components/photodump/results.tsxindex aa6ca05d..aa95ae45 100644--- a/src/components/photodump/results.tsx+++ b/src/components/photodump/results.tsx@@ -11,6 +11,7 @@ import { useGenerationActions, useIsAccount } from "@/lib/api";import type { Generation, OutputFile } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { downloadZip } from "@/lib/zip-download";import { useRetryPhoto } from "./hooks";export interface Tile {@@ -195,7 +196,11 @@ export function DownloadAll({ items, label = "Download" }: { items: Generation[]href={href}downloadaria-disabled={!href}- onClick={(e) => !href && e.preventDefault()}+ onClick={(e) => {+ // Asks first (src/lib/zip-download.ts): a refusal (a zip still going, too big) is a toast, not a failed download.+ e.preventDefault();+ if (href) void downloadZip(href);+ }}className={cn("inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/90",!href && "pointer-events-none opacity-50",diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex e7fd475b..984f7e29 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -31,6 +31,7 @@ import { formatCost, ratioValue, timeAgo } from "@/lib/format";import { downloadHref, downloadName } from "@/lib/library";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";+import { onZipLink } from "@/lib/zip-download";import { useShortsActions, useShortsSession, useSubmitGuard, type ShortsSessionView as View } from "./hooks";import { Steps } from "./ui";@@ -193,7 +194,13 @@ function Session({ s }: { s: View }) {</a>)}{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">+ <a+ href={`/api/generations/zip?ids=${parts.join(",")}`}+ download+ // Asks first: a refusal (a zip still going, too big) is a toast, never a page of its own.+ onClick={onZipLink}+ 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/zip-download.ts b/src/lib/zip-download.tsnew file mode 100644index 00000000..bbb0cdf6--- /dev/null+++ b/src/lib/zip-download.ts@@ -0,0 +1,43 @@+import { toast } from "sonner";++const asking = new Set<string>();++/**+ * Download a zip of results (/api/generations/zip?ids=…: Shorts' Download parts, Photodump's Download all, the+ * Library's Download). It asks the route first (`&check=1`, no zip made), so a refusal (nothing finished yet, too big, a+ * zip still going) is said in a toast and the page stays where it is; then the zip downloads without leaving the page.+ * A second click on the same zip while the first is being asked does nothing. Resolves true when the download started.+ */+export async function downloadZip(href: string): Promise<boolean> {+ if (asking.has(href)) return false;+ asking.add(href);+ try {+ const r = await fetch(`${href}${href.includes("?") ? "&" : "?"}check=1`, { cache: "no-store" }).catch(() => null);+ if (!r?.ok) {+ const said = ((await r?.json().catch(() => null)) as { error?: string } | null)?.error;+ toast.error(said ?? "Couldn't make the zip. Try again.");+ return false;+ }+ const a = document.createElement("a");+ a.href = href;+ a.download = "";+ a.click();+ return true;+ } finally {+ // The zip starts streaming a moment after the click: until then a second click would only be refused.+ setTimeout(() => asking.delete(href), 2000);+ }+}++/** A results zip link (it goes through downloadZip); every other download link downloads as it is. */+export const isZipHref = (href: string | undefined): href is string => !!href && href.startsWith("/api/generations/zip?");++/**+ * For any download <a> (`onClick={onZipLink}`): a results zip asks first (downloadZip); any other link is left alone.+ */+export function onZipLink(e: { currentTarget: HTMLAnchorElement; preventDefault(): void }): void {+ const href = e.currentTarget.getAttribute("href") ?? undefined;+ if (!isZipHref(href)) return;+ e.preventDefault();+ void downloadZip(href);+}diff --git a/tests/account-zip.test.ts b/tests/account-zip.test.tsindex 76f03663..810a904e 100644--- a/tests/account-zip.test.ts+++ b/tests/account-zip.test.ts@@ -187,6 +187,14 @@ describe("the owner's zip", () => {await one.arrayBuffer();await two.arrayBuffer();});++ it("says how big it is first, when asked, as an account's does", async () => {+ const r = await get(["a-1", "owner-1"], owner, "&check=1");+ expect(r.status).toBe(200);+ expect(r.headers.get("content-type")).toContain("application/json");+ expect(((await r.json()) as { files: number }).files).toBe(2);+ expect((await get(["no-such-run"], owner, "&check=1")).status).toBe(404);+ });});describe("a guest", () => {diff --git a/tests/zip-download.test.ts b/tests/zip-download.test.tsnew file mode 100644index 00000000..c251dfee--- /dev/null+++ b/tests/zip-download.test.ts@@ -0,0 +1,89 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++/**+ * A results zip (Shorts' Download parts, Photodump's Download all, the Library's Download) asks the route first: a+ * refusal is a toast and the page stays where it is; only a zip the route will make is downloaded.+ */++const errors: string[] = [];+vi.mock("sonner", () => ({ toast: { error: (m: string) => errors.push(m) } }));+const { downloadZip, isZipHref, onZipLink } = await import("@/lib/zip-download");++const clicked: string[] = [];+let asked: string[] = [];+let answer: () => Response = () => Response.json({ files: 1, size: 10 });++beforeEach(() => {+ vi.useFakeTimers();+ errors.length = 0;+ clicked.length = 0;+ asked = [];+ vi.stubGlobal("document", {+ createElement: () => {+ const a = { href: "", download: undefined as string | undefined, click: () => clicked.push(a.href) };+ return a;+ },+ });+ vi.stubGlobal("fetch", async (url: string) => {+ asked.push(url);+ return answer();+ });+});+afterEach(() => {+ vi.runAllTimers();+ vi.useRealTimers();+ vi.unstubAllGlobals();+});++const ZIP = "/api/generations/zip?ids=a,b";++describe("downloadZip", () => {+ it("asks first, then downloads", async () => {+ answer = () => Response.json({ files: 2, size: 10 });+ expect(await downloadZip(ZIP)).toBe(true);+ expect(asked).toEqual([`${ZIP}&check=1`]);+ expect(clicked).toEqual([ZIP]);+ expect(errors).toEqual([]);+ });++ it("says the route's refusal and downloads nothing", async () => {+ answer = () => Response.json({ error: "Your last download is still going" }, { status: 429 });+ expect(await downloadZip(ZIP)).toBe(false);+ expect(clicked).toEqual([]);+ expect(errors).toEqual(["Your last download is still going"]);+ });++ it("says something when the route can't be reached", async () => {+ vi.stubGlobal("fetch", async () => {+ throw new Error("offline");+ });+ expect(await downloadZip(ZIP)).toBe(false);+ expect(clicked).toEqual([]);+ expect(errors).toHaveLength(1);+ });++ it("does nothing on a second click while the first is going", async () => {+ answer = () => Response.json({ files: 2, size: 10 });+ const [one, two] = await Promise.all([downloadZip(ZIP), downloadZip(ZIP)]);+ expect([one, two]).toEqual([true, false]);+ expect(asked).toHaveLength(1);+ vi.advanceTimersByTime(2000);+ expect(await downloadZip(ZIP)).toBe(true);+ });+});++describe("onZipLink", () => {+ const link = (href: string) => {+ let prevented = false;+ onZipLink({ currentTarget: { getAttribute: () => href } as unknown as HTMLAnchorElement, preventDefault: () => (prevented = true) });+ return prevented;+ };++ it("takes over a results zip link and leaves every other download alone", async () => {+ answer = () => Response.json({ files: 2, size: 10 });+ expect(link(ZIP)).toBe(true);+ expect(link("/api/files/outputs/a.png?download=a.png")).toBe(false);+ expect(isZipHref("/api/folders/f1/zip")).toBe(false);+ await vi.waitFor(() => expect(clicked).toEqual([ZIP]));+ });+});