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
Guests: a refused upload or run shows one card, which closes when the page changes
Adarsha304e1b8dc00
diff --git a/src/components/color-grade-view.tsx b/src/components/color-grade-view.tsxindex 6322f76d..efdff968 100644--- a/src/components/color-grade-view.tsx+++ b/src/components/color-grade-view.tsx@@ -13,6 +13,7 @@ import { uploadFile } from "@/lib/api";import { applyPreset, CONTROLS, describeGrade, FRAGMENT, isNeutral, NEUTRAL, PRESETS, uniforms, VERTEX, type Grade } from "@/lib/grade";import { cn } from "@/lib/utils";import { loseContext as loseGlContext, releaseVideo } from "@/lib/media-release";+import { toastError } from "@/lib/refusals";type Source = HTMLImageElement | HTMLVideoElement;@@ -296,7 +297,8 @@ function Grader() {if (!blob) throw new Error("Couldn't export the image");await record(new File([blob], "graded.png", { type: "image/png" }), "image");} catch (e) {- toast.error((e as Error).message);+ // A guest's save opens "Create a free account" (an account's, "Connect your GPU"): nothing on top of it.+ toastError(e);} finally {setSaving(null);}@@ -348,7 +350,7 @@ function Grader() {if (!alive.current) return;await record(new File(chunks, "graded.webm", { type: "video/webm" }), "video");} catch (e) {- if (alive.current) toast.error((e as Error).message);+ if (alive.current) toastError(e);} finally {release(clip);if (alive.current) setSaving(null);diff --git a/src/components/guest-prompt.tsx b/src/components/guest-prompt.tsxindex ee2c707f..722be54d 100644--- a/src/components/guest-prompt.tsx+++ b/src/components/guest-prompt.tsx@@ -2,26 +2,36 @@import { Cpu, Sparkles } from "lucide-react";import Link from "next/link";-import { useEffect, useState } from "react";+import { usePathname } from "next/navigation";+import { Suspense, useCallback, useEffect, useState } from "react";import { YourGpu } from "@/components/gpu/your-gpu";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";-import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, signInHref, watchGuestRefusals } from "@/lib/api";--type Prompt = { kind: "guest"; here: string } | { kind: "gpu" };+import { CONNECT_GPU_EVENT, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGuestRefusals, type RefusalCard } from "@/lib/api";/*** The cards a public studio shows when something is refused (watchGuestRefusals): "Create a free* account to run this" for a guest (public sign-up, signed out) who tries to generate, upload or* change anything, and "Connect your GPU to run this" for an account (accounts run only on their- * own ComfyUI, never the owner's keys or GPU). Mounted once, in the app's providers.+ * own ComfyUI, never the owner's keys or GPU). Mounted once, in the app's providers, so it outlives+ * the page: a card closes when the page changes (its own Sign up or Log in, Back), and never opens+ * on the sign-in page (refusalCard).*/export function GuestPrompt() {- const [prompt, setPrompt] = useState<Prompt | null>(null);+ // The last card stays while the dialog animates out.+ const [card, setCard] = useState<RefusalCard | null>(null);+ const [open, setOpen] = useState(false);+ const close = useCallback(() => setOpen(false), []);useEffect(() => {watchGuestRefusals();- const guest = () => setPrompt({ kind: "guest", here: window.location.pathname + window.location.search });- const gpu = () => setPrompt({ kind: "gpu" });+ const show = (kind: RefusalCard["kind"]) => {+ const next = refusalCard(kind, window.location);+ if (!next) return;+ setCard(next);+ setOpen(true);+ };+ const guest = () => show("guest");+ const gpu = () => show("gpu");window.addEventListener(GUEST_PROMPT_EVENT, guest);window.addEventListener(CONNECT_GPU_EVENT, gpu);return () => {@@ -30,45 +40,61 @@ export function GuestPrompt() {};}, []);return (- <Dialog open={prompt !== null} onOpenChange={(o) => !o && setPrompt(null)}>- <DialogContent className={prompt?.kind === "gpu" ? "max-h-[90svh] overflow-y-auto sm:max-w-xl" : "sm:max-w-sm"}>- {prompt?.kind === "gpu" ? (- <>- <DialogHeader>- <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">- <Cpu className="size-5" />- </div>- <DialogTitle>Connect your GPU to run this</DialogTitle>- <DialogDescription>- Or run Fuobe on your own computer: it's{" "}- <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" className="underline underline-offset-4">- open source- </a>- .- </DialogDescription>- </DialogHeader>- <YourGpu />- </>- ) : (- <>- <DialogHeader>- <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">- <Sparkles className="size-5" />- </div>- <DialogTitle>Create a free account to run this</DialogTitle>- <DialogDescription>You're browsing as a guest. Sign up with an email and a password to generate, upload and keep your work.</DialogDescription>- </DialogHeader>- <DialogFooter className="gap-2 sm:justify-start">- <Button asChild>- <Link href={signInHref("signup", prompt?.here)}>Sign up free</Link>- </Button>- <Button asChild variant="secondary">- <Link href={signInHref("login", prompt?.here)}>Log in</Link>- </Button>- </DialogFooter>- </>- )}- </DialogContent>- </Dialog>+ <>+ <Suspense fallback={null}>+ <CloseOnNavigation close={close} />+ </Suspense>+ <Dialog open={open} onOpenChange={(o) => !o && close()}>+ <DialogContent className={card?.kind === "gpu" ? "max-h-[90svh] overflow-y-auto sm:max-w-xl" : "sm:max-w-sm"}>+ {card?.kind === "gpu" ? (+ <>+ <DialogHeader>+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">+ <Cpu className="size-5" />+ </div>+ <DialogTitle>Connect your GPU to run this</DialogTitle>+ <DialogDescription>+ Or run Fuobe on your own computer: it's{" "}+ <a href="https://github.com/workingprototype/fuobe" target="_blank" rel="noreferrer" className="underline underline-offset-4">+ open source+ </a>+ .+ </DialogDescription>+ </DialogHeader>+ <YourGpu />+ </>+ ) : (+ <>+ <DialogHeader>+ <div className="mb-1 grid size-10 place-items-center rounded-xl bg-primary text-primary-foreground">+ <Sparkles className="size-5" />+ </div>+ <DialogTitle>Create a free account to run this</DialogTitle>+ <DialogDescription>You're browsing as a guest. Sign up with an email and a password to generate, upload and keep your work.</DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-2 sm:justify-start">+ <Button asChild>+ <Link href={signInHref("signup", card?.here)} onClick={close}>+ Sign up free+ </Link>+ </Button>+ <Button asChild variant="secondary">+ <Link href={signInHref("login", card?.here)} onClick={close}>+ Log in+ </Link>+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ </>);}++/** Closes the card when the page changes. Reads the path (runtime data), so it sits under Suspense: routes still prerender. */+function CloseOnNavigation({ close }: { close: () => void }) {+ const pathname = usePathname();+ useEffect(() => close(), [pathname, close]);+ return null;+}diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsxindex 87b63d6a..798e9dec 100644--- a/src/components/studio/composer.tsx+++ b/src/components/studio/composer.tsx@@ -65,6 +65,7 @@ import {startStep,} from "@/lib/composer";import { formatCost } from "@/lib/format";+import { toastError } from "@/lib/refusals";import { cn } from "@/lib/utils";import { badgeFor, badgeText, openGpuSetup, setGpuRetry, useGpuBadges } from "@/hooks/use-gpu";import { AttachMenu } from "./attach-menu";@@ -517,8 +518,8 @@ export function Composer({ docked }: { docked: boolean }) {() => submitRef.current(true),);create.mutate(skipGpu ? ({ ...sent.request, gpuCheck: "skip" } as typeof sent.request) : sent.request, {- // Stopped by the GPU pre-flight: the guided fix is open already, so no error toast on top.- onError: (e) => void ((e as { gpuSetup?: boolean }).gpuSetup || toast.error((e as Error).message)),+ // Stopped by the GPU pre-flight, or refused with its own card: the guided fix or the card is open already, so no error toast on top.+ onError: (e) => void ((e as { gpuSetup?: boolean }).gpuSetup || toastError(e)),});};@@ -529,7 +530,7 @@ export function Composer({ docked }: { docked: boolean }) {const p = await enhance(draft.prompt, config.kind, op ?? (config.kind === "video" ? "t2v" : "t2i"));setDraft({ prompt: p });} catch (e) {- toast.error((e as Error).message);+ toastError(e);} finally {setEnhancing(false);}diff --git a/src/components/studio/media-slot.tsx b/src/components/studio/media-slot.tsxindex e504cf94..1e04099e 100644--- a/src/components/studio/media-slot.tsx+++ b/src/components/studio/media-slot.tsx@@ -7,6 +7,7 @@ import { toast } from "sonner";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { useAssets, type Asset } from "@/lib/api";+import { toastError } from "@/lib/refusals";import { postFile } from "@/lib/upload";import type { MediaKind } from "@/lib/catalog/types";import { slotCaption } from "@/lib/composer";@@ -87,7 +88,8 @@ export async function fileToSlot(file: File, onChange: (v: SlotValue | null) =>} catch (e) {if (opts.signal?.aborted || (e as Error).name === "AbortError") return;onChange(null);- toast.error((e as Error).message || "Upload failed. Please try again.");+ // Refused with its own card ("Create a free account", "Connect your GPU"): nothing on top of it.+ toastError(e, "Upload failed. Please try again.");} finally {revoke();}diff --git a/src/lib/api.ts b/src/lib/api.tsindex 9f71691e..ac503b7c 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -26,6 +26,7 @@ import {type StreamEvent,} from "./generation-stream";import { cursorAfter, filterToSearch, type AssetUse, type FeedFilter, type Folder } from "./library";+import { markRefusalShown, responseError } from "./refusals";import { postFile } from "./upload";import type { ShareCreated, ShareInfo, ShareListItem, SharePatch, ShareRequest } from "./share";import type { AccessSummary } from "./model-access";@@ -43,7 +44,7 @@ export interface Asset {async function json<T>(res: Response): Promise<T> {const body = (await res.json().catch(() => ({}))) as T & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Request failed (${res.status})`);return body;}@@ -1099,24 +1100,43 @@ export const CONNECT_GPU_EVENT = "fuobe:connect-gpu";/** The guided fix (src/components/gpu/guided-fix.tsx): { ref, plan? }. */export const GPU_SETUP_EVENT = "fuobe:gpu-setup";+/** A card GuestPrompt shows for a refusal: "Create a free account" (coming back to `here` after) or "Connect your GPU". */+export type RefusalCard = { kind: "guest"; here: string } | { kind: "gpu" };++/**+ * The card a refusal opens on this page. None on the sign-in page: the visitor is signing in already,+ * and a wrong password there is the form's own error.+ */+export function refusalCard(kind: RefusalCard["kind"], at: { pathname: string; search: string }): RefusalCard | null {+ if (at.pathname === "/login") return null;+ return kind === "guest" ? { kind, here: at.pathname + at.search } : { kind };+}+/*** A guest tried to change something (the proxy answers a guest's change with a 401 marked* x-fuobe-guest): open "Create a free account" (GuestPrompt). An account tried to run something* (a 403 marked x-fuobe-connect-gpu): open "Connect your GPU". Watches every fetch, so the studio's- * own helpers (json() here, and the components' own) all get it. Installed once.+ * own helpers (json() here, and the components' own) all get it. The response is marked+ * (src/lib/refusals.ts): the error json() and postFile() throw for it shows no toast on top of the+ * card. Never on the sign-in page (refusalCard). Installed once.*/export function watchGuestRefusals(): void {const w = window as typeof window & { __fuobeGuestFetch?: boolean };if (w.__fuobeGuestFetch) return;w.__fuobeGuestFetch = true;const original = window.fetch.bind(window);+ const open = (res: Response, kind: RefusalCard["kind"]) => {+ if (!refusalCard(kind, window.location)) return;+ markRefusalShown(res);+ window.dispatchEvent(new Event(kind === "guest" ? GUEST_PROMPT_EVENT : CONNECT_GPU_EVENT));+ };window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {const res = await original(input, init);if (res.status === 401 && res.headers.get("x-fuobe-guest") === "1") {const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();- if (method !== "GET" && method !== "HEAD") window.dispatchEvent(new Event(GUEST_PROMPT_EVENT));+ if (method !== "GET" && method !== "HEAD") open(res, "guest");}- if (res.status === 403 && res.headers.get("x-fuobe-connect-gpu") === "1") window.dispatchEvent(new Event(CONNECT_GPU_EVENT));+ if (res.status === 403 && res.headers.get("x-fuobe-connect-gpu") === "1") open(res, "gpu");// A run the GPU pre-flight stopped (something missing on the viewer's ComfyUI): the guided fix opens with its plan.if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") {resdiff --git a/src/lib/refusals.ts b/src/lib/refusals.tsnew file mode 100644index 00000000..38972d66--- /dev/null+++ b/src/lib/refusals.ts@@ -0,0 +1,26 @@+import { toast } from "sonner";++/**+ * Refusals that open their own card (watchGuestRefusals in ./api: "Create a free account", "Connect your GPU"). The+ * error a helper throws for one is marked, so a studio shows the card alone, with no error toast on top of it.+ */+const shown = new WeakSet<Response>();++/** The watcher opened a card for this response. */+export function markRefusalShown(res: Response): void {+ shown.add(res);+}++/** The error for a failed response: marked when its refusal shows its own card. */+export function responseError(res: Response, message: string): Error {+ const e = new Error(message);+ return shown.has(res) ? Object.assign(e, { refusalShown: true }) : e;+}++/** The refusal behind this error shows its own card already: no toast on top of it. */+export const refusalShown = (e: unknown): boolean => !!(e as { refusalShown?: boolean } | null)?.refusalShown;++/** The error toast for a failed upload or run (its message, else `fallback`), unless its refusal shows its own card. */+export function toastError(e: unknown, fallback?: string): void {+ if (!refusalShown(e)) toast.error((e as Error).message || fallback);+}diff --git a/src/lib/upload.ts b/src/lib/upload.tsindex 4434e93a..3b952916 100644--- a/src/lib/upload.ts+++ b/src/lib/upload.ts@@ -1,8 +1,10 @@import type { Asset } from "@/lib/api";+import { responseError } from "@/lib/refusals";/*** Upload a file as it is (the body is the file; its type and its name in headers), so the server streams it to disk- * instead of reading a whole form into memory. Throws with the server's own message ("That clip is over 95 MB…").+ * instead of reading a whole form into memory. Throws with the server's own message ("That clip is over 95 MB…"),+ * marked when the refusal shows its own card (src/lib/refusals.ts).*/export async function postFile(file: File, signal?: AbortSignal): Promise<Asset> {const res = await fetch("/api/uploads", {@@ -12,6 +14,6 @@ export async function postFile(file: File, signal?: AbortSignal): Promise<Asset>headers: { "Content-Type": file.type || "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },});const body = (await res.json().catch(() => ({}))) as Asset & { error?: string };- if (!res.ok) throw new Error(body.error ?? `Upload failed (${res.status})`);+ if (!res.ok) throw responseError(res, body.error ?? `Upload failed (${res.status})`);return body;}diff --git a/tests/e2e/guest-prompt.mjs b/tests/e2e/guest-prompt.mjsnew file mode 100644index 00000000..bfae4dec--- /dev/null+++ b/tests/e2e/guest-prompt.mjs@@ -0,0 +1,147 @@+// A refused change shows one card, in the browser. A guest uploads a picture in Color Grading: "Create a free account+// to run this" opens alone (no error toast, no trip to the sign-in page). Its Log in and Sign up free open the sign-in+// page with the card closed, Back closes it too, and a wrong password on the sign-in page is the form's own error.+// Then an account without its GPU: "Connect your GPU" opens alone, and closes when the page changes.+// Usage: node tests/e2e/guest-prompt.mjs [appUrl] [--shots <dir>] (the app with a password and FUOBE_PUBLIC_SIGNUP=1).+// Signs up one throwaway account. Exits 1 on a failed check.+import fs from "node:fs";+import path from "node:path";+import { launch, openRoute, root } from "./_browser.mjs";++const argv = process.argv.slice(2);+const app = (argv.find((a) => !a.startsWith("--") && argv[argv.indexOf(a) - 1] !== "--shots") ?? "http://localhost:3000").replace(/\/$/, "");+const shots = argv.includes("--shots") ? argv[argv.indexOf("--shots") + 1] : undefined;+if (shots) fs.mkdirSync(shots, { recursive: true });++const failures = [];+const check = (label, ok, extra = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(76)}${extra ? ` ${extra}` : ""}`);+ if (!ok) failures.push(label);+};+const shot = (page, name) => shots && page.screenshot({ path: path.join(shots, `${name}.png`) });++const picture = path.join(root, "public/samples/grade-sample.jpg");+const GUEST_CARD = "Create a free account to run this";+const GPU_CARD = "Connect your GPU to run this";++const browser = await launch();+const contextFor = async () => {+ const context = await browser.newContext({ viewport: { width: 1280, height: 860 } });+ const page = await context.newPage();+ page.setDefaultTimeout(30_000);+ return { context, page };+};++/** The open dialogs' titles, the error toasts, and the path: what the visitor sees. */+const seen = async (page) => ({+ cards: await page.getByRole("dialog").locator("h2").allTextContents(),+ errors: await page.locator("[data-sonner-toast][data-type=error]").allTextContents(),+ path: new URL(page.url()).pathname,+});+const settled = (page) => page.waitForTimeout(1500);++/** Upload a picture through Color Grading's Image tile, and wait for the server's answer. */+async function uploadPicture(page) {+ const answered = page.waitForResponse((r) => r.url().endsWith("/api/uploads") && r.request().method() === "POST");+ const [chooser] = await Promise.all([page.waitForEvent("filechooser"), page.getByRole("button", { name: "Image: upload" }).click()]);+ await chooser.setFiles(picture);+ return answered;+}++try {+ // ---------------------------------------------------------------------------+ // A guest in Color Grading.+ {+ const { context, page } = await contextFor();+ await openRoute(page, `${app}/color-grade`);+ const res = await uploadPicture(page);+ check("the guest's upload is refused (401, marked for the card)", res.status() === 401 && res.headers()["x-fuobe-guest"] === "1", String(res.status()));+ await page.getByRole("dialog").waitFor();+ await settled(page);+ let s = await seen(page);+ await shot(page, "1-guest-upload");+ check("one card opens: Create a free account", s.cards.length === 1 && s.cards[0] === GUEST_CARD, JSON.stringify(s.cards));+ check("no error toast on top of it", s.errors.length === 0, JSON.stringify(s.errors));+ check("and no trip to the sign-in page", s.path === "/color-grade", s.path);++ await page.getByRole("dialog").getByRole("link", { name: "Log in" }).click();+ await page.waitForURL((u) => u.pathname === "/login");+ await page.getByRole("heading", { name: "Welcome back" }).waitFor();+ await settled(page);+ s = await seen(page);+ await shot(page, "2-log-in");+ check("Log in opens the sign-in page, coming back to Color Grading", new URL(page.url()).searchParams.get("next") === "/color-grade", page.url());+ check("with the card closed", s.cards.length === 0, JSON.stringify(s.cards));++ // A wrong password: the form's own error, no card.+ await page.getByPlaceholder("Email").fill("[email protected]");+ await page.getByPlaceholder("Password").fill("not the password");+ const login = page.waitForResponse((r) => r.url().endsWith("/api/auth/login"));+ await page.getByRole("button", { name: "Log in", exact: true }).click();+ const refused = await login;+ await settled(page);+ s = await seen(page);+ await shot(page, "3-wrong-password");+ check("a wrong password is refused", refused.status() === 401, String(refused.status()));+ check("and is the form's own error, with no card", s.cards.length === 0 && (await page.locator("form .text-destructive").count()) === 1, JSON.stringify(s.cards));++ // Keep browsing, upload again, then Back: the card closes with the page.+ await page.getByRole("link", { name: "Keep browsing as a guest" }).click();+ await page.waitForURL((u) => u.pathname === "/color-grade");+ await page.getByRole("button", { name: "Image: upload" }).waitFor();+ await uploadPicture(page);+ await page.getByRole("dialog").waitFor();+ await page.goBack();+ await page.waitForURL((u) => u.pathname === "/login");+ await settled(page);+ s = await seen(page);+ check("Back closes the card (no card over the sign-in page)", s.cards.length === 0, JSON.stringify(s.cards));++ // Sign up free: the sign-up form, the card closed.+ await page.goForward();+ await page.waitForURL((u) => u.pathname === "/color-grade");+ await page.getByRole("button", { name: "Image: upload" }).waitFor();+ await uploadPicture(page);+ await page.getByRole("dialog").getByRole("link", { name: "Sign up free" }).click();+ await page.getByRole("heading", { name: "Create your free account" }).waitFor();+ await settled(page);+ s = await seen(page);+ await shot(page, "4-sign-up");+ check("Sign up free opens the sign-up form with the card closed", s.path === "/login" && s.cards.length === 0, JSON.stringify(s));+ await context.close();+ }++ // ---------------------------------------------------------------------------+ // An account without its GPU: "Connect your GPU", alone, closed when the page changes.+ {+ const { context, page } = await contextFor();+ await openRoute(page, `${app}/login?signup=1`);+ await page.getByPlaceholder("Email").fill(`e2e-${Date.now()}@example.com`);+ await page.getByPlaceholder("Password (at least 8 characters)").fill("long enough password");+ await page.getByRole("button", { name: "Sign up", exact: true }).click();+ await page.waitForURL((u) => u.pathname === "/connect");+ await openRoute(page, `${app}/`);+ await page.getByRole("link", { name: "Color grading" }).first().click();+ await page.waitForURL((u) => u.pathname === "/color-grade");+ await page.getByRole("button", { name: "Image: upload" }).waitFor();+ const res = await uploadPicture(page);+ check("the account's upload is refused until it connects a GPU (403)", res.status() === 403, String(res.status()));+ await page.getByRole("dialog").waitFor();+ await settled(page);+ let s = await seen(page);+ await shot(page, "5-connect-gpu");+ check("one card opens: Connect your GPU", s.cards.length === 1 && s.cards[0] === GPU_CARD, JSON.stringify(s.cards));+ check("no error toast on top of it", s.errors.length === 0, JSON.stringify(s.errors));+ await page.goBack();+ await page.waitForURL((u) => u.pathname === "/");+ await settled(page);+ s = await seen(page);+ check("Back closes it", s.cards.length === 0, JSON.stringify(s.cards));+ await context.close();+ }+} finally {+ await browser.close();+}++console.log(failures.length ? `\n${failures.length} failed` : "\nall checks passed");+process.exit(failures.length ? 1 : 0);diff --git a/tests/guest-prompt.test.ts b/tests/guest-prompt.test.tsnew file mode 100644index 00000000..258ab5c1--- /dev/null+++ b/tests/guest-prompt.test.ts@@ -0,0 +1,139 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// A refused change shows one thing: its card (GuestPrompt: "Create a free account", "Connect your GPU"), never an error+// toast on top of it, and never a card over the sign-in page, whose own form says what went wrong.++const toasts = vi.hoisted(() => ({ error: [] as string[] }));+vi.mock("sonner", () => ({ toast: Object.assign(() => {}, { error: (m: string) => void toasts.error.push(m) }) }));++import { fileToSlot, type SlotValue } from "@/components/studio/media-slot";+import { assetUsage, CONNECT_GPU_EVENT, enhance, GUEST_PROMPT_EVENT, refusalCard, signInHref, watchGuestRefusals } from "@/lib/api";+import { CONNECT_GPU_HEADER, CONNECT_GPU_MESSAGE, GUEST_HEADER, GUEST_LIBRARY_MESSAGE, GUEST_RUN_MESSAGE } from "@/lib/guest-access";+import { refusalShown } from "@/lib/refusals";++const answer = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) =>+ new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json", ...headers } });+const guestRefusal = () => answer(401, { error: GUEST_RUN_MESSAGE }, { [GUEST_HEADER]: "1" });++let events: string[] = [];+let server: (url: string, init?: RequestInit) => Response = () => answer(200, {});++/** A page at `pathname` with the watcher installed: `window` is this global, as in a browser. */+function page(pathname: string, search = "") {+ vi.stubGlobal("window", globalThis);+ vi.stubGlobal("location", { pathname, search });+ vi.stubGlobal("dispatchEvent", (e: Event) => void events.push(e.type));+ vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => server(String(input), init));+ watchGuestRefusals();+}++const picture = () => new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], "photo.png", { type: "image/png" });++/** Upload a picture into an image tile, as the Color Grading studio's Image tile does: what the tile was given. */+async function uploadToTile(): Promise<(SlotValue | null)[]> {+ const given: (SlotValue | null)[] = [];+ await fileToSlot(picture(), (v) => void given.push(v), "image");+ return given;+}++beforeEach(() => {+ events = [];+ toasts.error.length = 0;+});+afterEach(() => {+ vi.unstubAllGlobals();+ delete (globalThis as { __fuobeGuestFetch?: boolean }).__fuobeGuestFetch;+});++describe("a guest's refused upload (Color Grading's Image tile)", () => {+ it("opens one card and shows no error toast on top of it", async () => {+ page("/color-grade");+ server = (url, init) => (url === "/api/uploads" && init?.method === "POST" ? guestRefusal() : answer(200, {}));+ const given = await uploadToTile();+ expect(events).toEqual([GUEST_PROMPT_EVENT]);+ expect(toasts.error).toEqual([]);+ // The local preview while it uploads, then the empty tile again.+ expect(given.map((v) => v && { uploading: v.uploading })).toEqual([{ uploading: true }, null]);+ });++ it("still toasts any other failure (too big, a server error)", async () => {+ page("/color-grade");+ server = () => answer(413, { error: "That picture is over 25 MB." });+ await uploadToTile();+ expect(events).toEqual([]);+ expect(toasts.error).toEqual(["That picture is over 25 MB."]);+ });++ it("an account without its GPU gets Connect your GPU alone", async () => {+ page("/color-grade");+ server = () => answer(403, { error: CONNECT_GPU_MESSAGE, code: "connect-gpu" }, { [CONNECT_GPU_HEADER]: "1" });+ await uploadToTile();+ expect(events).toEqual([CONNECT_GPU_EVENT]);+ expect(toasts.error).toEqual([]);+ });+});++describe("a guest's refused run", () => {+ it("opens the card, and the error it throws says the card shows it already", async () => {+ page("/image");+ server = () => guestRefusal();+ const e = await enhance("a red coat", "image", "t2i").catch((err: unknown) => err);+ expect(events).toEqual([GUEST_PROMPT_EVENT]);+ expect(e).toBeInstanceOf(Error);+ expect((e as Error).message).toBe(GUEST_RUN_MESSAGE);+ expect(refusalShown(e)).toBe(true);+ });++ it("a refused read opens nothing, so its own message is the one shown", async () => {+ page("/library");+ server = () => answer(401, { error: GUEST_LIBRARY_MESSAGE }, { [GUEST_HEADER]: "1" });+ const e = await assetUsage("abc").catch((err: unknown) => err);+ expect(events).toEqual([]);+ expect(refusalShown(e)).toBe(false);+ expect((e as Error).message).toBe(GUEST_LIBRARY_MESSAGE);+ });++ it("other errors are never marked as shown", () => {+ expect(refusalShown(new Error("Request failed (500)"))).toBe(false);+ expect(refusalShown(null)).toBe(false);+ expect(refusalShown("text")).toBe(false);+ });+});++describe("the sign-in page", () => {+ it("never opens a card: a refusal there keeps its own message", async () => {+ page("/login", "?next=%2Fcolor-grade");+ server = () => guestRefusal();+ await uploadToTile();+ expect(events).toEqual([]);+ expect(toasts.error).toEqual([GUEST_RUN_MESSAGE]);+ });++ it("a wrong password is the form's own error, with no card", async () => {+ page("/login");+ server = () => answer(401, { error: "Wrong email or password" });+ const res = await fetch("/api/auth/login", { method: "POST", body: "{}" });+ expect(res.status).toBe(401);+ expect(((await res.json()) as { error: string }).error).toBe("Wrong email or password");+ expect(events).toEqual([]);+ });+});++describe("refusalCard", () => {+ it("a guest's card comes back to the page it opened on", () => {+ const card = refusalCard("guest", { pathname: "/color-grade", search: "?look=noir" });+ expect(card).toEqual({ kind: "guest", here: "/color-grade?look=noir" });+ expect(card?.kind === "guest" && signInHref("login", card.here)).toBe("/login?next=%2Fcolor-grade%3Flook%3Dnoir");+ });++ it("Connect your GPU", () => {+ expect(refusalCard("gpu", { pathname: "/motions", search: "" })).toEqual({ kind: "gpu" });+ });++ it("none on the sign-in page, in any of its modes", () => {+ for (const search of ["", "?signup=1", "?owner=1", "?next=%2Fcolor-grade"]) {+ expect(refusalCard("guest", { pathname: "/login", search })).toBeNull();+ expect(refusalCard("gpu", { pathname: "/login", search })).toBeNull();+ }+ });+});