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.

Chained jobs: open multi-shot, storyboard films, join clips, Kling extend, palette match

Claude1b443798b652
diff --git a/scripts/comfy/hand-built/video-concat-2.json b/scripts/comfy/hand-built/video-concat-2.json
index 75095b4c..a9dc9226 100644
--- a/scripts/comfy/hand-built/video-concat-2.json
+++ b/scripts/comfy/hand-built/video-concat-2.json
@@ -92,7 +92,10 @@
"20",
0
],
- "fps": 16.0,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"
diff --git a/scripts/comfy/hand-built/video-concat-3.json b/scripts/comfy/hand-built/video-concat-3.json
index 3b274bf6..f33641e2 100644
--- a/scripts/comfy/hand-built/video-concat-3.json
+++ b/scripts/comfy/hand-built/video-concat-3.json
@@ -131,7 +131,10 @@
"20",
0
],
- "fps": 16.0,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"
diff --git a/scripts/comfy/hand-built/video-concat-4.json b/scripts/comfy/hand-built/video-concat-4.json
index 44b63d02..7318b36d 100644
--- a/scripts/comfy/hand-built/video-concat-4.json
+++ b/scripts/comfy/hand-built/video-concat-4.json
@@ -170,7 +170,10 @@
"20",
0
],
- "fps": 16.0,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjs
index 8f3806ae..5565930b 100644
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@ -1491,7 +1491,7 @@ export const SPEC = [
vramGb: 0,
license: 'no model (ComfyUI core nodes)',
notes:
- `Hard-cut concatenation of ${n} clips (video${n > 1 ? ', video2' : ''}${n > 2 ? ', video3' : ''}${n > 3 ? ', video4' : ''}) in order: LoadVideo -> ImageScale (lanczos, center crop to width x height) -> BatchImagesNode -> CreateVideo(fps). ` +
+ `Hard-cut concatenation of ${n} clips (video${n > 1 ? ', video2' : ''}${n > 2 ? ', video3' : ''}${n > 3 ? ', video4' : ''}) in order: LoadVideo -> ImageScale (lanczos, center crop to width x height) -> BatchImagesNode -> CreateVideo (fps linked from the first clip's GetVideoComponents; bind fps to override). ` +
'Multi-shot recipe: storyboard panels (storyboard-qwen-edit-2509-next-scene) -> one wan22-i2v-14b-lightx2v job per shot (or wan22-flf2v-14b between panels N and N+1 for match cuts) -> this graph; add sound afterwards (v2a-mmaudio / music). ' +
'All clips should share one fps (frames are concatenated, not retimed); audio tracks are dropped. Runs on CPU; RAM grows with total frame count. LTX-2.5 native multishot (ltx25-t2v/i2v with a shot-list prompt) is the one-pass alternative.',
})),
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.ts
index b92f825e..add034cf 100644
--- a/src/app/api/generations/route.ts
+++ b/src/app/api/generations/route.ts
@@ -19,6 +19,7 @@ const RequestSchema = z.object({
audio: z.string().optional(),
voiceAudio: z.string().optional(),
voiceAudio2: z.string().optional(),
+ videos: z.array(z.string()).max(24).optional(),
})
.optional(),
params: z
diff --git a/src/app/api/storyboards/[id]/film/route.ts b/src/app/api/storyboards/[id]/film/route.ts
new file mode 100644
index 00000000..d1d659a0
--- /dev/null
+++ b/src/app/api/storyboards/[id]/film/route.ts
@@ -0,0 +1,15 @@
+import { z } from "zod";
+import { createStoryboardFilm } from "@/server/storyboard";
+
+const Body = z.object({ modelId: z.string().max(100).optional() });
+
+/** Animate a storyboard's frames into clips and join them into one film. */
+export async function POST(request: Request, ctx: RouteContext<"/api/storyboards/[id]/film">) {
+ 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 Response.json({ error: (e as Error).message }, { status: 422 });
+ }
+}
diff --git a/src/app/api/uploads/route.ts b/src/app/api/uploads/route.ts
index 2452be32..8906ba5f 100644
--- a/src/app/api/uploads/route.ts
+++ b/src/app/api/uploads/route.ts
@@ -1,4 +1,4 @@
-import { saveFile } from "@/server/storage";
+import { contentTypeFor, saveFile } from "@/server/storage";
const MAX_BYTES = 200 * 1024 * 1024;
const ALLOWED = /^(image\/(png|jpeg|webp|gif)|video\/(mp4|webm|quicktime)|audio\/(mpeg|wav|x-wav|ogg|flac|mp4|webm))$/;
@@ -8,10 +8,12 @@ export async function POST(request: Request) {
const file = form?.get("file");
if (!(file instanceof File)) return Response.json({ error: "No file" }, { status: 400 });
if (file.size > MAX_BYTES) return Response.json({ error: "File too large (200 MB max)" }, { status: 413 });
- if (!ALLOWED.test(file.type)) return Response.json({ error: `Unsupported file type ${file.type || "unknown"}` }, { status: 415 });
+ // Scripts often send no type (or octet-stream): go by the file extension then.
+ const type = !file.type || file.type === "application/octet-stream" ? contentTypeFor(file.name, "") : file.type;
+ if (!ALLOWED.test(type)) return Response.json({ error: `Unsupported file type ${type || file.type || "unknown"}` }, { status: 415 });
const asset = saveFile({
data: Buffer.from(await file.arrayBuffer()),
- contentType: file.type,
+ contentType: type,
name: file.name,
source: "upload",
});
diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsx
index c6d8fecd..7df3bcce 100644
--- a/src/components/storyboard-view.tsx
+++ b/src/components/storyboard-view.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { ArrowUp, Clapperboard, ImagePlus, Loader2, Minus, Plus, Sparkles, Trash2, Wand2, X } from "lucide-react";
+import { ArrowUp, Clapperboard, Film, 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";
@@ -38,12 +38,57 @@ function RatioPill({ value, onChange }: { value: string; onChange: (v: string) =
);
}
-function Board({ frames, onOpen }: { frames: Generation[]; onOpen: (g: Generation) => void }) {
+/** The film made from a board: the joined video big, its shots small underneath. */
+function FilmStrip({ items, ratio, onOpen }: { items: Generation[]; ratio: number; onOpen: (g: Generation) => void }) {
+ const create = useCreateGeneration();
+ const sorted = [...items].sort((a, b) => (a.request.step?.index ?? 0) - (b.request.step?.index ?? 0));
+ const film = sorted.findLast((g) => g.op === "concat");
+ const shots = sorted.filter((g) => g.op !== "concat");
+ const tile = (g: Generation, className?: string) =>
+ g.status === "succeeded" && g.outputs[0] ? (
+ <button onClick={() => onOpen(g)} className={cn("block w-full overflow-hidden rounded-xl bg-muted", className)} style={{ aspectRatio: ratio }}>
+ <MediaThumb output={g.outputs[0]} autoPlay={g === film} />
+ </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} />
+ );
+ return (
+ <div className="grid gap-3 rounded-2xl border bg-muted/30 p-3 md:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
+ {film && <div className="min-w-0">{tile(film)}</div>}
+ <div className="grid min-w-0 grid-cols-2 content-start gap-2">
+ {shots.map((g) => (
+ <figure key={g.id} className="min-w-0 space-y-1">
+ {tile(g)}
+ <figcaption className="text-[11px] text-muted-foreground">{g.request.step?.label}</figcaption>
+ </figure>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function Board({ frames, film, onOpen }: { frames: Generation[]; film: Generation[]; onOpen: (g: Generation) => void }) {
const { remove } = useGenerationActions();
const create = useCreateGeneration();
+ const qc = useQueryClient();
const first = frames[0];
const done = frames.filter((f) => f.status === "succeeded").length;
const ratio = tileRatio(first);
+ 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 new Error(body.error);
+ return body as { items: Generation[] };
+ },
+ onSuccess: (b) => {
+ toast.success(`Animating ${b.items.length - 1} shots, then joining them into one film`);
+ void qc.invalidateQueries({ queryKey: ["generations"] });
+ },
+ onError: (e) => toast.error((e as Error).message),
+ });
return (
<section className="animate-fade-up space-y-3">
<header className="flex items-start gap-3">
@@ -53,12 +98,17 @@ function Board({ frames, onOpen }: { frames: Generation[]; onOpen: (g: Generatio
{frames.length} frames · {done === frames.length ? "done" : `${done}/${frames.length} ready`} · {getModel(first.modelId)?.name} · {timeAgo(first.createdAt)}
</p>
</div>
+ {!film.length && frames.length > 1 && first.batchId && (
+ <Button variant="secondary" size="sm" disabled={makeFilm.isPending} onClick={() => makeFilm.mutate()}>
+ {makeFilm.isPending ? <Loader2 className="animate-spin" /> : <Film />} Make the film
+ </Button>
+ )}
<Button
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-destructive"
onClick={() => {
- frames.forEach((f) => void remove(f));
+ [...frames, ...film].forEach((f) => void remove(f));
toast("Storyboard deleted");
}}
>
@@ -105,6 +155,7 @@ function Board({ frames, onOpen }: { frames: Generation[]; onOpen: (g: Generatio
);
})}
</div>
+ {film.length > 0 && <FilmStrip items={film} ratio={ratio} onOpen={onOpen} />}
</section>
);
}
@@ -120,17 +171,26 @@ export function StoryboardView() {
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 feed = useGenerations({ features: ["storyboard", "storyboard-film"], limit: 240 });
- const boards = useMemo(() => {
+ const films = useMemo(() => {
const by = new Map<string, Generation[]>();
for (const g of feed.data ?? []) {
+ if (g.feature !== "storyboard-film" || !g.batchId) continue;
+ const k = g.batchId.replace(/-film$/, "");
+ by.set(k, [...(by.get(k) ?? []), g]);
+ }
+ return by;
+ }, [feed.data]);
+ const boards = useMemo(() => {
+ const by = new Map<string, Generation[]>();
+ for (const g of (feed.data ?? []).filter((x) => x.feature === "storyboard")) {
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 flat = boards.flatMap((b) => [...b, ...(films.get(b[0].batchId ?? "") ?? [])].filter((g) => g.status === "succeeded" && g.outputs[0]));
const pos = open ? flat.findIndex((g) => g.id === open.id) : -1;
const m = STORYBOARD_MODELS[engine];
@@ -279,7 +339,7 @@ export function StoryboardView() {
) : boards.length ? (
<div className="space-y-10">
{boards.map((b) => (
- <Board key={b[0].batchId ?? b[0].id} frames={b} onOpen={setOpen} />
+ <Board key={b[0].batchId ?? b[0].id} frames={b} film={films.get(b[0].batchId ?? "") ?? []} onOpen={setOpen} />
))}
</div>
) : (
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index c81bbd05..7230cfd7 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -26,7 +26,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { Kbd } from "@/components/ui/kbd";
import { EFFECTS, getModel, getPreset, modelsFor, MOTIONS } from "@/lib/catalog";
import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
-import { OPERATION_LABELS, type GenerationRequest, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";
+import { OPERATION_LABELS, type GenerationRequest, type MediaKind, type ModelDef, type Operation, type Preset } from "@/lib/catalog/types";
import { enhance, useCreateGeneration, useElements, useEngine, useStatus } from "@/lib/api";
import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
@@ -246,9 +246,12 @@ function buildRequest(
draft: ReturnType<typeof useStudio>["draft"],
op: Operation | undefined,
promptSuffix?: string,
+ refKind: MediaKind = "image",
): GenerationRequest {
const s = draft.slots;
- const images = [s.image, s.image2, s.image3, ...draft.refs].filter((x): x is SlotValue => !!x?.ref).map((x) => x.ref);
+ const refs = draft.refs.filter((x) => !!x?.ref).map((x) => x.ref);
+ const images = [s.image, s.image2, s.image3].filter((x): x is SlotValue => !!x?.ref).map((x) => x.ref).concat(refKind === "image" ? refs : []);
+ const videos = refKind === "video" ? refs : [];
return {
feature,
presetId: draft.presetId,
@@ -265,6 +268,7 @@ function buildRequest(
voiceAudio2: s.voiceAudio2?.ref || undefined,
video: s.video?.ref || undefined,
audio: s.audio?.ref || undefined,
+ videos: videos.length ? videos : undefined,
},
params: draft.params,
presetOptions: draft.presetOptions,
@@ -296,7 +300,7 @@ export function Composer({ docked }: { docked: boolean }) {
// Single-purpose studios (Extend, Reframe, Edit video…) pin their operation.
const studioOp = config.ops.length === 1 && !preset ? config.ops[0] : undefined;
- const rawRequest = buildRequest(config.feature, draft, studioOp, config.promptSuffix);
+ const rawRequest = buildRequest(config.feature, draft, studioOp, config.promptSuffix, config.multiRef?.kind);
const mentions = model ? applyMentions(rawRequest, model, elements) : { request: rawRequest, mentioned: [], notes: [] };
const sketched = model ? applySketch(mentions.request, model) : { request: mentions.request };
const request = model ? stripMotionPaths(sketched.request, model) : sketched.request;
@@ -329,7 +333,7 @@ export function Composer({ docked }: { docked: boolean }) {
return;
}
// The server resolves @mentions and drawings itself; only pin the operation when there are none.
- create.mutate(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix), {
+ create.mutate(buildRequest(config.feature, draft, resolvesOnServer ? studioOp : op, config.promptSuffix, config.multiRef?.kind), {
onSuccess: (items) => {
toast.success(items.length > 1 ? `${items.length} jobs queued` : "Queued", { duration: 1500 });
},
@@ -364,6 +368,12 @@ export function Composer({ docked }: { docked: boolean }) {
const slots = preset?.inputs ?? config.slots;
const opts = model?.options ?? {};
+ // Clips: ComfyUI joins 4 at a time. Images: what the model takes beyond the fixed image slots.
+ const refMax = !config.multiRef
+ ? 0
+ : config.multiRef.kind === "video"
+ ? Math.min(config.multiRef.max, model?.engine === "open" ? 4 : config.multiRef.max)
+ : Math.min(config.multiRef.max, Math.max(0, (opts.maxImages ?? 1) - slots.filter((s) => s.accept === "image").length));
const p = draft.params;
const setP = (patch: Partial<typeof p>) => setDraft((d) => ({ params: { ...d.params, ...patch } }));
const setExtra = (key: string, v: unknown) =>
@@ -422,10 +432,10 @@ export function Composer({ docked }: { docked: boolean }) {
</button>
</div>
))}
- {config.multiRef && draft.refs.length < Math.min(config.multiRef.max, Math.max(0, (opts.maxImages ?? 1) - slots.filter((s) => s.accept === "image").length)) && (
+ {config.multiRef && draft.refs.length < refMax && (
<MediaSlot
label={config.multiRef.label}
- kind="image"
+ kind={config.multiRef.kind ?? "image"}
value={null}
onFile={(f) => {
const id = nanoid(6);
diff --git a/src/components/studio/feed.tsx b/src/components/studio/feed.tsx
index da0041a9..c6d11a7d 100644
--- a/src/components/studio/feed.tsx
+++ b/src/components/studio/feed.tsx
@@ -187,6 +187,7 @@ export function GenerationGroup({
const finalize = useFinalizeDraft();
const p = g.request.params ?? {};
const meta = [
+ g.request.step?.label,
preset?.name,
model?.name ?? g.modelId,
OPERATION_LABELS[g.op],
diff --git a/src/components/studio/mode-switch-studio.tsx b/src/components/studio/mode-switch-studio.tsx
index 89e56eb7..2f716feb 100644
--- a/src/components/studio/mode-switch-studio.tsx
+++ b/src/components/studio/mode-switch-studio.tsx
@@ -6,10 +6,12 @@ import {
AUDIO_STUDIO,
DIALOGUE_STUDIO,
FOLEY_STUDIO,
+ JOIN_CLIPS_STUDIO,
MUSIC_STUDIO,
SFX_STUDIO,
TRANSLATE_STUDIO,
UPSCALE_STUDIO,
+ VIDEO_COLOR_MATCH_STUDIO,
VIDEO_DEPTH_STUDIO,
VIDEO_MATTE_STUDIO,
VIDEO_RELIGHT_STUDIO,
@@ -37,6 +39,8 @@ const MODES = {
{ id: "matte", label: "Remove background", config: VIDEO_MATTE_STUDIO },
{ id: "relight", label: "Relight", config: VIDEO_RELIGHT_STUDIO },
{ id: "depth", label: "Depth map", config: VIDEO_DEPTH_STUDIO },
+ { id: "join", label: "Join clips", config: JOIN_CLIPS_STUDIO },
+ { id: "colors", label: "Match colors", config: VIDEO_COLOR_MATCH_STUDIO },
],
} as const;
diff --git a/src/components/studio/shots-editor.tsx b/src/components/studio/shots-editor.tsx
index b96fcded..05773822 100644
--- a/src/components/studio/shots-editor.tsx
+++ b/src/components/studio/shots-editor.tsx
@@ -16,10 +16,12 @@ export function MultiShotChip({ model, params, onChange }: { model: ModelDef; pa
const [open, setOpen] = useState(false);
const ms = model.options.multiShot!;
const mode = params.shots ? "custom" : params.multiShot === "auto" ? "auto" : "off";
- const each = Math.max(1, Math.floor((params.duration ?? model.defaults?.duration ?? 6) / 2));
+ const concat = ms.mode === "concat";
+ const each = concat ? (model.defaults?.duration ?? 5) : Math.max(1, Math.floor((params.duration ?? model.defaults?.duration ?? 6) / 2));
const options = [
{ id: "off", label: "Off", hint: "One continuous shot" },
- { id: "auto", label: "Auto", hint: "The model plans the cuts" },
+ // Open models can't plan their own cuts.
+ ...(concat ? [] : [{ id: "auto", label: "Auto", hint: "The model plans the cuts" } as const]),
{ id: "custom", label: "Custom", hint: `Write up to ${ms.maxShots} shots` },
] as const;
return (
@@ -57,7 +59,11 @@ export function MultiShotChip({ model, params, onChange }: { model: ModelDef; pa
))}
</div>
<p className="px-1 pt-2 text-[11px] text-muted-foreground">
- {ms.mode === "native" ? `${model.name} takes each shot as its own prompt.` : `${model.name} follows shots written into the prompt.`}
+ {ms.mode === "native"
+ ? `${model.name} takes each shot as its own prompt.`
+ : concat
+ ? `Each shot renders as its own ${model.name} clip, then they're joined into one video.`
+ : `${model.name} follows shots written into the prompt.`}
</p>
</PopoverContent>
</Popover>
@@ -69,6 +75,14 @@ export function ShotsEditor({ model, shots, onChange }: { model: ModelDef; shots
const max = Math.max(...(model.options.durations ?? [15]));
const total = shots.reduce((n, s) => n + s.duration, 0);
const maxShots = model.options.multiShot?.maxShots ?? 6;
+ // Joined films: every shot is a separate clip, so it takes one of the model's own durations.
+ const concat = model.options.multiShot?.mode === "concat";
+ const steps = concat ? [...(model.options.durations ?? [5])].sort((a, b) => a - b) : null;
+ const stepTo = (d: number, dir: 1 | -1) => {
+ if (!steps) return dir > 0 ? Math.min(15, d + 1) : Math.max(1, d - 1);
+ return (dir > 0 ? steps.find((x) => x > d) : steps.findLast((x) => x < d)) ?? d;
+ };
+ const full = !concat && total >= max;
const set = (i: number, patch: Partial<Shot>) => onChange(shots.map((s, j) => (j === i ? { ...s, ...patch } : s)));
const starts = shots.map((_, i) => shots.slice(0, i).reduce((n, s) => n + s.duration, 0));
return (
@@ -89,7 +103,7 @@ export function ShotsEditor({ model, shots, onChange }: { model: ModelDef; shots
className="field-sizing-content max-h-28 min-h-8 flex-1 resize-none bg-transparent py-1 text-[14px] leading-snug outline-none placeholder:text-subtle-foreground"
/>
<div className="flex shrink-0 items-center gap-0.5 rounded-full bg-background p-0.5 shadow-soft">
- <button onClick={() => set(i, { duration: Math.max(1, s.duration - 1) })} className="grid size-6 place-items-center rounded-full hover:bg-accent" aria-label="Shorter">
+ <button onClick={() => set(i, { duration: stepTo(s.duration, -1) })} className="grid size-6 place-items-center rounded-full hover:bg-accent" aria-label="Shorter">
<Minus className="size-3" />
</button>
<Tooltip>
@@ -101,8 +115,8 @@ export function ShotsEditor({ model, shots, onChange }: { model: ModelDef; shots
</TooltipContent>
</Tooltip>
<button
- onClick={() => set(i, { duration: Math.min(15, s.duration + 1) })}
- disabled={total >= max}
+ onClick={() => set(i, { duration: stepTo(s.duration, 1) })}
+ disabled={full || (!!steps && s.duration >= steps[steps.length - 1])}
className="grid size-6 place-items-center rounded-full hover:bg-accent disabled:opacity-40"
aria-label="Longer"
>
@@ -122,15 +136,15 @@ export function ShotsEditor({ model, shots, onChange }: { model: ModelDef; shots
<div className="flex items-center gap-3 px-1">
{shots.length < maxShots && (
<button
- onClick={() => onChange([...shots, { prompt: "", duration: Math.max(1, Math.min(3, max - total)) }])}
- disabled={total >= max}
+ onClick={() => onChange([...shots, { prompt: "", duration: steps ? (model.defaults?.duration ?? steps[0]) : Math.max(1, Math.min(3, max - total)) }])}
+ disabled={full}
className="inline-flex items-center gap-1 text-[12px] font-medium text-brand-text hover:underline disabled:opacity-40"
>
<Plus className="size-3" /> Add shot
</button>
)}
- <span className={cn("ml-auto font-mono text-[11px] text-muted-foreground", total > max && "text-destructive")}>
- {total}s of {max}s
+ <span className={cn("ml-auto font-mono text-[11px] text-muted-foreground", !concat && total > max && "text-destructive")}>
+ {concat ? `${total}s film · up to ${max}s a shot` : `${total}s of ${max}s`}
</span>
</div>
</div>
diff --git a/src/components/studio/studio-context.tsx b/src/components/studio/studio-context.tsx
index 20e628fc..2ddf1400 100644
--- a/src/components/studio/studio-context.tsx
+++ b/src/components/studio/studio-context.tsx
@@ -20,8 +20,8 @@ export interface StudioConfig {
ops: Operation[];
feed: FeedFilter;
slots: InputSlot[];
- /** Extra reference images (multi-reference edit / image prompt). */
- multiRef?: { label: string; max: number };
+ /** Extra reference images (multi-reference edit / image prompt), or a list of clips (kind "video": join clips). */
+ multiRef?: { label: string; max: number; kind?: MediaKind };
/** Preset picker shown in the composer. */
presetPicker?: "motion" | "effect";
preset?: Preset;
diff --git a/src/components/workflows-view.tsx b/src/components/workflows-view.tsx
index 3df59ffe..2ff8f90b 100644
--- a/src/components/workflows-view.tsx
+++ b/src/components/workflows-view.tsx
@@ -28,7 +28,7 @@ export function WorkflowsView() {
});
if (q.isLoading) return <Loader2 className="size-5 animate-spin text-muted-foreground" />;
const data = q.data!;
- const usedBy = (id: string) => MODELS.filter((m) => m.routes.some((r) => r.provider === "comfyui" && r.endpoint === id)).map((m) => m.name);
+ const usedBy = (id: string) => MODELS.filter((m) => m.routes.some((r) => r.provider === "comfyui" && (r.endpoint === id || (r.endpoint.includes("{n}") && new RegExp(`^${r.endpoint.replace("{n}", "\\d")}$`).test(id))))).map((m) => m.name);
return (
<div className="space-y-6">
diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.ts
index ef2d80a9..ef270dcd 100644
--- a/src/lib/catalog/apps.ts
+++ b/src/lib/catalog/apps.ts
@@ -367,6 +367,29 @@ export const APPS: Preset[] = [
prompt:
"Relight the image with {option:light} {option:dir}. Keep the subject, composition and all details identical; only the light, shadows, reflections and color temperature change.",
}),
+ app({
+ name: "Match Lighting",
+ category: "Camera",
+ description: "Relight a photo to match the light in a reference shot",
+ icon: "Sunset",
+ hue: 35,
+ inputs: [photo, second("Lighting reference", "A photo whose light you want")],
+ prompt:
+ "Relight image 1 so its lighting matches image 2: the same light direction, softness, color temperature, contrast and mood. Keep the subject, composition and every detail of image 1 identical; only the light, shadows and reflections change.",
+ open: { modelId: "oss-qwen-relight-ref", op: "edit" },
+ }),
+ app({
+ name: "Match Colors",
+ category: "Camera",
+ description: "Give a photo the color palette of a reference image",
+ icon: "Palette",
+ hue: 300,
+ inputs: [photo, second("Color reference", "A still, poster or frame with the colors you want")],
+ prompt:
+ "Recolor image 1 to match the color palette and grade of image 2: the same hues, saturation, contrast and tone in the shadows and highlights. Keep the content, composition and details of image 1 unchanged.",
+ open: { modelId: "oss-palette-image", op: "color-match" },
+ parity: "The open version transfers the palette directly (no AI model, runs on CPU); the cloud version re-grades with Nano Banana Pro",
+ }),
app({
name: "Expand Image",
category: "Camera",
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index e85c4460..4cd09890 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -1,6 +1,6 @@
import { CLOUD_MODELS } from "./cloud-models.generated";
import { HIGGSFIELD_MODELS, HIGGSFIELD_ROUTES } from "./higgsfield-models.generated";
-import type { ModelDef, ModelRoute, Operation } from "./types";
+import { LAST_FRAME_CHAIN, type ModelDef, type ModelRoute, type Operation } from "./types";
/*
* Model catalog.
@@ -23,6 +23,9 @@ const CHATTERBOX_SLIDERS = [
{ param: "temperature", label: "Variety", min: 0.05, max: 2, step: 0.05, default: 0.8 },
];
+/** Open models have no multi-shot of their own: each shot renders separately, then the clips are joined. */
+const CONCAT_SHOTS = { mode: "concat", maxShots: 4 } as const;
+
const IMG_AR = ["1:1", "4:3", "3:4", "16:9", "9:16", "3:2", "2:3", "21:9", "5:4", "4:5"];
const VID_AR = ["16:9", "9:16", "1:1"];
@@ -231,7 +234,7 @@ const open: ModelDef[] = [
tagline: "Best open video model with Lightx2v 4-step LoRAs — minutes, not hours",
badges: ["fast", "top"],
routes: [comfy("t2v", "wan22-t2v-14b-lightx2v", "Lightx2v 4-step"), comfy("i2v", "wan22-i2v-14b-lightx2v", "Lightx2v 4-step"), comfy("flf2v", "wan22-flf2v-14b")],
- options: { aspectRatios: VID_AR, durations: [3, 5], resolutions: ["480p", "720p"], seed: true, negativePrompt: true, endFrame: true },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [3, 5], resolutions: ["480p", "720p"], seed: true, negativePrompt: true, endFrame: true },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "480p" },
}),
o({
@@ -242,7 +245,7 @@ const open: ModelDef[] = [
kind: "video",
tagline: "Full-quality Wan 2.2 (20 steps) — text, image and start/end frame",
routes: [comfy("t2v", "wan22-t2v-14b"), comfy("i2v", "wan22-i2v-14b"), comfy("flf2v", "wan22-flf2v-14b")],
- options: { aspectRatios: VID_AR, durations: [3, 5, 7], resolutions: ["480p", "720p"], seed: true, negativePrompt: true, endFrame: true },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [3, 5, 7], resolutions: ["480p", "720p"], seed: true, negativePrompt: true, endFrame: true },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "480p" },
}),
o({
@@ -254,7 +257,7 @@ const open: ModelDef[] = [
tagline: "720p video on a single consumer GPU",
badges: ["fast"],
routes: [comfy("t2v", "wan22-ti2v-5b"), comfy("i2v", "wan22-ti2v-5b-i2v")],
- options: { aspectRatios: VID_AR, durations: [3, 5], resolutions: ["720p"], seed: true, negativePrompt: true },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [3, 5], resolutions: ["720p"], seed: true, negativePrompt: true },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "720p" },
}),
o({
@@ -266,7 +269,7 @@ const open: ModelDef[] = [
tagline: "Open video with native synchronized audio, up to 10s",
badges: ["audio", "new"],
routes: [comfy("t2v", "ltx25-t2v"), comfy("i2v", "ltx25-i2v")],
- options: { aspectRatios: VID_AR, durations: [5, 8, 10], resolutions: ["720p", "1080p"], seed: true, negativePrompt: true, audio: "always" },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [5, 8, 10], resolutions: ["720p", "1080p"], seed: true, negativePrompt: true, audio: "always" },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "720p" },
}),
o({
@@ -278,7 +281,7 @@ const open: ModelDef[] = [
tagline: "Fast open video with audio",
badges: ["audio"],
routes: [comfy("t2v", "ltx2-t2v"), comfy("i2v", "ltx2-i2v")],
- options: { aspectRatios: VID_AR, durations: [5, 8], resolutions: ["720p"], seed: true, negativePrompt: true, audio: "always" },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [5, 8], resolutions: ["720p"], seed: true, negativePrompt: true, audio: "always" },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "720p" },
}),
o({
@@ -289,7 +292,7 @@ const open: ModelDef[] = [
kind: "video",
tagline: "Lightweight 8.3B model with strong motion",
routes: [comfy("t2v", "hunyuan15-t2v-720p"), comfy("i2v", "hunyuan15-i2v-720p")],
- options: { aspectRatios: VID_AR, durations: [5], resolutions: ["720p"], seed: true, negativePrompt: true },
+ options: { multiShot: CONCAT_SHOTS, aspectRatios: VID_AR, durations: [5], resolutions: ["720p"], seed: true, negativePrompt: true },
defaults: { aspectRatio: "16:9", duration: 5, resolution: "720p" },
}),
o({
@@ -531,6 +534,17 @@ const open: ModelDef[] = [
options: { seed: true, negativePrompt: true, maxImages: 1 },
hidden: true,
}),
+ o({
+ id: "oss-qwen-relight-ref",
+ name: "Qwen-Image-Edit Relight (reference)",
+ vendor: "Alibaba Qwen",
+ family: "qwen-image",
+ kind: "image",
+ tagline: "Relight a photo to match a reference image's light (Relight LoRA, 4 steps)",
+ routes: [comfy("edit", "relight-qwen-edit-2509-reference", "Relight LoRA + Lightning, image 2 = lighting reference")],
+ options: { seed: true, negativePrompt: true, maxImages: 2 },
+ hidden: true,
+ }),
o({
id: "oss-qwen-next-scene",
name: "Qwen-Image-Edit Next Scene",
@@ -604,12 +618,84 @@ const open: ModelDef[] = [
options: { durations: [30, 60, 120, 180], seed: true },
defaults: { duration: 60 },
}),
+ // Utilities used by chained jobs (multi-shot, storyboard films, extend) and the Video tools page.
+ o({
+ id: "oss-join-clips",
+ name: "Join clips",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "video",
+ tagline: "Join 2–4 clips into one video, scaled to one size",
+ routes: [comfy("concat", "video-concat-{n}")],
+ options: { aspectRatios: VID_AR, resolutions: ["480p", "720p", "1080p"] },
+ defaults: { aspectRatio: "16:9", resolution: "720p" },
+ }),
+ o({
+ id: "oss-palette-image",
+ name: "Palette match",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "image",
+ tagline: "Recolour an image to the palette of a reference image",
+ routes: [comfy("color-match", "palette-transfer-image")],
+ options: { sliders: [{ param: "strength", label: "Strength", min: 0, max: 1, step: 0.05, default: 0.8 }] },
+ }),
+ o({
+ id: "oss-palette-video",
+ name: "Palette match (video)",
+ vendor: "ComfyUI",
+ family: "utility",
+ kind: "video",
+ tagline: "Give every frame of a video the colours of a reference image",
+ routes: [comfy("color-match", "palette-transfer-video")],
+ options: { sliders: [{ param: "strength", label: "Strength", min: 0, max: 1, step: 0.05, default: 0.8 }] },
+ }),
];
+/** fal's FFmpeg utilities (docs/research/paid-model-apis-2.md): the cloud side of join clips and Kling extend. */
+const cloudTools: ModelDef[] = [
+ {
+ id: "join-clips",
+ name: "Join clips",
+ vendor: "fal",
+ family: "utility",
+ engine: "cloud",
+ kind: "video",
+ tagline: "Join clips into one video, in order",
+ routes: [{ op: "concat", provider: "fal", endpoint: "fal-ai/ffmpeg-api/merge-videos", map: { prompt: false, videos: "video_urls" } }],
+ options: {},
+ pricing: { unit: "request", usd: 0, note: "billed per compute second, ≈ free" },
+ },
+ {
+ id: "extract-frame",
+ name: "Extract frame",
+ vendor: "fal",
+ family: "utility",
+ engine: "cloud",
+ kind: "image",
+ tagline: "The first, middle or last frame of a video",
+ routes: [{ op: "frame", provider: "fal", endpoint: "fal-ai/ffmpeg-api/extract-frame", map: { prompt: false, video: "video_url", fixed: { frame_type: "last" } } }],
+ options: {},
+ pricing: { unit: "request", usd: 0.001 },
+ hidden: true,
+ },
+];
+
+/**
+ * Kling has no extend endpoint: Fuobe continues a clip from its last frame with Kling's own
+ * image-to-video and joins the two (fal's FFmpeg tools; src/server/chains.ts).
+ */
+function withLastFrameExtend(m: ModelDef): ModelDef {
+ const i2v = m.routes.find((r) => r.op === "i2v" && r.provider === "fal");
+ if (m.family !== "kling" || m.kind !== "video" || !i2v || m.routes.some((r) => r.op === "extend")) return m;
+ return { ...m, routes: [...m.routes, { op: "extend", provider: "fal", endpoint: LAST_FRAME_CHAIN, note: "last frame → Kling image-to-video → joined" }] };
+}
+
/** Cloud models with their Higgsfield routes attached, plus the models only Higgsfield hosts. */
const cloud: ModelDef[] = [
- ...CLOUD_MODELS.map((m) => (HIGGSFIELD_ROUTES[m.id] ? { ...m, routes: [...m.routes, ...HIGGSFIELD_ROUTES[m.id]] } : m)),
+ ...CLOUD_MODELS.map((m) => (HIGGSFIELD_ROUTES[m.id] ? { ...m, routes: [...m.routes, ...HIGGSFIELD_ROUTES[m.id]] } : m)).map(withLastFrameExtend),
...HIGGSFIELD_MODELS,
+ ...cloudTools,
];
/** Tools that run entirely in the browser; recorded in the library like any other result. */
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 49f2a331..a73e1f60 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -26,6 +26,7 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
if (map.mask && input.mask) out[map.mask] = input.mask;
if (map.video && input.video) out[map.video] = input.video;
if (map.videoArray && input.video) out[map.videoArray] = [input.video];
+ if (map.videos && input.videos?.length) out[map.videos] = input.videos;
if (map.audio && input.audio) out[map.audio] = input.audio;
if (map.aspectRatio && input.aspectRatio) {
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index a6304c4d..25b30a76 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -88,7 +88,7 @@ export interface Plan {
/** Operations that work from their inputs alone. */
const PROMPTLESS = new Set<Operation>([
- "finalize", "reframe", "dialogue", "voice-change", "dub", "bg-remove-video", "depth-video", "upscale-image", "upscale-video", "bg-remove",
+ "concat", "frame", "color-match", "finalize", "reframe", "dialogue", "voice-change", "dub", "bg-remove-video", "depth-video", "upscale-image", "upscale-video", "bg-remove",
"interpolate", "v2a", "face-swap", "motion-transfer", "lipsync", "avatar",
]);
@@ -131,7 +131,10 @@ export function planGeneration(
if (shots.length > model.options.multiShot.maxShots) throw new Error(`${model.name} takes up to ${model.options.multiShot.maxShots} shots`);
const total = shots.reduce((n, s) => n + s.duration, 0);
const max = Math.max(...(model.options.durations ?? [total]));
- if (total > max) throw new Error(`The shots add up to ${total}s — ${model.name} makes up to ${max}s`);
+ // Joined films (open models) render each shot as its own clip: only each shot has to fit.
+ const concat = model.options.multiShot.mode === "concat";
+ if (concat && shots.some((s) => s.duration > max)) throw new Error(`${model.name} makes clips up to ${max}s per shot`);
+ if (!concat && total > max) throw new Error(`The shots add up to ${total}s — ${model.name} makes up to ${max}s`);
// Per-shot prompts carry the overall description (and @element legend) with them.
const overall = prompt.trim().replace(/[.\s]+$/, "");
const native = model.options.multiShot.mode === "native";
@@ -171,7 +174,7 @@ export function planGeneration(
return { model, op, prompt, params: { ...params, numOutputs: perJobOutputs }, loras, jobs, perJobOutputs };
}
-const NEEDS: Partial<Record<Operation, { images?: number; video?: boolean; audio?: boolean; endImage?: boolean; mask?: boolean; msg: string }>> = {
+const NEEDS: Partial<Record<Operation, { images?: number; video?: boolean; videos?: number; audio?: boolean; endImage?: boolean; mask?: boolean; msg: string }>> = {
edit: { images: 1, msg: "Add an image to edit" },
inpaint: { images: 1, mask: true, msg: "Add an image and paint the area to change" },
outpaint: { images: 1, msg: "Add an image to extend" },
@@ -194,6 +197,9 @@ const NEEDS: Partial<Record<Operation, { images?: number; video?: boolean; audio
"bg-remove-video": { video: true, msg: "Add a video" },
"depth-video": { video: true, msg: "Add a video" },
"relight-video": { video: true, msg: "Add a video to relight" },
+ concat: { videos: 2, msg: "Add at least two clips to join" },
+ frame: { video: true, msg: "Add a video" },
+ "color-match": { images: 1, msg: "Add the image or video and a reference image" },
};
/** Human message for the first missing input of an operation, or null. */
@@ -203,6 +209,7 @@ export function missingInputs(op: Operation, req: Pick<GenerationRequest, "input
const i = req.inputs ?? {};
if (n.images && (i.images?.length ?? 0) < n.images) return n.msg;
if (n.video && !i.video) return n.msg;
+ if (n.videos && (i.videos?.length ?? 0) < n.videos) return n.msg;
if (n.audio && !i.audio) return n.msg;
if (n.endImage && !i.endImage) return n.msg;
if (n.mask && !i.mask) return n.msg;
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 609a9e7b..0e315cb9 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -43,7 +43,10 @@ export type Operation =
| "dub" // video (or audio) → translated, re-voiced and lip-synced
| "bg-remove-video" // video → the subject on a transparent background
| "depth-video" // video → depth map video
- | "relight-video"; // video → the same shot under new lighting
+ | "relight-video" // video → the same shot under new lighting
+ | "concat" // several clips → one video, in order
+ | "frame" // video → one of its frames (the last, for extending)
+ | "color-match"; // image or video + reference image → recoloured to the reference's palette
export const OPERATION_LABELS: Record<Operation, string> = {
t2i: "Text to image",
@@ -77,6 +80,9 @@ export const OPERATION_LABELS: Record<Operation, string> = {
"bg-remove-video": "Video background removal",
"depth-video": "Video depth map",
"relight-video": "Video relight",
+ concat: "Join clips",
+ frame: "Extract frame",
+ "color-match": "Match colors",
};
export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
@@ -111,6 +117,9 @@ export const OPERATION_OUTPUT: Record<Operation, MediaKind> = {
"bg-remove-video": "video",
"depth-video": "video",
"relight-video": "video",
+ concat: "video",
+ frame: "image",
+ "color-match": "image",
};
export type ProviderId = "fal" | "replicate" | "higgsfield" | "openai" | "google" | "comfyui" | "mock" | "local";
@@ -148,6 +157,8 @@ export interface FieldMap {
video?: string;
/** Video field that takes an array (receives the one input video). */
videoArray?: string;
+ /** Array field that receives every clip of `inputs.videos`, in order (join clips). */
+ videos?: string;
audio?: string;
aspectRatio?: string | EnumField;
resolution?: string | EnumField;
@@ -204,7 +215,7 @@ export interface ModelOptions {
audio?: boolean | "always";
endFrame?: boolean;
/** Multi-shot support: "native" sends per-shot prompts, "prompt" writes the shots into one prompt. */
- multiShot?: { mode: "native" | "prompt"; maxShots: number };
+ multiShot?: { mode: "native" | "prompt" | "concat"; maxShots: number };
/** Draft mode (cheap preview, then a full render of the take you like). */
draft?: boolean;
/** A style/template list fetched from the provider (Soul styles, Genjutsu looks, Marketing Studio templates). */
@@ -304,16 +315,28 @@ export interface GenerationRequest {
voiceAudio?: string;
/** Second speaker's reference voice (open-source dialogue). */
voiceAudio2?: string;
+ /** Several clips in order (join clips). */
+ videos?: string[];
};
params?: GenParams;
/** Values for preset option pickers (apps). */
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`. */
+ /** Chained jobs: where the previous job's image goes among `inputs.images` (one dependency). */
chainFrom?: "first" | "last";
+ /** Chained jobs with several dependencies: where each one's first output goes, in dependsOn order. */
+ chain?: ChainSlot[];
/** Storyboard frame this request makes (shown under the frame). */
frame?: { scene: string; index: number; of: number };
+ /** Part of a multi-step job (a shot of a multi-shot film, a step of an extend): shown on its tile. */
+ step?: { label: string; index: number; of: number };
+}
+
+export interface ChainSlot {
+ slot: "images" | "endImage" | "video" | "videos" | "audio";
+ /** For list slots: put it before or after the request's own items (default last). */
+ position?: "first" | "last";
}
/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */
@@ -327,6 +350,7 @@ export interface GenInput extends GenParams {
audio?: string;
voiceAudio?: string;
voiceAudio2?: string;
+ videos?: string[];
loras?: LoraRef[];
}
@@ -421,3 +445,6 @@ export interface Preset {
/** Research confidence / parity notes shown in docs and the UI. */
parity?: string;
}
+
+/** Route endpoint for models without an extend API: last frame → image-to-video → join (src/server/chains.ts). */
+export const LAST_FRAME_CHAIN = "chain:last-frame";
diff --git a/src/lib/studios.ts b/src/lib/studios.ts
index f5dc4e3e..75e1f871 100644
--- a/src/lib/studios.ts
+++ b/src/lib/studios.ts
@@ -338,3 +338,33 @@ export const VIDEO_RELIGHT_STUDIO: StudioConfig = {
promptOptional: false,
suggestions: ["Warm golden-hour sun from the left", "Pink and blue neon from the street", "A single cold window light, dark room", "Flickering campfire light from below"],
};
+
+export const JOIN_CLIPS_STUDIO: StudioConfig = {
+ feature: "video-tools",
+ title: "Video tools",
+ hero: "Join clips into one video",
+ subtitle: "Add clips in order — they're scaled to one size and cut together.",
+ placeholder: "",
+ kind: "video",
+ ops: ["concat"],
+ feed: { features: ["video-tools"] },
+ slots: [],
+ multiRef: { label: "Add clip", max: 12, kind: "video" },
+ defaultModels: { cloud: "join-clips", open: "oss-join-clips" },
+ promptOptional: true,
+ hidePrompt: true,
+};
+
+export const VIDEO_COLOR_MATCH_STUDIO: StudioConfig = {
+ ...VIDEO_MATTE_STUDIO,
+ hero: "Match the colors of a reference",
+ subtitle: "Every frame takes on the palette of the image you add — no AI model, runs on CPU.",
+ placeholder: "",
+ ops: ["color-match"],
+ slots: [
+ { key: "video", label: "Video", accept: "video", required: true },
+ { key: "image", label: "Color reference", accept: "image", required: true },
+ ],
+ defaultModels: { cloud: "", open: "oss-palette-video" },
+ hidePrompt: true,
+};
diff --git a/src/server/chains.ts b/src/server/chains.ts
new file mode 100644
index 00000000..9c474cff
--- /dev/null
+++ b/src/server/chains.ts
@@ -0,0 +1,140 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { getModel, supportsOp } from "@/lib/catalog";
+import type { Engine, Generation, GenerationRequest, ModelDef } from "@/lib/catalog/types";
+import { createGenerations } from "./generations";
+
+/**
+ * Multi-step jobs built from chained generations: each step waits for the ones it needs and
+ * gets their outputs as inputs (see CreateOptions.dependsOn and GenerationRequest.chain).
+ */
+
+const tidy = (p: string | undefined) => (p ?? "").trim().replace(/[.\s]+$/, "");
+
+export interface JoinOptions {
+ engine: Engine;
+ feature: string;
+ batchId: string;
+ title: string;
+ aspectRatio?: string;
+ resolution?: string;
+ /** Clips that already exist, placed before the chained ones (extend: the original video). */
+ before?: string[];
+ step?: GenerationRequest["step"];
+}
+
+/** 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 {
+ const modelId = o.engine === "open" ? "oss-join-clips" : "join-clips";
+ const max = o.engine === "open" ? 4 : 24;
+ const join = (group: string[], last: boolean): Generation =>
+ createGenerations(
+ {
+ feature: o.feature,
+ modelId,
+ op: "concat",
+ prompt: o.title,
+ inputs: last && o.before?.length ? { videos: o.before } : undefined,
+ // ComfyUI's join plays at the first clip's frame rate (linked in the workflow).
+ params: { aspectRatio: o.aspectRatio, resolution: o.resolution },
+ chain: group.map(() => ({ slot: "videos" as const })),
+ step: last ? o.step : { label: "Joining clips", index: 0, of: 1 },
+ },
+ { batchId: o.batchId, dependsOn: group },
+ )[0];
+ // Fold the first `max` clips into one until the rest fit in a final join (8 clips → 3 joins).
+ let level = ids;
+ const room = max - (o.before?.length ?? 0);
+ while (level.length > room) level = [join(level.slice(0, max), false).id, ...level.slice(max)];
+ return join(level, true);
+}
+
+/**
+ * Multi-shot on an open model: one clip per shot (the first gets the start image, the last the end
+ * frame), then a join. Returns the film first, then the shots.
+ */
+export function createShotFilm(original: GenerationRequest, model: ModelDef): Generation[] {
+ const shots = (original.params?.shots ?? []).filter((s) => s.prompt.trim());
+ const max = model.options.multiShot?.maxShots ?? 4;
+ if (shots.length > max) throw new Error(`${model.name} takes up to ${max} shots`);
+ const longest = Math.max(...(model.options.durations ?? [Infinity]));
+ const tooLong = shots.find((s) => s.duration > longest);
+ if (tooLong) throw new Error(`${model.name} makes clips up to ${longest}s — shorten “${tooLong.prompt.slice(0, 40)}”`);
+ const batchId = nanoid(10);
+ const overall = tidy(original.prompt);
+ const canT2v = supportsOp(model, "t2v");
+ const params = { ...original.params };
+ delete params.shots;
+ delete params.multiShot;
+ const n = shots.length;
+ const clips = shots.map((s, i) => {
+ const { images, endImage, ...rest } = original.inputs ?? {};
+ const inputs = { ...rest, ...((i === 0 || !canT2v) && images?.length && { images }), ...(i === n - 1 && endImage && { endImage }) };
+ return createGenerations(
+ {
+ ...original,
+ op: undefined,
+ prompt: overall ? `${overall}. ${s.prompt.trim()}` : s.prompt.trim(),
+ inputs: Object.keys(inputs).length ? inputs : undefined,
+ params: { ...params, duration: s.duration, numOutputs: 1 },
+ step: { label: `Shot ${i + 1} of ${n}`, index: i, of: n },
+ },
+ { batchId },
+ )[0];
+ });
+ const film = joinClips(
+ clips.map((c) => c.id),
+ {
+ engine: model.engine,
+ feature: original.feature,
+ batchId,
+ title: overall || shots.map((s) => tidy(s.prompt)).join(" / "),
+ aspectRatio: params.aspectRatio,
+ resolution: params.resolution,
+ step: { label: `Film · ${n} shots`, index: n, of: n + 1 },
+ },
+ );
+ return [film, ...clips];
+}
+
+/** Extend for models with no extend API (Kling): last frame → image-to-video on the same model → join. */
+export function createExtendChain(original: GenerationRequest, model: ModelDef): Generation[] {
+ const video = original.inputs?.video;
+ if (!video) throw new Error("Add the video to continue");
+ if (!supportsOp(model, "i2v")) throw new Error(`${model.name} can't continue a video`);
+ const batchId = nanoid(10);
+ const frame = createGenerations(
+ { feature: original.feature, modelId: "extract-frame", op: "frame", inputs: { video }, step: { label: "Last frame", index: 0, of: 3 } },
+ { batchId },
+ )[0];
+ const rest = { ...original.inputs };
+ delete rest.video;
+ delete rest.videos;
+ const clip = createGenerations(
+ {
+ ...original,
+ op: "i2v",
+ prompt: original.prompt?.trim() || "Continue the shot naturally, same subject, same camera move",
+ inputs: Object.keys(rest).length ? rest : undefined,
+ chain: [{ slot: "images", position: "first" }],
+ step: { label: "Continuation", index: 1, of: 3 },
+ },
+ { batchId, dependsOn: frame.id },
+ )[0];
+ const film = joinClips([clip.id], {
+ engine: model.engine,
+ feature: original.feature,
+ batchId,
+ title: tidy(original.prompt) || "Extended video",
+ before: [video],
+ step: { label: "Extended video", index: 2, of: 3 },
+ });
+ return [film, clip, frame];
+}
+
+/** The model a storyboard film is animated with. */
+export function filmModel(engine: Engine, modelId?: string): ModelDef {
+ const m = getModel(modelId ?? (engine === "open" ? "oss-wan22-14b-fast" : "seedance-2-5"));
+ if (!m || m.kind !== "video" || !supportsOp(m, "i2v")) throw new Error("Pick an image-to-video model");
+ return m;
+}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 6703151c..fcea919c 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -7,9 +7,12 @@ import { applyMentions } from "@/lib/catalog/elements";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";
import {
+ LAST_FRAME_CHAIN,
OPERATION_OUTPUT,
+ type ChainSlot,
type Generation,
type GenerationRequest,
+ type MediaKind,
type GenInput,
type ModelRoute,
type OutputFile,
@@ -18,6 +21,7 @@ import {
import { db } from "./db";
import { listElements } from "./elements";
import { pollTrainings } from "./training";
+import { createExtendChain, createShotFilm } from "./chains";
import { enhancePrompt } from "./enhance";
import { provider } from "./providers";
import type { RemoteOutput } from "./providers/types";
@@ -94,6 +98,7 @@ export function getGeneration(id: string): Generation | null {
}
export interface ListOptions {
+ batchId?: string;
feature?: string;
features?: string[];
kind?: string;
@@ -107,6 +112,10 @@ export interface ListOptions {
export function listGenerations(o: ListOptions = {}): Generation[] {
const where: string[] = [];
const args: unknown[] = [];
+ if (o.batchId) {
+ where.push("batch_id = ?");
+ args.push(o.batchId);
+ }
if (o.feature) {
where.push("feature = ?");
args.push(o.feature);
@@ -192,17 +201,32 @@ export function previewGeneration(req: GenerationRequest) {
}
export interface CreateOptions {
- /** Group several requests (storyboard frames) into one batch. */
+ /** Group several requests (storyboard frames, the shots of a film) into one batch. */
batchId?: string;
- /** Wait for this generation and feed its first output in as an image (see GenerationRequest.chainFrom). */
- dependsOn?: string;
+ /**
+ * Wait for these generations, then feed their first outputs in as inputs: where each goes is
+ * `request.chain` (one slot per id), or `request.chainFrom` for a single image dependency.
+ */
+ dependsOn?: string | string[];
}
+const depIds = (v: string | null): string[] => (!v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v]);
+
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);
+ // Open models make multi-shot films shot by shot, then join the clips.
+ const shotModel = getModel(original.modelId);
+ if (!opts.dependsOn && shotModel?.options.multiShot?.mode === "concat" && (original.params?.shots?.filter((x) => x.prompt.trim()).length ?? 0) > 1) {
+ return createShotFilm(original, shotModel);
+ }
+ if (!opts.dependsOn && original.op === "extend" && shotModel && routesFor(shotModel, "extend").some((r) => r.endpoint === LAST_FRAME_CHAIN)) {
+ return createExtendChain(original, shotModel);
+ }
+ const deps = opts.dependsOn === undefined ? [] : Array.isArray(opts.dependsOn) ? opts.dependsOn : [opts.dependsOn];
+ const waits = deps.length > 0;
+ // A dependent job can't be planned until its inputs exist; it's validated with placeholders, then launched by the runner.
+ const p = waits ? prepare(withChainInputs(original, slotsFor(original, deps.length).map(placeholderFor))) : prepare(original);
const { req, plan, route, demo, providerId, cost } = p;
- const jobs = opts.dependsOn ? 1 : plan.jobs;
+ const jobs = waits ? 1 : plan.jobs;
const batchId = opts.batchId ?? (jobs > 1 ? nanoid(10) : null);
const now = Date.now();
const created: Generation[] = [];
@@ -220,7 +244,7 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptio
kind: OPERATION_OUTPUT[plan.op],
status: "queued",
progress: null,
- message: opts.dependsOn ? "Waits for the previous frame" : demo ? "Demo mode — no provider connected" : "Submitting",
+ message: waits ? (original.frame ? "Waits for the previous frame" : "Waits for the earlier steps") : demo ? "Demo mode — no provider connected" : "Submitting",
prompt: plan.prompt,
request_json: JSON.stringify(original),
provider_input_json: null,
@@ -233,7 +257,7 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptio
created_at: now + i,
updated_at: now + i,
completed_at: null,
- depends_on: opts.dependsOn ?? null,
+ depends_on: !waits ? null : deps.length === 1 ? deps[0] : JSON.stringify(deps),
};
db()
.prepare(
@@ -243,23 +267,41 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptio
)
.run(row);
created.push(toGeneration(row));
- if (!opts.dependsOn) void submit(id, route, providerId, plan, req, i);
+ if (!waits) 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");
+/** Where each dependency's output goes: `chain`, or the single-image `chainFrom`. */
+function slotsFor(req: GenerationRequest, n: number): ChainSlot[] {
+ if (req.chain?.length) return req.chain.slice(0, n);
+ return Array.from({ length: n }, () => ({ slot: "images" as const, position: req.chainFrom ?? "last" }));
}
-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] } };
+const SLOT_KIND: Record<ChainSlot["slot"], MediaKind> = { images: "image", endImage: "image", video: "video", videos: "video", audio: "audio" };
+
+function placeholderFor(s: ChainSlot): string {
+ return SLOT_KIND[s.slot] === "image" ? "/api/files/placeholder.png" : SLOT_KIND[s.slot] === "video" ? "/api/files/placeholder.mp4" : "/api/files/placeholder.wav";
+}
+
+/** Put the dependencies' outputs into the request's inputs, slot by slot (lists keep dependency order). */
+export function withChainInputs(req: GenerationRequest, urls: string[]): GenerationRequest {
+ const inputs = { ...req.inputs };
+ const slots = slotsFor(req, urls.length);
+ for (const k of ["images", "videos"] as const) {
+ const at = (pos: "first" | "last") => slots.flatMap((s, i) => (s.slot === k && (s.position ?? "last") === pos ? [urls[i]] : []));
+ const first = at("first");
+ const last = at("last");
+ if (first.length || last.length) inputs[k] = [...first, ...(inputs[k] ?? []), ...last];
+ }
+ slots.forEach((s, i) => {
+ if (s.slot !== "images" && s.slot !== "videos") inputs[s.slot] = urls[i];
+ });
+ return { ...req, inputs };
}
-/** Launch dependent jobs whose input finished; fail the ones whose input failed. */
+/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. */
const launching = new Set<string>();
async function advanceDependents(): Promise<void> {
const rows = db()
@@ -267,20 +309,24 @@ async function advanceDependents(): Promise<void> {
.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() });
+ const request = JSON.parse(r.request_json) as GenerationRequest;
+ const ids = depIds(r.depends_on);
+ const slots = slotsFor(request, ids.length);
+ const deps = ids.map((id) => db().prepare("SELECT status, outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "outputs_json"> | undefined);
+ const earlier = request.frame ? "The previous frame" : "An earlier step";
+ if (deps.some((d) => !d || d.status === "failed" || d.status === "canceled")) {
+ update(r.id, { status: "failed", error: `${earlier} 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() });
+ if (deps.some((d) => d!.status !== "succeeded")) continue;
+ const urls = deps.map((d, i) => (JSON.parse(d!.outputs_json) as OutputFile[]).find((o) => o.kind === SLOT_KIND[slots[i].slot])?.url);
+ if (urls.some((u) => !u)) {
+ update(r.id, { status: "failed", error: `${earlier} has no ${SLOT_KIND[slots[urls.findIndex((u) => !u)].slot]} to use`, message: null, completed_at: Date.now() });
continue;
}
launching.add(r.id);
try {
- const original = withChainInput(JSON.parse(r.request_json) as GenerationRequest, url);
+ const original = withChainInputs(request, urls as string[]);
const { req, plan, route, providerId, cost, demo } = prepare(original);
update(r.id, {
provider: providerId,
@@ -338,6 +384,7 @@ async function submit(
audio: await prep(req.inputs?.audio),
voiceAudio: await prep(req.inputs?.voiceAudio),
voiceAudio2: await prep(req.inputs?.voiceAudio2),
+ videos: (await Promise.all((req.inputs?.videos ?? []).map(prep))).filter(Boolean) as string[],
loras: plan.loras,
// Vary seeds across a batch so N jobs don't return N identical results.
seed: plan.params.seed !== undefined && plan.params.seed >= 0 ? plan.params.seed + index : undefined,
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index c7d20606..e75fc41e 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -187,7 +187,11 @@ export const comfyProvider: ProviderAdapter = {
},
async submit({ route, input, generationId }) {
- const { manifest, workflow } = getWorkflow(route.endpoint);
+ // "video-concat-{n}": one workflow per clip count.
+ const clips = input.videos ?? [];
+ const endpoint = route.endpoint.replace("{n}", String(Math.max(2, Math.min(4, clips.length))));
+ if (route.endpoint.includes("{n}") && clips.length > 4) throw new ProviderError("ComfyUI joins up to 4 clips at a time");
+ const { manifest, workflow } = getWorkflow(endpoint);
const d = manifest.defaults;
const images = input.images ?? [];
const values: Partial<Record<BindingKey, unknown>> = {
@@ -199,7 +203,10 @@ export const comfyProvider: ProviderAdapter = {
image4: images[3],
endImage: input.endImage,
mask: input.mask,
- video: input.video,
+ video: input.video ?? clips[0],
+ video2: clips[1],
+ video3: clips[2],
+ video4: clips[3],
audio: input.audio,
seed: input.seed !== undefined && input.seed >= 0 ? input.seed : randomSeed(),
};
diff --git a/src/server/storyboard.ts b/src/server/storyboard.ts
index c578a414..ed733877 100644
--- a/src/server/storyboard.ts
+++ b/src/server/storyboard.ts
@@ -2,8 +2,10 @@ 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 { supportsOp } from "@/lib/catalog";
+import { filmModel, joinClips } from "./chains";
import { llmText } from "./enhance";
-import { createGenerations } from "./generations";
+import { createGenerations, listGenerations } from "./generations";
export interface StoryboardRequest {
engine: Engine;
@@ -55,3 +57,48 @@ export async function createStoryboard(r: StoryboardRequest): Promise<{ batchId:
});
return { batchId, scenes, items };
}
+
+/**
+ * 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.
+ */
+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));
+ 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`;
+ const aspectRatio = frames[0].request.params?.aspectRatio;
+ const n = frames.length;
+ const clips = frames.map((f, i) => {
+ const next = flf ? frames[i + 1] : undefined;
+ const scene = f.request.frame?.scene ?? f.request.prompt ?? "";
+ return createGenerations(
+ {
+ feature: "storyboard-film",
+ modelId: model.id,
+ prompt: next ? `${scene}. The shot moves naturally toward the next moment: ${next.request.frame?.scene ?? ""}` : `${scene}. Natural, cinematic motion.`,
+ params: { aspectRatio, duration: model.defaults?.duration },
+ chain: next ? [{ slot: "images", position: "first" }, { slot: "endImage" }] : [{ slot: "images", position: "first" }],
+ step: { label: `Shot ${i + 1} of ${n}`, index: i, of: n },
+ },
+ { batchId: filmBatch, dependsOn: next ? [f.id, next.id] : f.id },
+ )[0];
+ });
+ const film = joinClips(
+ clips.map((c) => c.id),
+ {
+ engine: model.engine,
+ feature: "storyboard-film",
+ batchId: filmBatch,
+ title: frames[0].request.frame?.scene ?? "Storyboard film",
+ aspectRatio,
+ resolution: model.defaults?.resolution,
+ step: { label: `Film · ${n} shots`, index: n, of: n + 1 },
+ },
+ );
+ return { batchId: filmBatch, items: [film, ...clips] };
+}
diff --git a/tests/catalog.test.ts b/tests/catalog.test.ts
index a7c1fcad..710d5acb 100644
--- a/tests/catalog.test.ts
+++ b/tests/catalog.test.ts
@@ -42,7 +42,11 @@ describe("catalog integrity", () => {
if (!fs.existsSync(file)) return;
const manifest = JSON.parse(fs.readFileSync(file, "utf8")) as Manifest;
const ids = new Set(manifest.workflows.map((w) => w.id));
- const missing = MODELS.flatMap((m) => m.routes.filter((r) => r.provider === "comfyui" && !ids.has(r.endpoint)).map((r) => `${m.id}:${r.endpoint}`));
+ // "{n}" routes pick a workflow per clip count (join clips: 2, 3 or 4).
+ const expand = (e: string) => (e.includes("{n}") ? ["2", "3", "4"].map((n) => e.replace("{n}", n)) : [e]);
+ const missing = MODELS.flatMap((m) =>
+ m.routes.filter((r) => r.provider === "comfyui").flatMap((r) => expand(r.endpoint).filter((e) => !ids.has(e)).map((e) => `${m.id}:${e}`)),
+ );
expect(missing).toEqual([]);
});
});
diff --git a/tests/chains.test.ts b/tests/chains.test.ts
new file mode 100644
index 00000000..6f6dabb8
--- /dev/null
+++ b/tests/chains.test.ts
@@ -0,0 +1,143 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-chains-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { createStoryboard, createStoryboardFilm } = await import("@/server/storyboard");
+const { db } = await import("@/server/db");
+const { getModel } = await import("@/lib/catalog");
+const { planGeneration } = await import("@/lib/catalog/plan");
+const { getPreset } = await import("@/lib/catalog");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+const dependsOn = (id: string) => {
+ const v = (db().prepare("SELECT depends_on FROM generations WHERE id = ?").get(id) as { depends_on: string | null }).depends_on;
+ return !v ? [] : v.startsWith("[") ? (JSON.parse(v) as string[]) : [v];
+};
+
+async function settle(id: string, ms = 40_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+describe("chain inputs", () => {
+ it("puts each dependency's output in its slot, keeping dependency order in lists", () => {
+ const req = {
+ feature: "x",
+ modelId: "m",
+ inputs: { images: ["own.png"], videos: ["orig.mp4"] },
+ chain: [{ slot: "images" as const, position: "first" as const }, { slot: "images" as const, position: "first" as const }, { slot: "endImage" as const }, { slot: "videos" as const }],
+ };
+ expect(gens.withChainInputs(req, ["a.png", "b.png", "end.png", "new.mp4"]).inputs).toEqual({
+ images: ["a.png", "b.png", "own.png"],
+ videos: ["orig.mp4", "new.mp4"],
+ endImage: "end.png",
+ });
+ // The single-dependency form storyboards use.
+ expect(gens.withChainInputs({ feature: "x", modelId: "m", chainFrom: "first", inputs: { images: ["ref.png"] } }, ["prev.png"]).inputs?.images).toEqual(["prev.png", "ref.png"]);
+ });
+});
+
+describe("open multi-shot", () => {
+ it("validates each shot against the model, not the total", () => {
+ const shots = [
+ { prompt: "wide", duration: 5 },
+ { prompt: "close", duration: 5 },
+ { prompt: "end", duration: 5 },
+ ];
+ expect(() => planGeneration({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { shots } }, getModel, getPreset)).not.toThrow();
+ expect(() => planGeneration({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { shots: [{ prompt: "a", duration: 9 }] } }, getModel, getPreset)).toThrow(/per shot/);
+ });
+
+ it("renders each shot, then joins them into one film", async () => {
+ const { saveFile } = await import("@/server/storage");
+ const png = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8cfc0f01f0005000201a2e2b6a40000000049454e44ae426082", "hex");
+ const start = saveFile({ data: png, contentType: "image/png", source: "upload" }).url;
+ const items = gens.createGenerations({
+ feature: "video",
+ modelId: "oss-wan22-14b-fast",
+ prompt: "A fox in the snow",
+ inputs: { images: [start] },
+ params: { aspectRatio: "16:9", shots: [{ prompt: "wide shot", duration: 3 }, { prompt: "close-up", duration: 5 }] },
+ });
+ const [film, ...shots] = items;
+ expect(film.op).toBe("concat");
+ expect(film.modelId).toBe("oss-join-clips");
+ expect(shots.map((s) => s.request.step?.label)).toEqual(["Shot 1 of 2", "Shot 2 of 2"]);
+ expect(shots.map((s) => s.op)).toEqual(["i2v", "t2v"]);
+ expect(shots[1].request.prompt).toBe("A fox in the snow. close-up");
+ expect(shots[1].request.params?.duration).toBe(5);
+ expect(dependsOn(film.id)).toEqual(shots.map((s) => s.id));
+ expect(new Set(items.map((g) => g.batchId)).size).toBe(1);
+ const done = await settle(film.id);
+ expect(done.status).toBe("succeeded");
+ expect(done.request.inputs?.videos).toHaveLength(2);
+ }, 45_000);
+
+ it("refuses more shots than the model takes", () => {
+ const shots = Array.from({ length: 5 }, (_, i) => ({ prompt: `s${i}`, duration: 3 }));
+ expect(() => gens.createGenerations({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", params: { shots } })).toThrow(/up to 4 shots/);
+ });
+});
+
+describe("Kling extend", () => {
+ it("chains last frame → Kling image-to-video → join with the original", () => {
+ const model = getModel("kling-3")!;
+ expect(model.routes.some((r) => r.op === "extend")).toBe(true);
+ const [film, clip, frame] = gens.createGenerations({ feature: "extend", modelId: "kling-3", op: "extend", prompt: "she keeps running", inputs: { video: "/api/files/placeholder.mp4" } });
+ expect(frame).toMatchObject({ modelId: "extract-frame", op: "frame" });
+ expect(clip).toMatchObject({ modelId: "kling-3", op: "i2v" });
+ expect(film).toMatchObject({ modelId: "join-clips", op: "concat" });
+ expect(dependsOn(clip.id)).toEqual([frame.id]);
+ expect(dependsOn(film.id)).toEqual([clip.id]);
+ expect(film.request.inputs?.videos).toEqual(["/api/files/placeholder.mp4"]);
+ expect(film.request.chain).toEqual([{ slot: "videos" }]);
+ });
+});
+
+describe("storyboard film", () => {
+ it("animates each frame toward the next, then joins the clips", async () => {
+ const board = await createStoryboard({ engine: "open", scenes: ["a lighthouse at dusk", "the keeper climbs the stairs", "the lamp turns on"] });
+ const { items } = createStoryboardFilm(board.batchId);
+ const [film, ...clips] = items;
+ expect(clips).toHaveLength(3);
+ expect(clips[0].modelId).toBe("oss-wan22-14b-fast");
+ // Start and end frame for every shot but the last.
+ expect(dependsOn(clips[0].id)).toEqual([board.items[0].id, board.items[1].id]);
+ expect(clips[0].request.chain).toEqual([{ slot: "images", position: "first" }, { slot: "endImage" }]);
+ expect(dependsOn(clips[2].id)).toEqual([board.items[2].id]);
+ expect(dependsOn(film.id)).toEqual(clips.map((c) => c.id));
+ expect(film.batchId).toBe(`${board.batchId}-film`);
+ const done = await settle(film.id, 60_000);
+ expect(done.status).toBe("succeeded");
+ const first = gens.getGeneration(clips[0].id)!;
+ expect(first.op).toBe("flf2v");
+ expect(first.request.inputs?.endImage).toBe(gens.getGeneration(board.items[1].id)!.outputs[0].url);
+ }, 70_000);
+
+ it("joins long films in rounds of four on ComfyUI", async () => {
+ const board = await createStoryboard({ engine: "open", scenes: ["1", "2", "3", "4", "5", "6"] });
+ const { batchId, items } = createStoryboardFilm(board.batchId);
+ const joins = gens.listGenerations({ batchId }).filter((g) => g.op === "concat");
+ expect(joins).toHaveLength(2);
+ // Clips 1–4 are joined first; the final join takes that plus clips 5 and 6.
+ const clips = items.filter((g) => g.op !== "concat").map((g) => g.id);
+ const final = items[0];
+ const firstRound = joins.find((j) => j.id !== final.id)!;
+ expect(dependsOn(firstRound.id)).toEqual(clips.slice(0, 4));
+ expect(dependsOn(final.id)).toEqual([firstRound.id, ...clips.slice(4)]);
+ });
+});
diff --git a/workflows/comfyui/video-concat-2.json b/workflows/comfyui/video-concat-2.json
index c893e08c..fb7cfbed 100644
--- a/workflows/comfyui/video-concat-2.json
+++ b/workflows/comfyui/video-concat-2.json
@@ -92,7 +92,10 @@
"20",
0
],
- "fps": 16,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"
diff --git a/workflows/comfyui/video-concat-3.json b/workflows/comfyui/video-concat-3.json
index 49a2cd95..1447bf8b 100644
--- a/workflows/comfyui/video-concat-3.json
+++ b/workflows/comfyui/video-concat-3.json
@@ -131,7 +131,10 @@
"20",
0
],
- "fps": 16,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"
diff --git a/workflows/comfyui/video-concat-4.json b/workflows/comfyui/video-concat-4.json
index b2d5eaae..d8290fff 100644
--- a/workflows/comfyui/video-concat-4.json
+++ b/workflows/comfyui/video-concat-4.json
@@ -170,7 +170,10 @@
"20",
0
],
- "fps": 16,
+ "fps": [
+ "2",
+ 2
+ ],
"bit_depth": "auto",
"color_space": "sRGB",
"codec": "none"