Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Storyboard: accounts make boards and films on their own GPU or key

Adarsh93c227eba987
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 9c8061a7..07f3d6b5 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -290,6 +290,14 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188
in its own runs, to open and download. "Describe my character" uses the studio's AI helper, so it isn't offered: the
account describes the character in its own words. A guest gets the sign-up card. The checks are
`src/server/account-tool-run.ts`.
+- **Storyboard.** An account makes boards the same way (`POST /api/storyboards`), and the film of a board
+ (`POST /api/storyboards/<id>/film`). Every frame, shot and join is a run of its own on the account's ComfyUI, or on
+ its own fal.ai or Replicate key on the cloud engine, with only its own pictures as look references, and a board (or
+ a film) counts once against its limits. Its boards are its own runs: the page lists them, to reopen, open and
+ download, and a film takes only its own board (another account's board, or the owner's, answers 404 "We can't
+ find that storyboard."). "From one idea" splits the story into a shot list without the studio's AI helper. One
+ sheet takes as many panels for an account as its recorded GPU test showed (`ONE_SHEET_GPU_TEST`; with none recorded
+ a one-sheet board answers 422 for an account). A guest gets the sign-up card.
- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.
A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403
(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.
diff --git a/src/app/api/storyboards/[id]/film/route.ts b/src/app/api/storyboards/[id]/film/route.ts
index 2a7f1a1c..3dbcb715 100644
--- a/src/app/api/storyboards/[id]/film/route.ts
+++ b/src/app/api/storyboards/[id]/film/route.ts
@@ -1,16 +1,50 @@
import { z } from "zod";
-import { createStoryboardFilm } from "@/server/storyboard";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createStoryboardFilm, planStoryboardFilm, startStoryboardFilm, storyboardFilmSteps, type StoryboardFilmRun } from "@/server/storyboard";
import { refusedRun } from "@/server/connect-refusal";
-const Body = z.object({ modelId: z.string().max(100).optional() });
+const Body = z.object({
+ modelId: z.string().max(100).optional(),
+ /** Client nonce: a repeat of it (a second click) gets the film the first one started. */
+ requestId: z.string().max(64).optional(),
+});
-/** Animate a storyboard's frames into clips and join them into one film. */
+/**
+ * Animate a storyboard's frames into clips and join them into one film. The owner's board as always; an account's own
+ * board only (another's, or the owner's, reads as not found), on its own GPU or key after the checks a studio run gets
+ * (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request, ctx: RouteContext<"/api/storyboards/[id]/film">) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
const parsed = Body.safeParse((await request.json().catch(() => ({}))) ?? {});
if (!parsed.success) return Response.json({ error: "Invalid request" }, { status: 400 });
- try {
- return Response.json(createStoryboardFilm((await ctx.params).id, parsed.data), { status: 201 });
- } catch (e) {
- return refusedRun(e, request);
+ const { id } = await ctx.params;
+ if (viewer.kind === "owner") {
+ try {
+ return Response.json(createStoryboardFilm(id, parsed.data), { status: 201 });
+ } catch (e) {
+ return refusedRun(e, request);
+ }
}
+ let run: StoryboardFilmRun | null = null;
+ // An account's repeat gets its own first film, never another's.
+ return onceForAccount(
+ viewer.account,
+ `storyboard-film:${id}`,
+ parsed.data.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "storyboard-film",
+ // Its frames are its own runs (planStoryboardFilm reads only its own); no other file goes in.
+ files: [],
+ plan: () => storyboardFilmSteps((run = planStoryboardFilm(id, { modelId: parsed.data.modelId }))),
+ start: () => startStoryboardFilm(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}
diff --git a/src/app/api/storyboards/estimate/route.ts b/src/app/api/storyboards/estimate/route.ts
index 685728f5..b2d1575c 100644
--- a/src/app/api/storyboards/estimate/route.ts
+++ b/src/app/api/storyboards/estimate/route.ts
@@ -1,18 +1,20 @@
+import { priceAsRun, toolViewer } from "@/server/account-tool-run";
import { estimateStoryboard, StoryboardBodySchema } from "@/server/storyboard";
-import { priceAs } from "@/server/visitor";
-/** What a board costs before it runs ("Free" on your GPU): every frame, the look's model for frame 1. */
-async function post(request: Request) {
- const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));
- if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });
- try {
- return Response.json(estimateStoryboard(parsed.data));
- } catch (e) {
- return Response.json({ error: (e as Error).message }, { status: 422 });
- }
-}
-
-/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */
+/**
+ * What a board costs before it runs ("Free" on your GPU): every frame, the look's model for frame 1. A visitor (public
+ * sign-up) gets the price of its run as it would go: an account's on its own GPU or its own key, a guest's on the open
+ * engine; never a demo (src/server/account-tool-run.ts priceAsRun).
+ */
export async function POST(request: Request) {
- return priceAs(request, () => post(request));
+ const owner = toolViewer(request).kind === "owner";
+ return priceAsRun(request, async () => {
+ const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });
+ try {
+ return Response.json(estimateStoryboard(parsed.data, { owner }));
+ } catch (e) {
+ return Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+ });
}
diff --git a/src/app/api/storyboards/route.ts b/src/app/api/storyboards/route.ts
index d938777b..65663d17 100644
--- a/src/app/api/storyboards/route.ts
+++ b/src/app/api/storyboards/route.ts
@@ -1,13 +1,44 @@
-import { createStoryboard, StoryboardBodySchema } from "@/server/storyboard";
+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { createStoryboard, planStoryboardRun, startStoryboard, StoryboardBodySchema, storyboardSteps, type StoryboardRun } from "@/server/storyboard";
import { refusedRun } from "@/server/connect-refusal";
+import { once } from "@/server/shorts-schemas";
-/** Popcorn-style storyboard: consecutive frames, each made from the previous one. */
+/**
+ * Popcorn-style storyboard: consecutive frames, each made from the previous one. The owner's board as always; an
+ * account's on its own GPU or its own fal.ai or Replicate key, with its own reference pictures, after the checks a studio
+ * run gets (src/server/account-tool-run.ts); a guest signs up first.
+ */
export async function POST(request: Request) {
+ const viewer = toolViewer(request);
+ if (viewer.kind === "guest") return guestRun();
+ if (viewer.kind === "account") {
+ const big = bodyTooBig(request);
+ if (big) return big;
+ }
const parsed = StoryboardBodySchema.safeParse(await request.json().catch(() => null));
if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => i.message).join("; ") }, { status: 400 });
- try {
- return Response.json(await createStoryboard(parsed.data), { status: 201 });
- } catch (e) {
- return refusedRun(e, request);
+ const input = parsed.data;
+ if (viewer.kind === "owner") {
+ try {
+ // A repeated requestId (a second click on Generate) gets the board the first one started.
+ return Response.json(await once("storyboard", input.requestId, () => createStoryboard(input)), { status: 201 });
+ } catch (e) {
+ return refusedRun(e, request);
+ }
}
+ let run: StoryboardRun | null = null;
+ // An account's repeat gets its own first board, never another's.
+ return onceForAccount(
+ viewer.account,
+ "storyboard",
+ input.requestId,
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "storyboard",
+ files: input.references ?? [],
+ plan: async () => storyboardSteps((run = await planStoryboardRun(input, { owner: false }))),
+ start: () => startStoryboard(run!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}
diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsx
index 50341946..885095c4 100644
--- a/src/components/storyboard-view.tsx
+++ b/src/components/storyboard-view.tsx
@@ -21,7 +21,7 @@ import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media
import { Viewer } from "@/components/studio/viewer";
import { StarterParam } from "@/components/starters/starter-param";
import { StarterSection, useStarters } from "@/components/starters/starter-section";
-import { useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsAccount, useIsVisitor, useStatus, uploadFile } from "@/lib/api";
+import { COMPUTER_KICK_EVENT, useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsAccount, useStatus, uploadFile } from "@/lib/api";
import { askDeleteForGood } from "@/components/studio/delete-for-good";
import {
MAX_FRAMES,
@@ -93,6 +93,22 @@ function useBoardTitles() {
const modelName = (g: Generation, names: Record<string, string>) => (g as Generation & { modelName?: string }).modelName ?? names[g.modelId] ?? g.modelId;
+/**
+ * Start a board or its film. Stopped by the GPU pre-flight, the guided fix opens (src/lib/api.ts watchGuestRefusals), so
+ * no error toast goes on top of it. A run started on the ComfyUI on this computer (an account's "Your GPU") is asked for by
+ * the tab that runs it at once.
+ */
+async function startRun<T>(url: string, body: unknown): Promise<T> {
+ const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ const b = (await res.json().catch(() => ({}))) as T & { error?: string; gpuWarning?: string };
+ if (res.status === 409 && res.headers.get("x-fuobe-gpu-setup") === "1") throw Object.assign(new Error(b.error ?? "This needs setting up on your GPU"), { refusalShown: true });
+ if (!res.ok) throw responseError(res, b.error ?? "Something went wrong. Please try again.");
+ window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));
+ // Its own ComfyUI seems to miss something: said, never a stop.
+ if (b.gpuWarning) toast.warning(b.gpuWarning);
+ return b;
+}
+
function RatioPill({ value, onChange }: { value: string; onChange: (v: string) => void }) {
return (
<div role="radiogroup" aria-label="Aspect ratio" className="flex flex-wrap gap-1 rounded-full bg-muted p-0.5">
@@ -360,14 +376,12 @@ function Board({
const ready = filmReady(frames, finishGaveUp);
const ratio = tileRatio(first);
const sheet = first.request.frame?.sheet;
+ // A click's film, once: a repeat of the request (a second click that got through) gets the film the first one started.
+ const filmRequest = useRef(nanoid());
const makeFilm = useMutation({
- mutationFn: async () => {
- const res = await fetch(`/api/storyboards/${first.batchId}/film`, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
- const body = await res.json();
- if (!res.ok) throw responseError(res, body.error);
- return body as { items: Generation[] };
- },
+ mutationFn: () => startRun<{ items: Generation[] }>(`/api/storyboards/${first.batchId}/film`, { requestId: filmRequest.current }),
onSuccess: (b) => {
+ filmRequest.current = nanoid();
toast.success(`Animating ${b.items.length - 1} shots, then joining them into one film`);
void qc.invalidateQueries({ queryKey: ["generations"] });
},
@@ -471,8 +485,6 @@ export function StoryboardView({
const hydrated = useHydrated();
const status = useStatus().data;
const statusReady = hydrated && !!status;
- // A storyboard doesn't run on an account's own GPU yet (only the studios' generations do), nor for a guest who signs up.
- const visitor = useIsVisitor();
const [mode, setMode] = useState<"auto" | "manual">("auto");
const [story, setStory] = useState("");
const [count, setCount] = useState(4);
@@ -492,7 +504,7 @@ export function StoryboardView({
const [sheetPicked, setSheet] = useState(false);
const sheet = sheetPicked && sheetLimit > 0;
const [open, setOpen] = useState<Generation | null>(null);
- // A ready story fills the composer (for everyone: the price shows at once, and Generate is the owner's), from its
+ // A ready story fills the composer (for everyone: the price shows at once), from its
// page's link (?starter=<id>) or its card here, then the composer comes into view.
const storyRef = useRef<HTMLTextAreaElement>(null);
const applyStarter = (id: string) => {
@@ -569,18 +581,17 @@ export function StoryboardView({
enabled: statusReady && (JSON.parse(priceKey) as { engine?: string }).engine === engine,
});
const est = estimate.data && !estimate.isError ? estimate.data : undefined;
+ // A click's board, once: a repeat of the request (a second click that got through) gets the board the first one started.
+ const boardRequest = useRef(nanoid());
const submit = useMutation({
- mutationFn: async () => {
- const res = await fetch("/api/storyboards", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(sheet ? boardBody : { ...boardBody, references: refs.filter((r) => r.ref).map((r) => r.ref) }),
- });
- const body = await res.json();
- if (!res.ok) throw responseError(res, body.error);
- return body as { scenes: string[]; batchId?: string };
- },
+ // A board for anyone: the owner's, or an account's on its own GPU or key. A guest's click opens the sign-up card.
+ mutationFn: () =>
+ startRun<{ scenes: string[]; batchId?: string }>("/api/storyboards", {
+ ...(sheet ? boardBody : { ...boardBody, references: refs.filter((r) => r.ref).map((r) => r.ref) }),
+ requestId: boardRequest.current,
+ }),
onSuccess: (b) => {
+ boardRequest.current = nanoid();
const idea = mode === "auto" ? story : scenes.find((s) => s.trim());
if (b.batchId && idea?.trim()) saveTitle(b.batchId, idea);
toast.success(sheet ? `${b.scenes.length} panels on the way, drawn together on one sheet` : `${b.scenes.length} frames on the way — each one builds on the last`);
@@ -722,9 +733,7 @@ export function StoryboardView({
{!sheet && engine === "open" && <NextScenePill value={nextScene} onChange={setNextScene} />}
<div className="ml-auto flex shrink-0 items-center gap-2">
<span className="text-right text-[12px] leading-tight tabular-nums text-muted-foreground" aria-live="polite">
- {visitor ? (
- <span className="block font-semibold text-foreground">Not available here</span>
- ) : estimate.isError ? (
+ {estimate.isError ? (
<span className="text-destructive">{(estimate.error as Error).message}</span>
) : (
<>
@@ -733,18 +742,14 @@ export function StoryboardView({
</>
)}
</span>
- <Button size="icon" className="size-10 shrink-0 rounded-full" disabled={!ready || submit.isPending || estimate.isError || visitor} onClick={() => submit.mutate()} aria-label="Generate storyboard">
+ <Button size="icon" className="size-10 shrink-0 rounded-full" disabled={!ready || submit.isPending || estimate.isError} onClick={() => submit.mutate()} aria-label="Generate storyboard">
{submit.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
</Button>
</div>
</div>
<p className="mt-2 flex items-start gap-1.5 text-[11px] text-muted-foreground">
<Sparkles className="mt-px size-3 shrink-0" />
- {mode === "auto"
- ? visitor
- ? "Fuobe splits your story into frames."
- : "Fuobe splits your story into frames."
- : "One prompt per frame. References keep the cast consistent."}
+ {mode === "auto" ? "Fuobe splits your story into frames." : "One prompt per frame. References keep the cast consistent."}
{sheet && ` One sheet draws every panel at once on MOSS-Image, then cuts it into frames.${ONE_SHEET_GPU_TEST ? "" : " Not yet tested on a GPU (shown to you as the owner)."}`}
{!sheet && lookName && ` Every frame gets the ${lookName} look's grade${aspect === "21:9" ? ", made at 16:9 and cropped to 21:9" : ""}.`}
</p>
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index a3de5d61..d6c3b972 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -274,7 +274,11 @@ export const anyoneMayReport = (method: string, pathname: string): boolean => me
* itself (src/server/account-tool-run.ts: its own files, its limits, its GPU or key for every step) and refuses a guest
* with the sign-up card. Genjutsu's "Describe my character" isn't here: it uses the studio's own AI helper.
*/
-export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/genjutsu(\/(scene|transcribe))?$/];
+export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
+ /^\/api\/genjutsu(\/(scene|transcribe))?$/,
+ // Storyboard: a board, and its film (the route reads the account's own board only).
+ /^\/api\/storyboards(\/[^/]+\/film)?$/,
+];
/**
* A tool's project routes that keep each account's projects apart (src/server/account-projects.ts): the proxy lets an
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 43896467..df5792ca 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -101,7 +101,8 @@ export interface JoinOptions {
copy?: boolean;
}
-const joinModelId = (engine: Engine, copy = false) => (engine === "open" ? (copy ? "oss-join-encoded" : "oss-join-clips") : "join-clips");
+/** The join a film of clips ends on: ComfyUI on your GPU (copied as they are when `copy`), fal in the cloud. */
+export const joinModelId = (engine: Engine, copy = false) => (engine === "open" ? (copy ? "oss-join-encoded" : "oss-join-clips") : "join-clips");
/** Join generations' clips, in order. ComfyUI joins 4 at a time, so longer films are joined in steps. */
export function joinClips(ids: string[], o: JoinOptions): Generation {
diff --git a/src/server/storyboard.ts b/src/server/storyboard.ts
index 580b5607..49fd5c0f 100644
--- a/src/server/storyboard.ts
+++ b/src/server/storyboard.ts
@@ -7,21 +7,25 @@ import {
parseScenes,
planOneSheet,
planStoryboard,
+ sheetPanelLimit,
SPLIT_SYSTEM,
STORYBOARD_NEXT_SCENE_IDS,
STORYBOARD_PARTNER_IDS,
type StoryboardLook,
type StoryboardNextScene,
type StoryboardPartner,
+ type FrameRequest,
} from "@/lib/catalog/storyboard";
import { soulLook } from "@/lib/catalog/soul";
-import type { Engine, Generation, GenerationRequest } from "@/lib/catalog/types";
+import type { Engine, Generation, GenerationRequest, ModelDef } from "@/lib/catalog/types";
import { storyboardName } from "@/lib/storyboard-board";
import { supportsOp } from "@/lib/catalog";
import { COPY_JOIN_VIDEOS } from "@/lib/catalog/clip-lengths";
-import { filmModel, joinClips } from "./chains";
+import { filmModel, joinClips, joinModelId } from "./chains";
import { llmText } from "./enhance";
import { createGenerations, listGenerations, previewChained } from "./generations";
+import { ShortsError } from "./shorts";
+import { tenantAccount } from "./tenant";
/** The body of POST /api/storyboards and /api/storyboards/estimate. */
export const StoryboardBodySchema = z.object({
@@ -42,6 +46,8 @@ export const StoryboardBodySchema = z.object({
resolution: z.string().max(10).optional(),
/** One sheet: every panel drawn on one MOSS-Image page (a layout box per panel), cropped into frames in the browser. */
sheet: z.boolean().optional(),
+ /** Client nonce: a repeat of it (a second click) gets the board the first one started. */
+ requestId: z.string().max(64).optional(),
});
export interface StoryboardRequest {
@@ -66,7 +72,10 @@ export interface StoryboardRequest {
sheet?: boolean;
}
-/** Split a story into scenes with the configured LLM, or a deterministic shot list offline. */
+/**
+ * Split a story into scenes with the configured LLM, or a deterministic shot list offline. Inside an account's run (or a
+ * visitor's price check) the install's AI helper is never asked (enhance.ts llmTextBackend): the shot list is used.
+ */
export async function splitStory(story: string, n: number): Promise<string[]> {
// A local model that decodes to a schema gets exactly n strings (the prompt asks for the same array).
const json = { name: "frames", schema: { type: "array", items: { type: "string" }, minItems: n, maxItems: n } };
@@ -82,12 +91,20 @@ function boardLook(r: Pick<StoryboardRequest, "look" | "lookStrength">): Storybo
return { id: look.id, words: look.look, ...(r.lookStrength !== undefined && { strength: r.lookStrength }) };
}
+/** Who a board is for: the owner, or a visitor (a signed-in account's run, or a price check). */
+export interface StoryboardViewer {
+ owner: boolean;
+}
+const OWNER: StoryboardViewer = { owner: true };
+
/**
* The board's requests: one sheet (one MOSS-Image page with every panel; no look, references or partner model), or a frame
- * each, every later one made from the one before.
+ * each, every later one made from the one before. One sheet is the owner's until a GPU render of it is recorded
+ * (ONE_SHEET_GPU_TEST), then everyone's up to the panels that render showed.
*/
-function boardFrames(r: StoryboardRequest, scenes: string[], batchTitle?: string) {
+function boardFrames(r: StoryboardRequest, scenes: string[], batchTitle?: string, viewer: StoryboardViewer = OWNER): FrameRequest[] {
if (r.sheet) {
+ if (!viewer.owner && !sheetPanelLimit(false)) throw new Error("One sheet isn't available yet: make the board frame by frame");
if (r.look) throw new Error("A one-sheet board has no look: make it frame by frame to use one");
return [planOneSheet({ engine: r.engine, scenes, references: r.references, style: r.style, aspectRatio: r.aspectRatio, resolution: r.resolution, batchTitle })];
}
@@ -95,10 +112,10 @@ function boardFrames(r: StoryboardRequest, scenes: string[], batchTitle?: string
}
/** What a board costs before it runs: each frame's price (frame 1 alone, the rest as chained steps), and whether it would be a demo. */
-export function estimateStoryboard(r: StoryboardRequest): { costUsd: number | null; demo: boolean; frames: number; models: string[] } {
+export function estimateStoryboard(r: StoryboardRequest, viewer: StoryboardViewer = OWNER): { costUsd: number | null; demo: boolean; frames: number; models: string[] } {
const n = Math.max(1, Math.min(MAX_FRAMES, r.scenes?.filter((s) => s.trim()).length || r.frames || 4));
const scenes = Array.from({ length: n }, (_, i) => r.scenes?.[i]?.trim() || `scene ${i + 1}`);
- const frames = boardFrames(r, scenes);
+ const frames = boardFrames(r, scenes, undefined, viewer);
let cost: number | null = 0;
let demo = false;
const models: string[] = [];
@@ -111,43 +128,75 @@ export function estimateStoryboard(r: StoryboardRequest): { costUsd: number | nu
return { costUsd: cost === null ? null : Math.round((cost as number) * 10000) / 10000, demo, frames: n, models };
}
-export async function createStoryboard(r: StoryboardRequest): Promise<{ batchId: string; scenes: string[]; items: Generation[] }> {
+/** A board planned (its story split into scenes, every frame's request made), not started yet. */
+export interface StoryboardRun {
+ scenes: string[];
+ frames: FrameRequest[];
+}
+
+/**
+ * Plan a board as it will start: nothing is made yet. An account's board is planned inside its own work
+ * (src/server/account-tool-run.ts), so every frame is checked before any starts.
+ */
+export async function planStoryboardRun(r: StoryboardRequest, viewer: StoryboardViewer = OWNER): Promise<StoryboardRun> {
const n = Math.max(1, Math.min(MAX_FRAMES, r.scenes?.length || r.frames || 4));
const scenes = r.scenes?.length ? r.scenes.slice(0, MAX_FRAMES).map((s) => s.trim()).filter(Boolean) : await splitStory(r.story ?? "", n);
if (!scenes.length) throw new Error("Describe the story or write at least one scene");
- const batchId = nanoid(10);
// The board is named after the user's idea on every device (the Library's stack title too).
const batchTitle = storyboardName(r.scenes?.length ? undefined : r.story, scenes);
- const frames = boardFrames(r, scenes, batchTitle);
+ return { scenes, frames: boardFrames(r, scenes, batchTitle, viewer) };
+}
+
+/** A planned board's frames as the steps a run checks: frame 1 alone, each later frame waiting for the one before. */
+export const storyboardSteps = (run: StoryboardRun): { request: GenerationRequest; deps: number }[] => run.frames.map((request, i) => ({ request, deps: i ? 1 : 0 }));
+
+/** Start a planned board: frame 1 first, every later frame made from the one before. */
+export function startStoryboard(run: StoryboardRun): { batchId: string; scenes: string[]; items: Generation[] } {
+ const batchId = nanoid(10);
const items: Generation[] = [];
let previous: string | undefined;
- for (const request of frames) {
+ for (const request of run.frames) {
const [g] = createGenerations(request, { batchId, dependsOn: previous });
items.push(g);
previous = g.id;
}
- return { batchId, scenes, items };
+ return { batchId, scenes: run.scenes, items };
+}
+
+/** Plan and start a board (the owner's; an account's goes through src/server/account-tool-run.ts). */
+export async function createStoryboard(r: StoryboardRequest): Promise<{ batchId: string; scenes: string[]; items: Generation[] }> {
+ return startStoryboard(await planStoryboardRun(r));
+}
+
+/** A board's film planned: each shot's request and the frames it waits for, then the join. Nothing is made yet. */
+export interface StoryboardFilmRun {
+ filmBatch: string;
+ model: ModelDef;
+ batchTitle: string;
+ aspectRatio?: string;
+ shots: { request: GenerationRequest & { batchTitle?: string }; after: string | string[] }[];
}
/**
- * Turn a storyboard into a film: each frame is animated toward the next one (start + end frame
- * when the model can, else from its frame alone), then the clips are joined. Frames still
- * rendering are waited for.
+ * Plan a storyboard's film: each frame is animated toward the next one (start + end frame when the model can, else from
+ * its frame alone), then the clips are joined. Frames still rendering are waited for. Only the asker's own board: inside
+ * an account's work its own frames (another's board, or the owner's, reads as not found); outside it, the owner's.
*/
-export function createStoryboardFilm(batchId: string, opts: { modelId?: string } = {}): { batchId: string; items: Generation[] } {
- const frames = listGenerations({ batchId, feature: "storyboard", limit: 50 }).sort((a, b) => (a.request.frame?.index ?? 0) - (b.request.frame?.index ?? 0));
+export function planStoryboardFilm(batchId: string, opts: { modelId?: string } = {}): StoryboardFilmRun {
+ const account = tenantAccount();
+ const frames = listGenerations({ batchId, feature: "storyboard", limit: 50, ...(account && { account }) }).sort((a, b) => (a.request.frame?.index ?? 0) - (b.request.frame?.index ?? 0));
+ if (account && !frames.length) throw new ShortsError("We can't find that storyboard.", 404);
if (frames.length < 2) throw new Error("A film needs at least two frames");
const broken = frames.find((f) => f.status === "failed" || f.status === "canceled");
if (broken) throw new Error(`Frame ${(broken.request.frame?.index ?? 0) + 1} didn't render — retry it first`);
const model = filmModel(frames[0].engine, opts.modelId);
const flf = supportsOp(model, "flf2v");
- const filmBatch = `${batchId}-film`;
// Boards made before the server stored a name fall back to the first scene.
const batchTitle = (frames[0].request as { batchTitle?: string }).batchTitle?.trim() || frames[0].request.frame?.scene || "Storyboard film";
// A 21:9 board in a look is made at 16:9 and cropped after (frame.crop): its film is 21:9, like its frames.
const aspectRatio = frames[0].request.frame?.crop ?? frames[0].request.params?.aspectRatio;
const n = frames.length;
- const clips = frames.map((f, i) => {
+ const shots = frames.map((f, i) => {
const next = flf ? frames[i + 1] : undefined;
const scene = f.request.frame?.scene ?? f.request.prompt ?? "";
const request: GenerationRequest & { batchTitle?: string } = {
@@ -159,20 +208,52 @@ export function createStoryboardFilm(batchId: string, opts: { modelId?: string }
step: { label: `Shot ${i + 1} of ${n}`, index: i, of: n },
batchTitle,
};
- return createGenerations(request, { batchId: filmBatch, dependsOn: next ? [f.id, next.id] : f.id })[0];
+ return { request, after: next ? [f.id, next.id] : f.id };
});
+ return { filmBatch: `${batchId}-film`, model, batchTitle, aspectRatio, shots };
+}
+
+/** How many clips one join takes (ComfyUI's join takes 4 at a time unless it copies the clips as they are). */
+const joinTakes = (run: StoryboardFilmRun) => (run.model.engine === "open" && !COPY_JOIN_VIDEOS.has(run.model.id) ? 4 : 24);
+
+/**
+ * A planned film as the steps a run checks: each shot (waiting for its frames), then the join waiting for the shots (once,
+ * at the most clips one join takes: a longer film's joins run the same way).
+ */
+export function storyboardFilmSteps(run: StoryboardFilmRun): { request: GenerationRequest; deps: number }[] {
+ const takes = Math.min(run.shots.length, joinTakes(run));
+ const join: GenerationRequest = {
+ feature: "storyboard-film",
+ modelId: joinModelId(run.model.engine, COPY_JOIN_VIDEOS.has(run.model.id)),
+ op: "concat",
+ prompt: run.batchTitle,
+ params: { aspectRatio: run.aspectRatio, resolution: run.model.defaults?.resolution },
+ chain: Array.from({ length: takes }, () => ({ slot: "videos" as const })),
+ };
+ return [...run.shots.map((s) => ({ request: s.request, deps: Array.isArray(s.after) ? s.after.length : 1 })), { request: join, deps: takes }];
+}
+
+/** Start a planned film: the shots, then the join. */
+export function startStoryboardFilm(run: StoryboardFilmRun): { batchId: string; items: Generation[] } {
+ const n = run.shots.length;
+ const clips = run.shots.map((s) => createGenerations(s.request, { batchId: run.filmBatch, dependsOn: s.after })[0]);
const film = joinClips(
clips.map((c) => c.id),
{
- engine: model.engine,
+ engine: run.model.engine,
feature: "storyboard-film",
- batchId: filmBatch,
- title: batchTitle,
- aspectRatio,
- resolution: model.defaults?.resolution,
- copy: COPY_JOIN_VIDEOS.has(model.id),
+ batchId: run.filmBatch,
+ title: run.batchTitle,
+ aspectRatio: run.aspectRatio,
+ resolution: run.model.defaults?.resolution,
+ copy: COPY_JOIN_VIDEOS.has(run.model.id),
step: { label: `Film · ${n} shots`, index: n, of: n + 1 },
},
);
- return { batchId: filmBatch, items: [film, ...clips] };
+ return { batchId: run.filmBatch, items: [film, ...clips] };
+}
+
+/** Turn a storyboard into a film (the owner's; an account's goes through src/server/account-tool-run.ts). */
+export function createStoryboardFilm(batchId: string, opts: { modelId?: string } = {}): { batchId: string; items: Generation[] } {
+ return startStoryboardFilm(planStoryboardFilm(batchId, opts));
}
diff --git a/tests/account-storyboard.test.ts b/tests/account-storyboard.test.ts
new file mode 100644
index 00000000..aa710714
--- /dev/null
+++ b/tests/account-storyboard.test.ts
@@ -0,0 +1,400 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { NextRequest } from "next/server";
+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";
+import { tempDir } from "./helpers/temp-dir";
+
+/**
+ * Storyboard for a signed-in account (public sign-up): its boards and their films run on the account's own ComfyUI (a
+ * stand-in here) through the same generations every studio run makes, with only its own reference pictures, and they
+ * stay its own: it reopens them from its own runs, and another account or the owner's boards are never reached. A
+ * guest gets the sign-up card. Splitting a story never asks the install's AI helper for an account.
+ */
+const dir = tempDir("fuobe-account-storyboard-");
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";
+process.env.FUOBE_PUBLIC_SIGNUP = "1";
+delete process.env.FUOBE_PASSWORD;
+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;
+delete process.env.FUOBE_HOSTED_RUNS;
+delete process.env.ANTHROPIC_API_KEY;
+globalThis.__fuobeTestDiskFree = 1e13;
+
+// Plain fetch is the install's own ComfyUI ("owner-comfy.test") or its AI helper, a local model ("owner-llm.test"):
+// recorded ("METHOD url"), so a test sees that nothing reached them.
+const LLM_SCENES = ["Wide shot: the crew boards the night train", "Close-up: a gloved hand lifts the case", "Wide shot: the train vanishes into the tunnel"];
+const realFetch = globalThis.fetch;
+const fetched: string[] = [];
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = new URL(String(input instanceof Request ? input.url : input));
+ if (url.hostname === "127.0.0.1") return realFetch(input, init);
+ fetched.push(`${(init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase()} ${url}`);
+ if (url.host === "owner-llm.test:11434") {
+ if (url.pathname === "/api/tags") return Response.json({ models: [{ name: "qwen3:8b", model: "qwen3:8b" }] });
+ if (url.pathname === "/api/chat") return Response.json({ model: "qwen3:8b", message: { role: "assistant", content: JSON.stringify(LLM_SCENES) }, done: true });
+ }
+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });
+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });
+ return Response.json({});
+}) as typeof fetch;
+
+const auth = await import("@/server/auth");
+const boardsRoute = await import("@/app/api/storyboards/route");
+const filmRoute = await import("@/app/api/storyboards/[id]/film/route");
+const estimateRoute = await import("@/app/api/storyboards/estimate/route");
+const uploadsRoute = await import("@/app/api/uploads/route");
+const gpuRoute = await import("@/app/api/account/gpu/route");
+const { proxy } = await import("@/proxy");
+const access = await import("@/lib/guest-access");
+const { getGeneration, listGenerations } = await import("@/server/generations");
+const { db } = await import("@/server/db");
+const { resetRates } = await import("@/server/rate");
+const { clearAccountLoras } = await import("@/server/account-loras");
+const { saveFile } = await import("@/server/storage");
+const { setSetting } = await import("@/server/settings");
+const { splitStory } = await import("@/server/storyboard");
+const { heuristicScenes, ONE_SHEET_GPU_TEST } = await import("@/lib/catalog/storyboard");
+const { ACCOUNT_LIMITS } = await import("@/server/account-files");
+
+let fake: FakeComfy;
+let a = "";
+let b = "";
+const cookies: Record<string, string> = {};
+beforeAll(async () => {
+ fake = await startFakeComfy({ loras: [], delayMs: 0, output: "image" });
+ globalThis.__fuobeTestGpuPort = fake.port;
+ auth.setPassword("install password");
+ for (const [k, email] of [
+ ["a", "[email protected]"],
+ ["b", "[email protected]"],
+ ["c", "[email protected]"],
+ ] as const) {
+ const id = auth.createAccount(email, "long enough").id;
+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;
+ if (k === "a") a = id;
+ if (k === "b") b = id;
+ }
+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;
+ // The install's own AI helper is a local model: the owner's boards would ask it to split a story.
+ setSetting("enhanceProvider", "local");
+ setSetting("ollamaUrl", "http://owner-llm.test:11434");
+ // A and B link their own ComfyUI; C has neither a GPU nor a key.
+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);
+});
+afterAll(async () => {
+ globalThis.fetch = realFetch;
+ globalThis.__fuobeTestGpuPort = undefined;
+ globalThis.__fuobeTestDiskFree = undefined;
+ await fake.close();
+});
+beforeEach(() => {
+ resetRates();
+ for (const id of [a, b]) clearAccountLoras(id);
+});
+
+function json(url: string, method: string, body: unknown, who?: string): Request {
+ const text = JSON.stringify(body);
+ return new Request(`http://localhost:3000${url}`, {
+ method,
+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },
+ body: text,
+ });
+}
+
+const viaProxy = (url: string, method = "GET", who?: string) =>
+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));
+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";
+
+async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {
+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));
+ expect(r.status, await r.clone().text()).toBe(201);
+ return ((await r.json()) as { url: string }).url;
+}
+
+/** Tick the runner until the row is done (or the time is up). */
+async function settle(id: string, ms = 30_000) {
+ const end = Date.now() + ms;
+ for (;;) {
+ await globalThis.__fuobeRunner?.tick();
+ const g = getGeneration(id, { includeDeleted: true });
+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+/** What GET /api/generations?features=storyboard,storyboard-film lists for an account (the route lists its own runs only). */
+const mine = (who: "a" | "b") => listGenerations({ features: ["storyboard", "storyboard-film"], account: who === "a" ? a : b });
+
+/**
+ * What reached the install's own GPU or AI helper. Its own checks aside: whether its ComfyUI and its local model are up
+ * (they send nothing of anyone's run).
+ */
+const reached = () => fetched.filter((f) => !f.endsWith("/system_stats") && f !== "GET http://owner-llm.test:11434/api/tags");
+
+const rows = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+
+/** Send a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */
+async function send(call: () => Promise<Response>): Promise<Response> {
+ let r = await call();
+ if (r.status === 409) {
+ const j = (await r.clone().json()) as { code: string; fix?: { items: { file: string }[] } };
+ expect(j.code).toBe("comfy_missing_model");
+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix!.items.map((i) => i.file)];
+ for (const id of [a, b]) clearAccountLoras(id);
+ r = await call();
+ }
+ return r;
+}
+const board = (body: unknown, who: string) => send(() => boardsRoute.POST(json("/api/storyboards", "POST", body, who)));
+const film = (id: string, body: unknown, who?: string) => send(() => filmRoute.POST(json(`/api/storyboards/${id}/film`, "POST", body, who), { params: Promise.resolve({ id }) }));
+
+const SCENES = ["A model in an emerald gown on a palace stair at midnight", "She runs to a vintage car under the lamps", "The car on a coast road at dawn"];
+
+describe("the proxy opens Storyboard's runs to accounts, and keeps the sign-up card for guests", () => {
+ it("a guest gets the sign-up card on a board and a film; the price check stays open", async () => {
+ for (const p of ["/api/storyboards", "/api/storyboards/b1/film"]) {
+ const r = viaProxy(p, "POST");
+ expect(r.status, p).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");
+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);
+ }
+ expect(passed(viaProxy("/api/storyboards/estimate", "POST"))).toBe(true);
+ });
+
+ it("an account with its own GPU reaches the routes; one with neither a GPU nor a key is asked to connect one", async () => {
+ for (const p of ["/api/storyboards", "/api/storyboards/b1/film"]) {
+ expect(passed(viaProxy(p, "POST", "a")), p).toBe(true);
+ const r = viaProxy(p, "POST", "c");
+ expect(r.status, p).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect((await r.json()).code).toBe("connect-gpu");
+ }
+ expect(access.ownGpuRun("GET", "/api/storyboards")).toBe(false);
+ expect(access.ownGpuRun("POST", "/api/storyboards/b1")).toBe(false);
+ expect(access.ownGpuRun("POST", "/api/storyboards/b1/film/x")).toBe(false);
+ // Reading the owner's boards stays closed (an account's own boards are its own runs).
+ expect(viaProxy("/api/storyboards", "GET", "a").status).toBe(403);
+ });
+
+ it("the routes refuse a guest themselves", async () => {
+ const r = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES }));
+ expect(r.status).toBe(401);
+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");
+ const f = await filmRoute.POST(json("/api/storyboards/b1/film", "POST", {}), { params: Promise.resolve({ id: "b1" }) });
+ expect(f.status).toBe(401);
+ expect(f.headers.get(access.GUEST_HEADER)).toBe("1");
+ });
+});
+
+describe("an account makes, reopens and films its own storyboards on its own ComfyUI", () => {
+ let ref = "";
+ let batch = "";
+ let frames: string[] = [];
+ beforeAll(async () => {
+ ref = await upload("a", TINY_PNG, "image/png", "look.png");
+ });
+
+ it("prices a board for its own GPU, never as a demo", async () => {
+ const r = await estimateRoute.POST(json("/api/storyboards/estimate", "POST", { engine: "open", scenes: SCENES, references: [ref] }, "a"));
+ expect(r.status, await r.clone().text()).toBe(200);
+ const e = (await r.json()) as { demo: boolean; costUsd: number | null; frames: number };
+ expect(e.demo).toBe(false);
+ expect(e.frames).toBe(3);
+ });
+
+ it("makes a board with its own look reference: every frame is its own, on its ComfyUI, and its results are its own files", async () => {
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await board({ engine: "open", scenes: SCENES, references: [ref], aspectRatio: "16:9", requestId: "board-request-1" }, "a");
+ expect(r.status, await r.clone().text()).toBe(201);
+ const body = (await r.json()) as { batchId: string; scenes: string[]; items: { id: string; batchId: string | null }[] };
+ batch = body.batchId;
+ frames = body.items.map((g) => g.id);
+ expect(body.scenes).toEqual(SCENES);
+ expect(frames).toHaveLength(3);
+ expect(new Set(body.items.map((g) => g.batchId))).toEqual(new Set([batch]));
+ for (const id of frames) expect(getGeneration(id)!.request.account, id).toBe(a);
+ // Its look reference went into frame 1.
+ expect(getGeneration(frames[0])!.request.inputs?.images).toEqual([ref]);
+ for (const id of frames) {
+ const g = await settle(id);
+ expect(g?.status, g?.error ?? "").toBe("succeeded");
+ }
+ // Every frame went to its own ComfyUI; nothing reached the install's GPU or AI helper.
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(3);
+ expect(reached()).toEqual([]);
+ const out = getGeneration(frames[2])!.outputs[0];
+ expect(out.url).toMatch(/^\/api\/files\/outputs\//);
+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(a);
+ // It reopens the board from its own runs, and opens (and downloads) each frame.
+ expect(mine("a").map((g) => g.id)).toEqual(expect.arrayContaining(frames));
+ expect(passed(viaProxy(out.url, "GET", "a"))).toBe(true);
+ expect(passed(viaProxy(`/api/generations/${frames[0]}`, "GET", "a"))).toBe(true);
+ });
+
+ it("a second click with the same request id gets the same board", async () => {
+ const n = rows();
+ const r = await board({ engine: "open", scenes: SCENES, references: [ref], aspectRatio: "16:9", requestId: "board-request-1" }, "a");
+ expect(r.status).toBe(201);
+ expect(((await r.json()) as { batchId: string }).batchId).toBe(batch);
+ expect(rows()).toBe(n);
+ });
+
+ it("splits a story without the install's AI helper", async () => {
+ // The owner's split asks the install's own model.
+ fetched.length = 0;
+ expect(await splitStory("a heist on a night train", 3)).toEqual(LLM_SCENES);
+ expect(fetched).toContain("POST http://owner-llm.test:11434/api/chat");
+ // An account's board is split offline: the same shot list, and nothing reaches the install's AI helper.
+ fetched.length = 0;
+ const story = "A model in a silver coat crosses a night market, then steps onto a rooftop";
+ const r = await board({ engine: "open", story, frames: 3, aspectRatio: "16:9" }, "a");
+ expect(r.status, await r.clone().text()).toBe(201);
+ const body = (await r.json()) as { scenes: string[]; items: { id: string }[] };
+ expect(body.scenes).toEqual(heuristicScenes(story, 3));
+ expect(reached()).toEqual([]);
+ // Named after the idea it was made from.
+ expect((getGeneration(body.items[0].id)!.request as { batchTitle?: string }).batchTitle).toBe(story);
+ for (const g of body.items) await settle(g.id);
+ });
+
+ it("makes the board's film: every shot and the join are its own, on its ComfyUI", async () => {
+ fake.opts.output = "video";
+ fake.log.length = 0;
+ fetched.length = 0;
+ const r = await film(batch, { requestId: "film-request-1" }, "a");
+ expect(r.status, await r.clone().text()).toBe(201);
+ const body = (await r.json()) as { batchId: string; items: { id: string; op: string }[] };
+ expect(body.batchId).toBe(`${batch}-film`);
+ const join = body.items[0];
+ expect(join.op).toBe("concat");
+ expect(body.items).toHaveLength(4);
+ for (const g of body.items) expect(getGeneration(g.id)!.request.account, g.id).toBe(a);
+ const done = await settle(join.id);
+ expect(done?.status, done?.error ?? "").toBe("succeeded");
+ for (const g of body.items) expect(getGeneration(g.id)!.status, g.id).toBe("succeeded");
+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(body.items.length);
+ expect(reached()).toEqual([]);
+ const out = done!.outputs[0];
+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(a);
+ expect(passed(viaProxy(out.url, "GET", "a"))).toBe(true);
+ expect(mine("a").map((g) => g.id)).toContain(join.id);
+ // The same click again: the same film.
+ const again = await film(batch, { requestId: "film-request-1" }, "a");
+ expect(((await again.json()) as { items: { id: string }[] }).items[0].id).toBe(join.id);
+ fake.opts.output = "image";
+ });
+
+ it("another account never sees, opens, films or reuses its boards", async () => {
+ const out = getGeneration(frames[0])!.outputs[0].url;
+ expect(viaProxy(`/api/generations/${frames[0]}`, "GET", "b").status).toBe(403);
+ expect(viaProxy(`/api/generations/${frames[0]}`, "DELETE", "b").status).toBe(403);
+ expect(viaProxy(out, "GET", "b").status).toBe(403);
+ expect(viaProxy(out, "GET").status).toBe(401);
+ expect(mine("b")).toEqual([]);
+ // A film of A's board: not found for B, the same as a board that doesn't exist, and nothing is made.
+ const n = rows();
+ for (const id of [batch, "no-such-board"]) {
+ const r = await filmRoute.POST(json(`/api/storyboards/${id}/film`, "POST", {}, "b"), { params: Promise.resolve({ id }) });
+ expect(r.status, id).toBe(404);
+ expect((await r.json()).error).toBe("We can't find that storyboard.");
+ }
+ expect(rows()).toBe(n);
+ // A's picture as B's look reference: refused before anything is planned or sent.
+ fake.log.length = 0;
+ const r = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, references: [ref] }, "b"));
+ expect(r.status).toBe(403);
+ expect((await r.json()).code).toBe("input-not-yours");
+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);
+ // A's frame as B's reference: the same.
+ const frame = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, references: [out] }, "b"));
+ expect(frame.status).toBe(403);
+ // The same request id from B is B's own board, never A's.
+ const own = await upload("b", TINY_PNG, "image/png", "b.png");
+ const bRun = await board({ engine: "open", scenes: SCENES.slice(0, 2), references: [own], requestId: "board-request-1" }, "b");
+ expect(bRun.status, await bRun.clone().text()).toBe(201);
+ const bBody = (await bRun.json()) as { batchId: string; items: { id: string }[] };
+ expect(bBody.batchId).not.toBe(batch);
+ for (const g of bBody.items) expect(getGeneration(g.id)!.request.account).toBe(b);
+ for (const g of bBody.items) await settle(g.id);
+ expect(mine("a").some((g) => g.batchId === bBody.batchId)).toBe(false);
+ });
+
+ it("the owner's storyboards and files are never reachable", async () => {
+ const ownerPic = saveFile({ data: TINY_PNG, contentType: "image/png", source: "upload", name: "owner.png" }).url;
+ const t = Date.now();
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, batch_id, request_json, outputs_json, created_at, updated_at) VALUES (?, 'storyboard', 'oss-qwen-image-21', 'open', 'comfyui', 't2i', 'image', 'succeeded', 'owner-board', ?, ?, ?, ?)",
+ );
+ for (const i of [0, 1]) add.run(`owner-frame-${i}`, JSON.stringify({ feature: "storyboard", modelId: "oss-qwen-image-21", frame: { scene: `owner scene ${i}`, index: i, of: 2 } }), JSON.stringify([{ url: ownerPic, kind: "image" }]), t + i, t + i);
+ // Not in its list, closed through the proxy, and its film is not found (nothing is made).
+ expect(mine("a").map((g) => g.id)).not.toContain("owner-frame-0");
+ expect(viaProxy("/api/generations/owner-frame-0", "GET", "a").status).toBe(403);
+ expect(viaProxy(ownerPic, "GET", "a").status).toBe(403);
+ const n = rows();
+ const r = await filmRoute.POST(json("/api/storyboards/owner-board/film", "POST", {}, "a"), { params: Promise.resolve({ id: "owner-board" }) });
+ expect(r.status).toBe(404);
+ expect(rows()).toBe(n);
+ // The owner's picture as its look reference: refused like any file that isn't its own; a link never goes in.
+ const reuse = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, references: [ownerPic] }, "a"));
+ expect(reuse.status).toBe(403);
+ expect((await reuse.json()).code).toBe("input-not-yours");
+ const link = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES, references: ["https://example.com/a.png"] }, "a"));
+ expect(link.status).toBe(400);
+ });
+
+ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {
+ const n = rows();
+ const r = await boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES }, "c"));
+ expect(r.status).toBe(403);
+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");
+ expect((await r.json()).code).toBe("connect-gpu");
+ expect(rows()).toBe(n);
+ });
+
+ it("keeps the account's limits: runs going at once, and a body over what a run may weigh", async () => {
+ const now = Date.now();
+ const add = db().prepare(
+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'storyboard', 'oss-qwen-image-21', 'open', 'comfyui', 't2i', 'image', 'queued', ?, '[]', ?, ?)",
+ );
+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-${i}`, JSON.stringify({ feature: "storyboard", modelId: "oss-qwen-image-21", account: a }), now, now);
+ for (const call of [
+ () => boardsRoute.POST(json("/api/storyboards", "POST", { engine: "open", scenes: SCENES }, "a")),
+ () => filmRoute.POST(json(`/api/storyboards/${batch}/film`, "POST", {}, "a"), { params: Promise.resolve({ id: batch }) }),
+ ]) {
+ const r = await call();
+ expect(r.status).toBe(429);
+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);
+ }
+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-%'").run();
+ const big = new Request("http://localhost:3000/api/storyboards", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });
+ expect((await boardsRoute.POST(big)).status).toBe(413);
+ });
+
+ it("offers One sheet to an account only once its GPU test is recorded", async () => {
+ const body = { engine: "open", sheet: true, scenes: SCENES, aspectRatio: "16:9" };
+ const priced = await estimateRoute.POST(json("/api/storyboards/estimate", "POST", body, "a"));
+ const n = rows();
+ const r = await board(body, "a");
+ if (ONE_SHEET_GPU_TEST) {
+ expect(priced.status).toBe(200);
+ expect(r.status, await r.clone().text()).toBe(201);
+ // One picture with every panel, its own, drawn on its own ComfyUI.
+ const { items } = (await r.json()) as { items: { id: string }[] };
+ expect(items).toHaveLength(1);
+ const g = getGeneration(items[0].id)!;
+ expect(g.request.account).toBe(a);
+ expect(g.request.frame?.sheet?.panels).toHaveLength(3);
+ const done = await settle(g.id);
+ expect(done?.status, done?.error ?? "").toBe("succeeded");
+ expect(done!.provider).toBe("comfyui");
+ } else {
+ expect(priced.status).toBe(422);
+ expect(r.status).toBe(422);
+ expect((await r.json()).error).toMatch(/One sheet isn't available yet/);
+ expect(rows()).toBe(n);
+ // The owner's price check still has it.
+ const owner = await estimateRoute.POST(json("/api/storyboards/estimate", "POST", body, "owner"));
+ expect(owner.status, await owner.clone().text()).toBe(200);
+ }
+ });
+});
diff --git a/tests/e2e/storyboard-accounts-live.mjs b/tests/e2e/storyboard-accounts-live.mjs
new file mode 100644
index 00000000..7b8ae122
--- /dev/null
+++ b/tests/e2e/storyboard-accounts-live.mjs
@@ -0,0 +1,73 @@
+// Storyboard for visitors, in a browser (a studio with a password and public sign-up, fuobe.com by default): a guest and a
+// signed-in account see a price, never "Not available here", and Generate is on. A guest's Generate and Look ref open the
+// sign-up card; an account with neither a GPU nor a key of its own gets the card that connects one. The account is a
+// throwaway one this script makes and deletes. No board is made (that needs the account's own GPU or key).
+// Usage: node tests/e2e/storyboard-accounts-live.mjs [appUrl] [--shots <dir>] Exits 1 on a failed check.
+import fs from "node:fs";
+import path from "node:path";
+import crypto from "node:crypto";
+import { launch } from "./_browser.mjs";
+
+const argv = process.argv.slice(2);
+const flag = (k) => (argv.includes(k) ? argv[argv.indexOf(k) + 1] : undefined);
+const app = (argv.find((a, i) => !a.startsWith("--") && argv[i - 1] !== "--shots") ?? "https://fuobe.com").replace(/\/$/, "");
+const shots = flag("--shots");
+if (shots) fs.mkdirSync(shots, { recursive: true });
+
+const failures = [];
+const check = (label, ok, extra = "") => {
+ console.log(`${ok ? "ok " : "FAIL"} ${label.padEnd(72)}${extra ? ` ${extra}` : ""}`);
+ if (!ok) failures.push(label);
+};
+
+const browser = await launch();
+const email = `storyboard-ui-${crypto.randomBytes(5).toString("hex")}@example.com`;
+const password = crypto.randomBytes(18).toString("base64url");
+let signedUp = false;
+const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
+try {
+ const page = await context.newPage();
+ const card = (title) => page.getByRole("dialog").getByText(title);
+ const closeCard = async () => {
+ await page.keyboard.press("Escape");
+ await page.waitForTimeout(500);
+ };
+ const look = async (who, cards) => {
+ await page.goto(`${app}/storyboard`, { waitUntil: "load", timeout: 60_000 });
+ await page.waitForTimeout(3000);
+ await page.getByLabel("Your story").fill("A model in an emerald gown slips out of a palace ball at midnight and drives a vintage car to the sea");
+ await page.waitForTimeout(2500);
+ check(`${who}: the price never says "Not available here"`, (await page.getByText("Not available here").count()) === 0);
+ const generate = page.getByRole("button", { name: "Generate storyboard" });
+ check(`${who}: Generate is on`, await generate.isEnabled());
+ if (shots) await page.screenshot({ path: path.join(shots, `storyboard-${who}.png`), fullPage: false });
+ // Generate: the card that says what running it takes, and nothing else.
+ await generate.click();
+ await page.waitForTimeout(2500);
+ check(`${who}: Generate opens "${cards.run}"`, (await card(cards.run).count()) > 0);
+ if (shots) await page.screenshot({ path: path.join(shots, `storyboard-${who}-generate.png`) });
+ await closeCard();
+ // Look ref: asked first, before the file chooser.
+ await page.getByRole("button", { name: "Look ref: upload" }).click();
+ await page.waitForTimeout(1500);
+ check(`${who}: Look ref opens "${cards.upload}"`, (await card(cards.upload).count()) > 0);
+ if (shots) await page.screenshot({ path: path.join(shots, `storyboard-${who}-look-ref.png`) });
+ await closeCard();
+ };
+ await look("guest", { run: "Create a free account to run this", upload: "Create a free account to add your own files" });
+
+ // A throwaway account (signed in in this browser), then the same page.
+ const res = await page.request.post(`${app}/api/auth/signup`, { data: { email, password }, headers: { origin: app } });
+ signedUp = res.ok();
+ check("signed up a throwaway account", signedUp, String(res.status()));
+ await look("account", { run: /^(Connect your GPU|Add an API key) to run this$/, upload: /^Connect your GPU (or add a key )?to add your own files$/ });
+} finally {
+ if (signedUp) {
+ const page = context.pages()[0];
+ const del = await page.request.delete(`${app}/api/auth/me`, { data: { password }, headers: { origin: app } });
+ console.log(`deleted the throwaway account: ${del.status()}`);
+ }
+ await browser.close();
+}
+console.log(failures.length ? `${failures.length} failed` : "all ok");
+process.exit(failures.length ? 1 : 0);