The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Chains: a slot can take a step's output number i, so one step fans out over a list of frames and another gathers them back
Claudebd3539a2326e
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex a4ca85b1..e6fb9649 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -696,6 +696,8 @@ export interface GenerationRequest {chainFrom?: "first" | "last";/** Chained jobs with several dependencies: where each one's first output goes, in dependsOn order. */chain?: ChainSlot[];+ /** Server-set when the runner filled the chain slots from the earlier steps' outputs (a retry takes them out again: unfilledRequest). */+ chainFilled?: boolean;/** 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. */@@ -732,6 +734,14 @@ export interface ChainSlot {* accompaniment/instrumental/residual/no_vocals). Without it, the first output of the slot's kind.*/stem?: string;+ /**+ * Fan-out from a step that makes a list (extract-frames: one image per frame): take the dependency's+ * output number `index` of the slot's kind (0-based, by `meta.index` when the outputs carry it). Past+ * the end it takes the last one, so a provider that returns a frame fewer than planned holds the last+ * frame instead of failing the whole render. One step per index fans a list out; a step with one slot+ * per index gathers it back in order.+ */+ index?: number;}/** Canonical, provider-ready input (asset refs already resolved to provider URLs/filenames). */diff --git a/src/server/chains.ts b/src/server/chains.tsindex 1b5d989e..7b423261 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -313,20 +313,20 @@ const asList = (a: string | string[] | undefined) => (a === undefined ? [] : Arr/** Chain slots that take an audio output (and so may pick a stem). */const AUDIO_SLOTS = new Set<ChainSlot["slot"]>(["audio", "voiceAudio", "audio2"]);-/** Kahn's algorithm: steps in an order where every `after` comes first; throws on a cycle. */+/** Kahn's algorithm: steps in an order where every `after` comes first; throws on a cycle. Linear in steps + edges (a per-frame render has hundreds). */function topoOrder(steps: PipelineStep[]): PipelineStep[] {- const byKey = new Map(steps.map((s) => [s.key, s]));const indegree = new Map(steps.map((s) => [s.key, new Set(asList(s.after)).size]));+ const next = new Map<string, PipelineStep[]>();+ for (const t of steps) for (const a of new Set(asList(t.after))) next.set(a, [...(next.get(a) ?? []), t]);const ready = steps.filter((s) => indegree.get(s.key) === 0);const out: PipelineStep[] = [];- while (ready.length) {- const s = ready.shift()!;+ for (let i = 0; i < ready.length; i++) {+ const s = ready[i];out.push(s);- for (const t of steps) {- if (!new Set(asList(t.after)).has(s.key)) continue;+ for (const t of next.get(s.key) ?? []) {const n = indegree.get(t.key)! - 1;indegree.set(t.key, n);- if (n === 0) ready.push(byKey.get(t.key)!);+ if (n === 0) ready.push(t);}}if (out.length < steps.length) {@@ -344,7 +344,8 @@ function topoOrder(steps: PipelineStep[]): PipelineStep[] {** A chain slot takes the first output of its kind from the step it names, or with `stem` the* audio output whose `meta.stem` matches — that's how one separate-audio step feeds both the voice- * to clone and the background to mix back in.+ * to clone and the background to mix back in — or with `index` its output number i: one step per+ * index fans a list out (a step per extracted frame), one step with a slot per index gathers it back.** @example Dub a clip into Spanish in the speaker's own voice, over the original music and effects* ```ts@@ -386,6 +387,8 @@ export function createPipeline(steps: PipelineStep[], opts: PipelineOptions = {}if (chain && chain.length !== after.length) throw new Error(`Step “${s.key}” has ${chain.length} chain slot${chain.length === 1 ? "" : "s"} for ${after.length} earlier step${after.length === 1 ? "" : "s"}`);const stray = chain?.find((c) => c.stem && !AUDIO_SLOTS.has(c.slot));if (stray) throw new Error(`Step “${s.key}”: a stem (“${stray.stem}”) only goes into an audio slot, not “${stray.slot}”`);+ const badIndex = chain?.find((c) => c.index !== undefined && !(Number.isInteger(c.index) && c.index >= 0));+ if (badIndex) throw new Error(`Step “${s.key}”: an output number must be a whole number from 0 (got ${badIndex.index})`);}const ordered = topoOrder(steps);const n = steps.length;diff --git a/src/server/generations.ts b/src/server/generations.tsindex 48eb52f1..b2dc9bfc 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -568,6 +568,12 @@ export function pickOutput(outputs: OutputFile[], s: ChainSlot): OutputFile | un// A mask: the output made as one (meta.role "mask": a painted window's last tracked frame), else a mask video, else a still.if (s.slot === "mask") return outputs.find((o) => o.meta?.role === "mask") ?? outputs.find((o) => o.kind === "video") ?? outputs.find((o) => o.kind === "image");const ofKind = outputs.filter((o) => o.kind === SLOT_KIND[s.slot]);+ if (s.index !== undefined) {+ if (!ofKind.length) return undefined;+ const at = (o: OutputFile, i: number) => (typeof o.meta?.index === "number" ? o.meta.index : i);+ const ordered = ofKind.map((o, i) => ({ o, i: at(o, i) })).sort((a, b) => a.i - b.i);+ return (ordered.find((x) => x.i === s.index) ?? ordered[Math.min(s.index, ordered.length - 1)]).o;+ }if (!s.stem) return ofKind[0] ?? (SOUNDTRACK_SLOTS.has(s.slot) ? outputs.find((o) => o.kind === "video") : undefined);const want = STEM_ALIASES[s.stem.toLowerCase()] ?? [s.stem.toLowerCase()];return ofKind.find((o) => typeof o.meta?.stem === "string" && want.includes(o.meta.stem.toLowerCase()));@@ -622,6 +628,28 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generatreturn { ...req, prompt, inputs };}+/**+ * A stored step as it was before the runner filled its chain slots (`chainFilled`): the chained list+ * items come out from the front ("first") and the back ("last"), single slots are emptied, and the+ * step's own items stay. A retry rebuilds the step from new dependencies this way. Text that filled a+ * "prompt" slot can't be told from the prompt, so it stays.+ */+export function unfilledRequest(req: GenerationRequest, deps: number): GenerationRequest {+ const { chainFilled, ...rest } = req;+ if (!chainFilled) return rest;+ const slots = slotsFor(rest, deps);+ const inputs = { ...rest.inputs };+ for (const k of ["images", "videos", "audios"] as const) {+ const count = (pos: "first" | "last") => slots.filter((s) => s.slot === k && (s.position ?? "last") === pos).length;+ const list = inputs[k] ?? [];+ const own = list.slice(count("first"), list.length - count("last"));+ if (own.length) inputs[k] = own;+ else delete inputs[k];+ }+ for (const s of slots) if (s.slot !== "images" && s.slot !== "videos" && s.slot !== "audios" && s.slot !== "prompt") delete inputs[s.slot];+ return { ...rest, inputs: Object.keys(inputs).length ? inputs : undefined };+}+/** Generations this process is handing to a provider right now (shared across hot reloads and bundles). */declare global {var __fuobeSubmitting: Set<string> | undefined;@@ -677,7 +705,7 @@ async function advanceDependents(): Promise<void> {const model = getModel(request.modelId);if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();- const original = withChainInputs(request, values as string[]);+ const original: GenerationRequest = { ...withChainInputs(request, values as string[]), chainFilled: true };const prepared = prepare(original);const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);if (mode.error) throw new Error(mode.error);diff --git a/tests/chain-fanout.test.ts b/tests/chain-fanout.test.tsnew file mode 100644index 00000000..9cfd83b1--- /dev/null+++ b/tests/chain-fanout.test.ts@@ -0,0 +1,152 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";+import type { Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";++// The per-index chain slot (ChainSlot.index): one step per output of a list-making step (fan-out),+// and one step with a slot per index that gathers them back in order (fan-in).++vi.setConfig({ testTimeout: 90_000 });++const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-fanout-"));+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://127.0.0.1:9";+process.env.OLLAMA_URL = "http://127.0.0.1:9";++const { setSetting } = await import("@/server/settings");+const gens = await import("@/server/generations");+const { createPipeline } = await import("@/server/chains");+const { saveFile } = await import("@/server/storage");+const { db } = await import("@/server/db");++beforeAll(() => setSetting("demoMode", "auto"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));++async function settle(id: string, ms = 80_000): Promise<Generation> {+ const end = Date.now() + ms;+ for (;;) {+ const g = gens.getGeneration(id)!;+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);+ await new Promise((r) => setTimeout(r, 250));+ }+}++const count = () => (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;++describe("pickOutput with an index", () => {+ const frames: OutputFile[] = [+ { url: "/api/files/f2.png", kind: "image", meta: { index: 2 } },+ { url: "/api/files/f0.png", kind: "image", meta: { index: 0 } },+ { url: "/api/files/clip.mp4", kind: "video" },+ { url: "/api/files/f1.png", kind: "image", meta: { index: 1 } },+ ];++ it("takes output number i of the slot's kind, by meta.index", () => {+ expect(gens.pickOutput(frames, { slot: "images", index: 0 })?.url).toBe("/api/files/f0.png");+ expect(gens.pickOutput(frames, { slot: "images", index: 1 })?.url).toBe("/api/files/f1.png");+ expect(gens.pickOutput(frames, { slot: "images", index: 2 })?.url).toBe("/api/files/f2.png");+ expect(gens.pickOutput(frames, { slot: "video", index: 0 })?.url).toBe("/api/files/clip.mp4");+ });++ it("goes by position when the outputs carry no index, and holds the last one past the end", () => {+ const plain: OutputFile[] = [+ { url: "/a.png", kind: "image" },+ { url: "/b.png", kind: "image" },+ ];+ expect(gens.pickOutput(plain, { slot: "images", index: 1 })?.url).toBe("/b.png");+ expect(gens.pickOutput(plain, { slot: "images", index: 7 })?.url).toBe("/b.png");+ expect(gens.pickOutput(frames, { slot: "images", index: 40 })?.url).toBe("/api/files/f2.png");+ expect(gens.pickOutput([{ url: "/c.mp4", kind: "video" }], { slot: "images", index: 0 })).toBeUndefined();+ });+});++describe("fan-out and fan-in in createPipeline", () => {+ const clip = () => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/demo-landscape.mp4")), contentType: "video/mp4", source: "upload" }).url;++ it("refuses an output number that isn't a whole number from 0, before creating anything", () => {+ const before = count();+ for (const index of [-1, 1.5]) {+ expect(() =>+ createPipeline([+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames", inputs: { video: "/api/files/a.mp4" } } },+ { key: "f0", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "ink" }, after: "frames", chain: [{ slot: "images", index }] },+ ]),+ ).toThrow(/Step “f0”: an output number must be a whole number from 0/);+ }+ expect(count()).toBe(before);+ });++ it("restyles every extracted frame with the previous styled frame as a reference, then rebuilds the clip in order", async () => {+ const n = 5; // the demo extractor returns 4 frames: frame 5 holds the last one+ const steps = [+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames" as const, inputs: { video: clip() }, params: { frameInterval: 3 } } },+ ...Array.from({ length: n }, (_, i) => ({+ key: `f${i}`,+ request: { feature: "t", modelId: "nano-banana-2", op: "edit" as const, prompt: "Ink sketch", params: { seed: 7 } },+ after: i ? ["frames", `f${i - 1}`] : ["frames"],+ chain: i ? [{ slot: "images" as const, index: i, position: "first" as const }, { slot: "images" as const }] : [{ slot: "images" as const, index: i }],+ })),+ {+ key: "film",+ request: { feature: "t", modelId: "images-to-video", op: "images-to-video" as const, params: { fps: 8 } },+ after: Array.from({ length: n }, (_, i) => `f${i}`),+ chain: Array.from({ length: n }, () => ({ slot: "images" as const })),+ },+ ];+ const p = createPipeline(steps);+ expect(p.items.map((g) => g.op)).toEqual(["extract-frames", ...Array(n).fill("edit"), "images-to-video"]);++ const film = await settle(p.byKey.film.id);+ expect(film.status, film.error ?? "").toBe("succeeded");+ const frames = gens.getGeneration(p.byKey.frames.id)!.outputs;+ expect(frames).toHaveLength(4);+ const styled = Array.from({ length: n }, (_, i) => gens.getGeneration(p.byKey[`f${i}`].id)!);+ expect(styled[0].request.inputs?.images).toEqual([frames[0].url]);+ for (let i = 1; i < n; i++) expect(styled[i].request.inputs?.images).toEqual([frames[Math.min(i, 3)].url, styled[i - 1].outputs[0].url]);+ expect(styled.every((g) => g.request.params?.seed === 7 && g.request.chainFilled)).toBe(true);+ // Gathered back in frame order.+ expect(film.request.inputs?.images).toEqual(styled.map((g) => g.outputs[0].url));+ });++ it("takes the filled inputs out again for a retry, keeping the step's own", () => {+ const filled: GenerationRequest = {+ feature: "t",+ modelId: "nano-banana-2",+ op: "edit",+ inputs: { images: ["/frame3.png", "/own-anchor.png", "/styled2.png"], video: "/cut.mp4" },+ chain: [{ slot: "images", index: 3, position: "first" }, { slot: "images" }, { slot: "video" }],+ chainFilled: true,+ };+ const { chainFilled, ...waiting } = filled;+ expect(chainFilled).toBe(true);+ expect(gens.unfilledRequest(filled, 3)).toEqual({ ...waiting, inputs: { images: ["/own-anchor.png"] } });+ // Never filled (it never launched): unchanged.+ expect(gens.unfilledRequest(waiting, 3)).toEqual(waiting);+ // Nothing of its own: no inputs left.+ expect(gens.unfilledRequest({ feature: "t", modelId: "images-to-video", inputs: { images: ["/a.png", "/b.png"] }, chain: [{ slot: "images" }, { slot: "images" }], chainFilled: true }, 2).inputs).toBeUndefined();+ });++ it("orders and validates a few hundred steps quickly", () => {+ const n = 240;+ const steps = [+ { key: "frames", request: { feature: "t", modelId: "extract-frames", op: "extract-frames" as const, inputs: { video: "/api/files/a.mp4" } } },+ ...Array.from({ length: n }, (_, i) => ({+ key: `f${i}`,+ request: { feature: "t", modelId: "nano-banana-2", op: "edit" as const, prompt: "Ink" },+ after: i % 12 ? ["frames", `f${i - 1}`] : ["frames"],+ chain: i % 12 ? [{ slot: "images" as const, index: i, position: "first" as const }, { slot: "images" as const }] : [{ slot: "images" as const, index: i }],+ })),+ ];+ const t = performance.now();+ const p = createPipeline(steps);+ const ms = performance.now() - t;+ expect(p.items).toHaveLength(n + 1);+ // Each lane waits for the frame before it; lanes start together.+ const at = new Map(p.items.map((g, i) => [g.id, i]));+ for (let i = 1; i < n; i++) if (i % 12) expect(at.get(p.byKey[`f${i}`].id)!).toBeGreaterThan(at.get(p.byKey[`f${i - 1}`].id)!);+ expect(ms).toBeLessThan(15_000);+ for (const g of p.items) void gens.cancelGeneration(g.id);+ });+});