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 (Popcorn): up to 8 consistent frames, each made from the previous one

Claude1a3fc417a674
diff --git a/package.json b/package.json
index ec9db518..d41fa54f 100644
--- a/package.json
+++ b/package.json
@@ -4,6 +4,7 @@
"private": true,
"scripts": {
"dev": "next dev",
+ "dev:clean": "rm -rf .next && next dev",
"build": "next build",
"start": "next start",
"lint": "eslint",
diff --git a/src/app/(studio)/layout.tsx b/src/app/(studio)/layout.tsx
index dc1cccea..381172e9 100644
--- a/src/app/(studio)/layout.tsx
+++ b/src/app/(studio)/layout.tsx
@@ -8,7 +8,7 @@ export default function StudioLayout({ children }: { children: React.ReactNode }
style={{ "--sidebar-width": "15.5rem", "--sidebar-width-icon": "3.25rem" } as React.CSSProperties}
>
<AppSidebar />
- <SidebarInset className="min-h-svh md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-l-[0.5px] md:border-t-[0.5px] md:shadow-[-2px_0_6px_rgba(0,0,0,.02)] md:peer-data-[variant=inset]:m-0 md:peer-data-[variant=inset]:mt-2 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:rounded-tl-xl">
+ <SidebarInset className="min-h-svh min-w-0 md:m-0 md:mt-2 md:rounded-none md:rounded-tl-xl md:border-l-[0.5px] md:border-t-[0.5px] md:shadow-[-2px_0_6px_rgba(0,0,0,.02)] md:peer-data-[variant=inset]:m-0 md:peer-data-[variant=inset]:mt-2 md:peer-data-[variant=inset]:rounded-none md:peer-data-[variant=inset]:rounded-tl-xl">
{children}
</SidebarInset>
<GlobalShortcuts />
diff --git a/src/app/(studio)/storyboard/page.tsx b/src/app/(studio)/storyboard/page.tsx
new file mode 100644
index 00000000..c7a387f5
--- /dev/null
+++ b/src/app/(studio)/storyboard/page.tsx
@@ -0,0 +1,8 @@
+import type { Metadata } from "next";
+import { StoryboardView } from "@/components/storyboard-view";
+
+export const metadata: Metadata = { title: "Storyboard" };
+
+export default function Page() {
+ return <StoryboardView />;
+}
diff --git a/src/app/api/storyboards/route.ts b/src/app/api/storyboards/route.ts
new file mode 100644
index 00000000..ccfd9bd1
--- /dev/null
+++ b/src/app/api/storyboards/route.ts
@@ -0,0 +1,24 @@
+import { z } from "zod";
+import { createStoryboard } from "@/server/storyboard";
+
+const Body = z.object({
+ engine: z.enum(["cloud", "open"]),
+ scenes: z.array(z.string().max(1000)).max(8).optional(),
+ story: z.string().max(4000).optional(),
+ frames: z.number().int().min(1).max(8).optional(),
+ references: z.array(z.string().startsWith("/api/files/")).max(4).optional(),
+ style: z.string().max(500).optional(),
+ aspectRatio: z.string().max(10).optional(),
+ resolution: z.string().max(10).optional(),
+});
+
+/** Popcorn-style storyboard: consecutive frames, each made from the previous one. */
+export async function POST(request: Request) {
+ const parsed = Body.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 Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index e6bec1dc..6de12b69 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -6,6 +6,7 @@ import { useTheme } from "next-themes";
import { Suspense } from "react";
import {
AtSign,
+ GalleryHorizontal,
Layers,
Crop,
FastForward,
@@ -64,6 +65,7 @@ const NAV = [
{ href: "/color-grade", label: "Color grading", icon: SlidersHorizontal },
{ href: "/motions", label: "Camera motions", icon: Film },
{ href: "/effects", label: "Effects", icon: Sparkles },
+ { href: "/storyboard", label: "Storyboard", icon: GalleryHorizontal },
{ href: "/apps", label: "Apps", icon: LayoutGrid },
],
},
diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsx
new file mode 100644
index 00000000..c6d8fecd
--- /dev/null
+++ b/src/components/storyboard-view.tsx
@@ -0,0 +1,303 @@
+"use client";
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { ArrowUp, Clapperboard, ImagePlus, Loader2, Minus, Plus, Sparkles, Trash2, Wand2, X } from "lucide-react";
+import Link from "next/link";
+import { useMemo, useState } from "react";
+import { nanoid } from "nanoid";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { Skeleton } from "@/components/ui/skeleton";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { FailedTile, MediaThumb, PendingTile, tileRatio } from "@/components/studio/feed";
+import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { Viewer } from "@/components/studio/viewer";
+import { useCreateGeneration, useEngine, useGenerationActions, useGenerations } from "@/lib/api";
+import { getModel } from "@/lib/catalog";
+import { MAX_FRAMES, STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
+import type { Generation } from "@/lib/catalog/types";
+import { timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+
+const ASPECTS = ["16:9", "9:16", "1:1", "4:3", "3:4", "21:9"];
+
+function RatioPill({ value, onChange }: { value: string; onChange: (v: string) => void }) {
+ return (
+ <div className="flex flex-wrap gap-1 rounded-full bg-muted p-0.5">
+ {ASPECTS.map((a) => (
+ <button
+ key={a}
+ onClick={() => onChange(a)}
+ className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground transition", value === a && "bg-background text-foreground shadow-soft")}
+ >
+ {a}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function Board({ frames, onOpen }: { frames: Generation[]; onOpen: (g: Generation) => void }) {
+ const { remove } = useGenerationActions();
+ const create = useCreateGeneration();
+ const first = frames[0];
+ const done = frames.filter((f) => f.status === "succeeded").length;
+ const ratio = tileRatio(first);
+ return (
+ <section className="animate-fade-up space-y-3">
+ <header className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <h3 className="line-clamp-1 font-heading text-[19px] leading-snug">{first.request.frame?.scene ?? first.request.prompt}</h3>
+ <p className="text-[12px] text-muted-foreground">
+ {frames.length} frames · {done === frames.length ? "done" : `${done}/${frames.length} ready`} · {getModel(first.modelId)?.name} · {timeAgo(first.createdAt)}
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground hover:text-destructive"
+ onClick={() => {
+ frames.forEach((f) => void remove(f));
+ toast("Storyboard deleted");
+ }}
+ >
+ <Trash2 /> Delete
+ </Button>
+ </header>
+ <div className="scrollbar-none -mx-1 flex gap-3 overflow-x-auto px-1 pb-1">
+ {frames.map((g, i) => {
+ const o = g.outputs[0];
+ return (
+ <figure key={g.id} className="w-[min(70vw,280px)] shrink-0 space-y-1.5">
+ <div className="relative overflow-hidden rounded-xl" style={{ aspectRatio: ratio }}>
+ {g.status === "succeeded" && o ? (
+ <button onClick={() => onOpen(g)} className="group/tile block size-full cursor-zoom-in bg-muted">
+ <MediaThumb output={o} />
+ <span className="absolute inset-x-0 bottom-0 flex justify-end gap-1 bg-gradient-to-t from-black/60 to-transparent p-2 pt-8 opacity-0 transition-opacity group-hover/tile:opacity-100">
+ <Link
+ href={`/video?image=${encodeURIComponent(o.url)}&prompt=${encodeURIComponent(g.request.frame?.scene ?? "")}`}
+ onClick={(e) => e.stopPropagation()}
+ className="inline-flex h-7 items-center gap-1 rounded-full bg-white/20 px-2.5 text-[12px] font-medium text-white backdrop-blur hover:bg-white/30"
+ >
+ <Clapperboard className="size-3.5" /> Animate
+ </Link>
+ <Link
+ href={`/edit?image=${encodeURIComponent(o.url)}`}
+ onClick={(e) => e.stopPropagation()}
+ className="inline-flex h-7 items-center gap-1 rounded-full bg-white/20 px-2.5 text-[12px] font-medium text-white backdrop-blur hover:bg-white/30"
+ >
+ <Wand2 className="size-3.5" /> Edit
+ </Link>
+ </span>
+ </button>
+ ) : g.status === "failed" || g.status === "canceled" ? (
+ <FailedTile g={g} ratio={ratio} onRetry={() => create.mutate(g.request, { onError: (e) => toast.error((e as Error).message) })} />
+ ) : (
+ <PendingTile g={g} ratio={ratio} />
+ )}
+ <span className="pointer-events-none absolute top-2 left-2 grid size-6 place-items-center rounded-full bg-background/90 font-mono text-[11px] font-semibold shadow-soft">
+ {i + 1}
+ </span>
+ </div>
+ <figcaption className="line-clamp-2 px-0.5 text-[12px] leading-snug text-muted-foreground">{g.request.frame?.scene}</figcaption>
+ </figure>
+ );
+ })}
+ </div>
+ </section>
+ );
+}
+
+export function StoryboardView() {
+ const qc = useQueryClient();
+ const [engine, setEngine] = useEngine();
+ const [mode, setMode] = useState<"auto" | "manual">("auto");
+ const [story, setStory] = useState("");
+ const [count, setCount] = useState(4);
+ const [scenes, setScenes] = useState<string[]>(["", "", ""]);
+ const [style, setStyle] = useState("");
+ const [aspect, setAspect] = useState("16:9");
+ const [refs, setRefs] = useState<SlotValue[]>([]);
+ const [open, setOpen] = useState<Generation | null>(null);
+ const feed = useGenerations({ features: ["storyboard"], limit: 160 });
+
+ const boards = useMemo(() => {
+ const by = new Map<string, Generation[]>();
+ for (const g of feed.data ?? []) {
+ const k = g.batchId ?? g.id;
+ by.set(k, [...(by.get(k) ?? []), g]);
+ }
+ return [...by.values()].map((fs) => fs.sort((a, b) => (a.request.frame?.index ?? 0) - (b.request.frame?.index ?? 0)));
+ }, [feed.data]);
+ const flat = boards.flatMap((b) => b.filter((g) => g.status === "succeeded" && g.outputs[0]));
+ const pos = open ? flat.findIndex((g) => g.id === open.id) : -1;
+
+ const m = STORYBOARD_MODELS[engine];
+ const submit = useMutation({
+ mutationFn: async () => {
+ const res = await fetch("/api/storyboards", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ engine,
+ ...(mode === "auto" ? { story, frames: count } : { scenes: scenes.filter((s) => s.trim()) }),
+ references: refs.filter((r) => r.ref).map((r) => r.ref),
+ style: style || undefined,
+ aspectRatio: aspect,
+ }),
+ });
+ const body = await res.json();
+ if (!res.ok) throw new Error(body.error);
+ return body as { scenes: string[] };
+ },
+ onSuccess: (b) => {
+ toast.success(`${b.scenes.length} frames on the way — each one builds on the last`);
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
+
+ const ready = (mode === "auto" ? story.trim().length > 3 : scenes.some((s) => s.trim())) && !refs.some((r) => r.uploading);
+ const addRef = (f: File) => {
+ const id = nanoid(6);
+ void fileToSlot(f, (v) =>
+ setRefs((rs) => {
+ if (!v) return rs.filter((r) => r.id !== id);
+ return rs.some((r) => r.id === id) ? rs.map((r) => (r.id === id ? { ...v, id } : r)) : [...rs, { ...v, id }];
+ }),
+ );
+ };
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <header className="sticky top-0 z-20 flex h-14 items-center gap-2 bg-background/85 px-3 backdrop-blur sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="font-heading text-[22px] leading-none">Storyboard</h1>
+ <div className="ml-auto">
+ <EngineSwitch value={engine} onChange={setEngine} />
+ </div>
+ </header>
+ <main className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 space-y-10 px-3 pb-16 sm:px-6">
+ <div className="mx-auto max-w-[820px] pt-6 text-center">
+ <h2 className="font-heading text-display text-balance">Tell it frame by frame</h2>
+ <p className="mt-2 text-[13px] text-muted-foreground">
+ Up to {MAX_FRAMES} consistent frames — each one is made from the previous frame, so faces, wardrobe and light carry through. Runs on{" "}
+ {getModel(m.next)?.name}.
+ </p>
+ <div className="mt-6 rounded-composer border bg-background p-3 text-left shadow-soft focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">
+ <div className="mb-2 flex items-center gap-1 rounded-full bg-muted p-0.5 text-[13px] font-medium sm:w-fit">
+ {(["auto", "manual"] as const).map((k) => (
+ <button key={k} onClick={() => setMode(k)} className={cn("h-8 flex-1 rounded-full px-4 text-muted-foreground transition", mode === k && "bg-background text-foreground shadow-soft")}>
+ {k === "auto" ? "From one idea" : "Scene by scene"}
+ </button>
+ ))}
+ </div>
+ {mode === "auto" ? (
+ <textarea
+ value={story}
+ onChange={(e) => setStory(e.target.value)}
+ rows={2}
+ placeholder="The whole story in a sentence or two — e.g. “a lighthouse keeper finds a glowing bottle and follows its map into the sea”"
+ className="field-sizing-content max-h-52 min-h-16 w-full resize-none bg-transparent px-2 py-1.5 text-base leading-relaxed outline-none placeholder:text-subtle-foreground"
+ />
+ ) : (
+ <div className="space-y-1.5">
+ {scenes.map((s, i) => (
+ <div key={i} className="flex items-start gap-2 rounded-xl border bg-muted/40 p-1.5 pl-2.5">
+ <span className="mt-1.5 font-mono text-[12px] font-semibold text-muted-foreground">{i + 1}</span>
+ <textarea
+ value={s}
+ onChange={(e) => setScenes((xs) => xs.map((x, j) => (j === i ? e.target.value : x)))}
+ rows={1}
+ placeholder={i ? "What happens next?" : "Opening frame — who, where, what"}
+ className="field-sizing-content max-h-28 min-h-8 flex-1 resize-none bg-transparent py-1 text-[14px] outline-none placeholder:text-subtle-foreground"
+ />
+ <button
+ onClick={() => setScenes((xs) => (xs.length > 1 ? xs.filter((_, j) => j !== i) : xs))}
+ className="grid size-7 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent"
+ aria-label={`Remove frame ${i + 1}`}
+ >
+ <X className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ {scenes.length < MAX_FRAMES && (
+ <button onClick={() => setScenes((xs) => [...xs, ""])} className="inline-flex items-center gap-1 px-1 text-[12px] font-medium text-brand-text hover:underline">
+ <Plus className="size-3" /> Add frame
+ </button>
+ )}
+ </div>
+ )}
+ <input
+ value={style}
+ onChange={(e) => setStyle(e.target.value)}
+ placeholder="Look (optional) — e.g. “35mm film, moody teal night, anamorphic”"
+ className="mt-2 h-9 w-full rounded-lg border bg-background px-2.5 text-[13px] outline-none focus:border-primary"
+ />
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {refs.map((r) => (
+ <div key={r.id} className="relative size-12 overflow-hidden rounded-lg border bg-muted">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={r.preview} alt="" className="size-full object-cover" />
+ {r.uploading && <Loader2 className="absolute inset-0 m-auto size-4 animate-spin" />}
+ <button onClick={() => setRefs((rs) => rs.filter((x) => x.id !== r.id))} className="absolute top-0.5 right-0.5 grid size-4 place-items-center rounded-full bg-foreground/80 text-background" aria-label="Remove reference">
+ <X className="size-2.5" />
+ </button>
+ </div>
+ ))}
+ {refs.length < 4 && <MediaSlot label="Character / look" kind="image" value={null} onChange={(v) => v && setRefs((rs) => [...rs, { ...v, id: nanoid(6) }])} onFile={addRef} />}
+ {mode === "auto" && (
+ <div className="flex items-center gap-1 rounded-full bg-secondary px-1 py-0.5 text-[13px] font-medium">
+ <button onClick={() => setCount((c) => Math.max(2, c - 1))} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label="Fewer frames">
+ <Minus className="size-3.5" />
+ </button>
+ <span className="w-16 text-center tabular-nums">{count} frames</span>
+ <button onClick={() => setCount((c) => Math.min(MAX_FRAMES, c + 1))} className="grid size-7 place-items-center rounded-full hover:bg-accent" aria-label="More frames">
+ <Plus className="size-3.5" />
+ </button>
+ </div>
+ )}
+ <RatioPill value={aspect} onChange={setAspect} />
+ <Button size="icon" className="ml-auto size-10 rounded-full" disabled={!ready || submit.isPending} onClick={() => submit.mutate()} aria-label="Generate storyboard">
+ {submit.isPending ? <Loader2 className="animate-spin" /> : <ArrowUp />}
+ </Button>
+ </div>
+ <p className="mt-2 flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ <Sparkles className="size-3" />
+ {mode === "auto" ? "Your story is split into frames by the prompt LLM (Settings → Prompt enhancement), or a shot list when none is set." : "One prompt per frame. References keep the cast consistent."}
+ </p>
+ </div>
+ </div>
+
+ {feed.isLoading ? (
+ <div className="flex gap-3">
+ {[0, 1, 2].map((i) => (
+ <Skeleton key={i} className="h-40 w-64 rounded-xl" />
+ ))}
+ </div>
+ ) : boards.length ? (
+ <div className="space-y-10">
+ {boards.map((b) => (
+ <Board key={b[0].batchId ?? b[0].id} frames={b} onOpen={setOpen} />
+ ))}
+ </div>
+ ) : (
+ <div className="grid place-items-center rounded-xl border border-dashed py-14 text-center text-muted-foreground">
+ <ImagePlus className="size-6" />
+ <p className="mt-2 text-[14px]">Your storyboards appear here.</p>
+ </div>
+ )}
+ </main>
+ {open && pos >= 0 && (
+ <Viewer
+ generation={flat[pos]}
+ index={0}
+ onClose={() => setOpen(null)}
+ onPrev={pos > 0 ? () => setOpen(flat[pos - 1]) : undefined}
+ onNext={pos < flat.length - 1 ? () => setOpen(flat[pos + 1]) : undefined}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index c4a52bf5..da0041a9 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -101,13 +101,13 @@ export function MediaThumb({ output, className, autoPlay }: { output: OutputFile
return <img src={output.url} alt="" loading="lazy" className={cn("size-full object-cover", className)} />;
}
-function tileRatio(g: Generation): number {
+export function tileRatio(g: Generation): number {
const ar = g.request.params?.aspectRatio ?? getModel(g.modelId)?.defaults?.aspectRatio;
if (g.kind === "audio") return 1.6;
return ratioValue(ar && ar !== "auto" ? ar : undefined, g.kind === "video" ? 16 / 9 : 1);
}
-function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
+export function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
const { cancel } = useGenerationActions();
const pct = g.progress != null ? Math.round(g.progress * 100) : null;
const label = g.status === "queued" ? (g.message ?? "Queued") : (g.message ?? "Generating…");
@@ -140,7 +140,7 @@ function PendingTile({ g, ratio }: { g: Generation; ratio: number }) {
);
}
-function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
+export function FailedTile({ g, ratio, onRetry }: { g: Generation; ratio: number; onRetry: () => void }) {
return (
<div className="flex h-full flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.8) }}>
<div className="min-h-0 space-y-1 overflow-hidden">
diff --git a/src/lib/catalog/storyboard.ts b/src/lib/catalog/storyboard.ts
new file mode 100644
index 00000000..fd6b808b
--- /dev/null
+++ b/src/lib/catalog/storyboard.ts
@@ -0,0 +1,65 @@
+/**
+ * Storyboards (Higgsfield Popcorn): up to 8 consistent frames. Frame 1 is made from the
+ * references (or text alone); every later frame is an edit of the previous frame, so faces,
+ * wardrobe, location and grade carry through.
+ */
+import type { Engine } from "./types";
+
+export const MAX_FRAMES = 8;
+
+/** Which models make the first frame and the follow-ups on each engine. */
+export const STORYBOARD_MODELS: Record<Engine, { first: string; firstWithRefs: string; next: string; chainFrom: "first" | "last" }> = {
+ cloud: { first: "nano-banana-pro", firstWithRefs: "nano-banana-pro", next: "nano-banana-pro", chainFrom: "last" },
+ // Qwen-Image-Edit + the next-scene LoRA takes the previous panel as image 1 and the character as image 2.
+ open: { first: "oss-z-image-turbo", firstWithRefs: "oss-qwen-edit", next: "oss-qwen-next-scene", chainFrom: "first" },
+};
+
+const SHOTS = [
+ "establishing wide shot",
+ "medium shot",
+ "close-up",
+ "over-the-shoulder shot",
+ "low-angle shot",
+ "detail insert shot",
+ "tracking shot",
+ "wide closing shot",
+];
+
+/** Offline split of one story idea into n scenes (used when no LLM is configured). */
+export function heuristicScenes(story: string, n: number): string[] {
+ const s = story.trim().replace(/[.\s]+$/, "");
+ return Array.from({ length: n }, (_, i) => `${SHOTS[i % SHOTS.length]}: ${s} — beat ${i + 1} of ${n}`);
+}
+
+/** Parse an LLM answer into n scene lines (JSON array or numbered list). */
+export function parseScenes(text: string, n: number): string[] | null {
+ const json = /\[[\s\S]*\]/.exec(text)?.[0];
+ if (json) {
+ try {
+ const arr = (JSON.parse(json) as unknown[]).map((x) => String(typeof x === "object" && x ? ((x as { scene?: string }).scene ?? JSON.stringify(x)) : x).trim()).filter(Boolean);
+ if (arr.length >= Math.min(2, n)) return arr.slice(0, n);
+ } catch {}
+ }
+ const lines = text
+ .split("\n")
+ .map((l) => l.replace(/^\s*(\d+[.)]|[-*•])\s*/, "").trim())
+ .filter((l) => l.length > 8);
+ return lines.length >= Math.min(2, n) ? lines.slice(0, n) : null;
+}
+
+export const SPLIT_SYSTEM = `You are a storyboard artist. Split the user's story into the requested number of consecutive frames of one film.
+Each frame is one sentence describing a single still image: shot type, what the characters do, where, the light.
+Keep the same characters, wardrobe and location style across frames. Return ONLY a JSON array of strings.`;
+
+/** Prompt for one frame. `refs` = number of reference images sent before/after the previous frame. */
+export function framePrompt(scene: string, index: number, opts: { refs: number; chainFrom: "first" | "last"; style?: string }): string {
+ const s = scene.trim().replace(/[.\s]+$/, "");
+ const style = opts.style?.trim() ? ` Style: ${opts.style.trim().replace(/[.\s]+$/, "")}.` : "";
+ if (index === 0) {
+ const refs = opts.refs ? ` Use the reference image${opts.refs > 1 ? "s" : ""} for the characters and look.` : "";
+ return `Frame 1 of a storyboard: ${s}.${refs}${style} Cinematic still, consistent production design.`;
+ }
+ if (opts.chainFrom === "first") return `Next Scene: ${s}.${style}`;
+ const prev = opts.refs + 1;
+ return `Next frame of the same storyboard: ${s}. Image ${prev} is the previous frame — continue from it with the same characters, faces, wardrobe, props, location style, lighting and color grade, like consecutive shots of one film.${style}`;
+}
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index de45d585..609a9e7b 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -310,6 +310,10 @@ export interface GenerationRequest {
presetOptions?: Record<string, string>;
/** Server-side only: LoRAs added by @element mentions (trained identities). */
loras?: LoraRef[];
+ /** Chained jobs: where the previous job's image goes among `inputs.images`. */
+ chainFrom?: "first" | "last";
+ /** Storyboard frame this request makes (shown under the frame). */
+ frame?: { scene: string; index: number; of: number };
}
/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */
diff --git a/src/server/db.ts b/src/server/db.ts
index bc12c252..bdacf3e8 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -84,6 +84,8 @@ const MIGRATIONS: string[] = [
completed_at INTEGER
);
CREATE INDEX IF NOT EXISTS trainings_element ON trainings(element_id);`,
+ // Chained jobs (storyboard frames wait for the previous frame).
+ `ALTER TABLE generations ADD COLUMN depends_on TEXT;`,
];
declare global {
diff --git a/src/server/enhance.ts b/src/server/enhance.ts
index 069aa5b1..838cd29a 100644
--- a/src/server/enhance.ts
+++ b/src/server/enhance.ts
@@ -28,7 +28,7 @@ function instruction(prompt: string, kind: MediaKind, op: Operation): string {
return `Rewrite this as ${what}:\n\n${prompt}`;
}
-async function viaClaude(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
+async function viaClaude(system: string, user: string): Promise<string | null> {
const client = new Anthropic({ apiKey: getSetting("anthropicKey") });
const res = await client.beta.messages.create({
model: "claude-opus-5-5",
@@ -36,19 +36,19 @@ async function viaClaude(prompt: string, kind: MediaKind, op: Operation): Promis
output_config: { effort: "low" },
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default",
- system: SYSTEM,
- messages: [{ role: "user", content: instruction(prompt, kind, op) }],
+ system,
+ messages: [{ role: "user", content: user }],
} as Parameters<typeof client.beta.messages.create>[0] & { fallbacks: string });
- if (!("content" in res) || res.stop_reason === "refusal") return prompt;
+ if (!("content" in res) || res.stop_reason === "refusal") return null;
const text = res.content
.filter((b): b is Anthropic.Beta.BetaTextBlock => b.type === "text")
.map((b) => b.text)
.join("")
.trim();
- return text || prompt;
+ return text || null;
}
-async function viaOllama(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
+async function viaOllama(system: string, user: string): Promise<string | null> {
const res = await fetch(`${getSetting("ollamaUrl").replace(/\/+$/, "")}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -57,15 +57,28 @@ async function viaOllama(prompt: string, kind: MediaKind, op: Operation): Promis
stream: false,
think: false,
messages: [
- { role: "system", content: SYSTEM },
- { role: "user", content: instruction(prompt, kind, op) },
+ { role: "system", content: system },
+ { role: "user", content: user },
],
}),
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) throw new Error(`ollama ${res.status}`);
const j = (await res.json()) as { message?: { content?: string } };
- return j.message?.content?.replace(/<think>[\s\S]*?<\/think>/g, "").trim() || prompt;
+ return j.message?.content?.replace(/<think>[\s\S]*?<\/think>/g, "").trim() || null;
+}
+
+/**
+ * One-shot text from whichever LLM this install allows: Claude (when a key is set, and never
+ * on "open source only" installs unless picked explicitly), else a local Ollama. Null when none.
+ */
+export async function llmText(system: string, user: string): Promise<string | null> {
+ const choice = getSetting("enhanceProvider");
+ if (choice === "none") return null;
+ const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));
+ if (useClaude) return viaClaude(system, user).catch(() => null);
+ if (choice === "ollama" || choice === "auto") return viaOllama(system, user).catch(() => null);
+ return null;
}
/** Deterministic fallback so the toggle always does something useful offline. */
@@ -81,17 +94,5 @@ export function heuristicEnhance(prompt: string, kind: MediaKind, op: Operation)
}
export async function enhancePrompt(prompt: string, kind: MediaKind, op: Operation): Promise<string> {
- const choice = getSetting("enhanceProvider");
- // "Open source only" installs never call a paid API unless Claude was picked explicitly.
- const useClaude = choice === "anthropic" || (choice === "auto" && engineMode() !== "open" && !!getSetting("anthropicKey"));
- if (useClaude) return viaClaude(prompt, kind, op);
- if (choice === "ollama") return viaOllama(prompt, kind, op);
- if (choice === "auto") {
- try {
- return await viaOllama(prompt, kind, op);
- } catch {
- /* no local LLM running */
- }
- }
- return heuristicEnhance(prompt, kind, op);
+ return (await llmText(SYSTEM, instruction(prompt, kind, op))) ?? heuristicEnhance(prompt, kind, op);
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 1647a982..2dba54db 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -50,6 +50,7 @@ interface Row {
created_at: number;
updated_at: number;
completed_at: number | null;
+ depends_on: string | null;
}
function toGeneration(r: Row): Generation {
@@ -165,7 +166,8 @@ export function chooseRoute(candidates: ModelRoute[]): { route: ModelRoute; demo
// ---------------------------------------------------------------------------
// Create
-export function createGenerations(original: GenerationRequest): Generation[] {
+/** Resolve mentions and drawings, plan, enforce the engine mode and pick a provider route. */
+function prepare(original: GenerationRequest) {
// @element mentions become reference images / LoRAs; the stored request keeps the mentions for "Reuse".
const model = getModel(original.modelId);
const req = model ? stripMotionPaths(applySketch(applyMentions(original, model, listElements()).request, model).request, model) : original;
@@ -180,11 +182,25 @@ export function createGenerations(original: GenerationRequest): Generation[] {
}
const { route, demo } = chooseRoute(routesFor(plan.model, plan.op));
const providerId: ProviderId = demo ? "mock" : route.provider;
- const batchId = plan.jobs > 1 ? nanoid(10) : null;
+ return { req, plan, route, demo, providerId, cost: demo ? 0 : estimateCost(plan.model, plan.params, 1) };
+}
+
+export interface CreateOptions {
+ /** Group several requests (storyboard frames) into one batch. */
+ batchId?: string;
+ /** Wait for this generation and feed its first output in as an image (see GenerationRequest.chainFrom). */
+ dependsOn?: string;
+}
+
+export function createGenerations(original: GenerationRequest, opts: CreateOptions = {}): Generation[] {
+ // A dependent job can't be planned until its input exists; it's validated without it, then launched by the runner.
+ const p = opts.dependsOn ? prepare(withChainPlaceholder(original)) : prepare(original);
+ const { req, plan, route, demo, providerId, cost } = p;
+ const jobs = opts.dependsOn ? 1 : plan.jobs;
+ const batchId = opts.batchId ?? (jobs > 1 ? nanoid(10) : null);
const now = Date.now();
- const cost = estimateCost(plan.model, plan.params, 1);
const created: Generation[] = [];
- for (let i = 0; i < plan.jobs; i++) {
+ for (let i = 0; i < jobs; i++) {
const id = nanoid(12);
const row: Row = {
id,
@@ -198,7 +214,7 @@ export function createGenerations(original: GenerationRequest): Generation[] {
kind: OPERATION_OUTPUT[plan.op],
status: "queued",
progress: null,
- message: demo ? "Demo mode — no provider connected" : "Submitting",
+ message: opts.dependsOn ? "Waits for the previous frame" : demo ? "Demo mode — no provider connected" : "Submitting",
prompt: plan.prompt,
request_json: JSON.stringify(original),
provider_input_json: null,
@@ -206,11 +222,12 @@ export function createGenerations(original: GenerationRequest): Generation[] {
external_meta_json: null,
outputs_json: "[]",
error: null,
- cost_usd: demo ? 0 : cost,
+ cost_usd: cost,
favorite: 0,
created_at: now + i,
updated_at: now + i,
completed_at: null,
+ depends_on: opts.dependsOn ?? null,
};
db()
.prepare(
@@ -220,12 +237,62 @@ export function createGenerations(original: GenerationRequest): Generation[] {
)
.run(row);
created.push(toGeneration(row));
- void submit(id, route, providerId, plan, req, i);
+ if (!opts.dependsOn) void submit(id, route, providerId, plan, req, i);
}
ensureRunner();
return created;
}
+/** Validate a chained request as if the previous frame were already there. */
+function withChainPlaceholder(req: GenerationRequest): GenerationRequest {
+ return withChainInput(req, "/api/files/placeholder.png");
+}
+
+function withChainInput(req: GenerationRequest, url: string): GenerationRequest {
+ const images = req.inputs?.images ?? [];
+ return { ...req, inputs: { ...req.inputs, images: req.chainFrom === "first" ? [url, ...images] : [...images, url] } };
+}
+
+/** Launch dependent jobs whose input finished; fail the ones whose input failed. */
+const launching = new Set<string>();
+async function advanceDependents(): Promise<void> {
+ const rows = db()
+ .prepare("SELECT * FROM generations WHERE status = 'queued' AND external_id IS NULL AND depends_on IS NOT NULL ORDER BY created_at ASC LIMIT 50")
+ .all() as Row[];
+ for (const r of rows) {
+ if (launching.has(r.id)) continue;
+ const dep = db().prepare("SELECT status, outputs_json FROM generations WHERE id = ?").get(r.depends_on) as Pick<Row, "status" | "outputs_json"> | undefined;
+ if (!dep || dep.status === "failed" || dep.status === "canceled") {
+ update(r.id, { status: "failed", error: "The previous frame didn't finish", message: null, completed_at: Date.now() });
+ continue;
+ }
+ if (dep.status !== "succeeded") continue;
+ const url = (JSON.parse(dep.outputs_json) as OutputFile[]).find((o) => o.kind === "image")?.url;
+ if (!url) {
+ update(r.id, { status: "failed", error: "The previous frame has no image", message: null, completed_at: Date.now() });
+ continue;
+ }
+ launching.add(r.id);
+ try {
+ const original = withChainInput(JSON.parse(r.request_json) as GenerationRequest, url);
+ const { req, plan, route, providerId, cost, demo } = prepare(original);
+ update(r.id, {
+ provider: providerId,
+ op: plan.op,
+ prompt: plan.prompt,
+ cost_usd: cost,
+ request_json: JSON.stringify(original),
+ message: demo ? "Demo mode — no provider connected" : "Submitting",
+ });
+ await submit(r.id, route, providerId, plan, req, 0);
+ } catch (e) {
+ update(r.id, { status: "failed", error: (e as Error).message, message: null, completed_at: Date.now() });
+ } finally {
+ launching.delete(r.id);
+ }
+ }
+}
+
async function submit(
id: string,
route: ModelRoute,
@@ -303,7 +370,7 @@ export function ensureRunner(): void {
// Jobs that never got an external id (server died mid-submit) can't be recovered.
db()
.prepare(
- "UPDATE generations SET status = 'failed', error = 'Interrupted before it reached the provider', completed_at = ? WHERE status IN ('queued','running') AND external_id IS NULL AND created_at < ?",
+ "UPDATE generations SET status = 'failed', error = 'Interrupted before it reached the provider', completed_at = ? WHERE status IN ('queued','running') AND external_id IS NULL AND depends_on IS NULL AND created_at < ?",
)
.run(Date.now(), Date.now() - 2 * 60 * 1000);
}
@@ -319,6 +386,7 @@ async function tick(): Promise<void> {
await Promise.all([
...active.map((r) => pollOne(r).catch((e) => update(r.id, { message: `Poll error: ${(e as Error).message}` }))),
pollTrainings().catch(() => {}),
+ advanceDependents().catch(() => {}),
]);
} finally {
state.busy = false;
@@ -452,6 +520,7 @@ export function recordLocalGeneration(input: {
created_at: now,
updated_at: now,
completed_at: now,
+ depends_on: null,
};
db()
.prepare(`INSERT INTO generations (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
diff --git a/src/server/storyboard.ts b/src/server/storyboard.ts
new file mode 100644
index 00000000..c578a414
--- /dev/null
+++ b/src/server/storyboard.ts
@@ -0,0 +1,57 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { framePrompt, heuristicScenes, MAX_FRAMES, parseScenes, SPLIT_SYSTEM, STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
+import type { Engine, Generation } from "@/lib/catalog/types";
+import { llmText } from "./enhance";
+import { createGenerations } from "./generations";
+
+export interface StoryboardRequest {
+ engine: Engine;
+ /** Manual: one prompt per frame. */
+ scenes?: string[];
+ /** Auto: one story, split into `frames`. */
+ story?: string;
+ frames?: number;
+ references?: string[];
+ style?: string;
+ aspectRatio?: string;
+ resolution?: string;
+}
+
+/** Split a story into scenes with the configured LLM, or a deterministic shot list offline. */
+export async function splitStory(story: string, n: number): Promise<string[]> {
+ const text = await llmText(SPLIT_SYSTEM, `Story: ${story}\nFrames: ${n}`);
+ return (text && parseScenes(text, n)) || heuristicScenes(story, n);
+}
+
+export async function createStoryboard(r: StoryboardRequest): Promise<{ batchId: string; scenes: string[]; items: Generation[] }> {
+ 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 refs = (r.references ?? []).slice(0, 4);
+ const m = STORYBOARD_MODELS[r.engine];
+ const batchId = nanoid(10);
+ const params = { aspectRatio: r.aspectRatio, resolution: r.resolution, numOutputs: 1 };
+ const items: Generation[] = [];
+ let previous: string | undefined;
+ scenes.forEach((scene, i) => {
+ const first = i === 0;
+ // The open next-scene workflow takes the previous panel plus one character reference.
+ const frameRefs = first ? refs : m.chainFrom === "first" ? refs.slice(0, 1) : refs;
+ const [g] = createGenerations(
+ {
+ feature: "storyboard",
+ modelId: first ? (refs.length ? m.firstWithRefs : m.first) : m.next,
+ prompt: framePrompt(scene, i, { refs: frameRefs.length, chainFrom: m.chainFrom, style: r.style }),
+ inputs: frameRefs.length ? { images: frameRefs } : undefined,
+ params,
+ chainFrom: first ? undefined : m.chainFrom,
+ frame: { scene, index: i, of: scenes.length },
+ },
+ { batchId, dependsOn: previous },
+ );
+ items.push(g);
+ previous = g.id;
+ });
+ return { batchId, scenes, items };
+}
diff --git a/tests/storyboard.test.ts b/tests/storyboard.test.ts
new file mode 100644
index 00000000..52683316
--- /dev/null
+++ b/tests/storyboard.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { getModel } from "@/lib/catalog";
+import { framePrompt, heuristicScenes, parseScenes, STORYBOARD_MODELS } from "@/lib/catalog/storyboard";
+
+describe("storyboard", () => {
+ it("parses LLM answers as a JSON array or a numbered list", () => {
+ expect(parseScenes('Sure! ["a girl waits at a bus stop", "the bus arrives", "she boards"]', 3)).toEqual(["a girl waits at a bus stop", "the bus arrives", "she boards"]);
+ expect(parseScenes("1. A girl waits at the stop\n2. Headlights wash over her\n3. She boards the bus", 2)).toEqual(["A girl waits at the stop", "Headlights wash over her"]);
+ expect(parseScenes("no", 3)).toBeNull();
+ });
+
+ it("falls back to a shot list offline", () => {
+ const s = heuristicScenes("a heist in Paris.", 3);
+ expect(s).toHaveLength(3);
+ expect(s[0]).toBe("establishing wide shot: a heist in Paris — beat 1 of 3");
+ });
+
+ it("tells chained frames which image is the previous one", () => {
+ expect(framePrompt("the bus arrives", 1, { refs: 2, chainFrom: "last" })).toMatch(/Image 3 is the previous frame/);
+ expect(framePrompt("the bus arrives", 1, { refs: 1, chainFrom: "first" })).toBe("Next Scene: the bus arrives.");
+ expect(framePrompt("a girl waits", 0, { refs: 1, chainFrom: "last", style: "35mm film" })).toBe(
+ "Frame 1 of a storyboard: a girl waits. Use the reference image for the characters and look. Style: 35mm film. Cinematic still, consistent production design.",
+ );
+ });
+
+ it("uses edit-capable models for follow-up frames on both engines", () => {
+ for (const m of Object.values(STORYBOARD_MODELS)) {
+ expect(getModel(m.next)?.routes.some((r) => r.op === "edit")).toBe(true);
+ expect(getModel(m.first)?.routes.some((r) => r.op === "t2i")).toBe(true);
+ }
+ });
+});