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
Keyframe film: Frames mode on the open engine renders one Wan 2.2 start/end-frame clip per pair of frames and joins them
Claude0ea1dc53c480
diff --git a/src/server/chains.ts b/src/server/chains.tsindex 5560e45b..397ba8c1 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -1,11 +1,13 @@import "server-only";import { nanoid } from "nanoid";import { getModel, supportsOp } from "@/lib/catalog";+import { frameTimes, planKeyframeClips, spread } from "@/lib/catalog/keyframes";import { routesFor } from "@/lib/catalog/plan";-import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";+import type { ChainSlot, Engine, Generation, GenerationRequest, ModelDef, ModelRoute, Operation } from "@/lib/catalog/types";import { db } from "./db";-import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained } from "./generations";+import { cancelGeneration, chooseRoute, createGenerations, getGeneration, previewChained, previewGeneration } from "./generations";import { provider } from "./providers";+import { loadManifest } from "./providers/comfyui";/*** Multi-step jobs built from chained generations: each step waits for the ones it needs and@@ -163,6 +165,75 @@ export function createShotFilm(original: GenerationRequest, model: ModelDef): Gereturn [film, ...clips];}+/**+ * Frames mode on an open model (Kling 4.0's keyframes, gap G02): one start/end-frame clip per pair of+ * neighbouring frames, each as long as the gap between them in the workflow's own frame steps, then+ * the stretch after the last frame (from it alone) when it isn't at the end, then a join. Two frames+ * at the start and the end make one clip and no join. Returns the film first, then the clips.+ */+export function createKeyframeFilm(original: GenerationRequest, model: ModelDef, route: ModelRoute): Generation[] {+ // The whole request is checked first (prompt, frame count, gaps), so no clip starts for a film that can't be made.+ previewGeneration({ ...original, op: "keyframes" });+ const images = original.inputs?.images ?? [];+ const duration = original.params?.duration ?? model.defaults?.duration ?? 5;+ const times = original.params?.keyframeTimes?.length ? original.params.keyframeTimes : frameTimes(spread(images.length), duration);+ const wf = loadManifest().workflows.find((w) => w.id === route.endpoint);+ const clips = planKeyframeClips(times, duration, {+ name: model.name,+ maxSeconds: Math.max(...(model.options.durations ?? [5])),+ fps: Number(wf?.defaults.fps ?? 16),+ step: Number(wf?.defaults.frameStep ?? 4),+ maxFrames: wf?.limits?.maxFrames,+ });+ const tail = clips.some((c) => c.to === null);+ assertOneMode([+ { label: `${model.name} clips`, modelId: model.id, op: "flf2v" },+ ...(tail ? [{ label: `${model.name} after the last frame`, modelId: model.id, op: "i2v" as const }] : []),+ ...(clips.length > 1 ? [{ label: "Joining the clips", modelId: joinModelId(model.engine), op: "concat" as const }] : []),+ ]);+ const batchId = nanoid(10);+ const params = { ...original.params };+ delete params.keyframeTimes;+ delete params.shots;+ delete params.multiShot;+ const rest = { ...original.inputs };+ delete rest.images;+ delete rest.endImage;+ const n = clips.length;+ const made: Generation[] = [];+ try {+ for (const [i, c] of clips.entries()) {+ const label = c.to === null ? `After frame ${c.from + 1}` : `Frames ${c.from + 1} → ${c.to + 1}`;+ const request: GenerationRequest = {+ ...original,+ op: c.to === null ? "i2v" : "flf2v",+ inputs: { ...rest, images: [images[c.from]], ...(c.to !== null && { endImage: images[c.to] }) },+ params: { ...params, duration: c.seconds, numOutputs: 1 },+ ...(n > 1 ? { step: { label, index: i, of: n + 1 } } : {}),+ };+ made.push(createGenerations(request, { batchId })[0]);+ }+ if (n === 1) return made;+ const film = joinClips(+ made.map((c) => c.id),+ {+ engine: model.engine,+ feature: original.feature,+ batchId,+ title: tidy(original.prompt) || "Keyframe film",+ aspectRatio: params.aspectRatio,+ resolution: params.resolution,+ step: { label: `Film · ${images.length} frames`, index: n, of: n + 1 },+ },+ );+ return [film, ...made];+ } catch (e) {+ // Don't leave half a film rendering.+ for (const g of made) void cancelGeneration(g.id);+ throw e;+ }+}+/** 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;diff --git a/src/server/generations.ts b/src/server/generations.tsindex 18fcf7d1..bc7edd97 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -8,7 +8,8 @@ import { withSignatureWords } from "@/lib/catalog/palettes";import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";import { cueText, type Cue } from "@/lib/cues";import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";-import { estimateCost, planGeneration, routesFor } from "@/lib/catalog/plan";+import { keyframeChain } from "@/lib/catalog/keyframes";+import { estimateCost, inferOperation, planGeneration, routesFor } from "@/lib/catalog/plan";import { keepMatte } from "@/lib/catalog/payload";import {LAST_FRAME_CHAIN,@@ -25,7 +26,7 @@ import {import { db } from "./db";import { listElements } from "./elements";import { pollTrainings } from "./training";-import { createExtendChain, createShotFilm } from "./chains";+import { createExtendChain, createKeyframeFilm, createShotFilm } from "./chains";import { enhancePrompt } from "./enhance";import { setResolver, watchGenerations, type LiveEvent } from "./live";import { provider } from "./providers";@@ -465,11 +466,16 @@ export function createGenerations(original: GenerationRequest, opts: CreateOptioif (!opts.dependsOn && original.op === "extend" && shotModel && routesFor(shotModel, "extend").some((r) => r.endpoint === LAST_FRAME_CHAIN)) {return createExtendChain(original, shotModel);}+ // Frames mode on an open model: one start/end-frame clip per pair of frames, then joined.+ const filmRoute = shotModel && keyframeChain(shotModel);+ if (!opts.dependsOn && filmRoute && inferOperation(shotModel, original) === "keyframes") return createKeyframeFilm(original, shotModel, filmRoute);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;+ // A chained route is built from its inputs when it's created; it can't wait for another step's output.+ if (waits && route.chained) throw new Error(`${plan.model.name} builds this from several clips of the images you add — give it uploaded images, not another step's output`);const jobs = waits ? 1 : plan.jobs;const batchId = opts.batchId ?? (jobs > 1 ? nanoid(10) : null);const now = Date.now();diff --git a/tests/chains.test.ts b/tests/chains.test.tsindex 6f6dabb8..8634e79e 100644--- a/tests/chains.test.ts+++ b/tests/chains.test.ts@@ -141,3 +141,66 @@ describe("storyboard film", () => {expect(dependsOn(final.id)).toEqual([firstRound.id, ...clips.slice(4)]);});});++describe("keyframe film (Frames mode on the open engine)", () => {+ const png = Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c63f8cfc0f01f0005000201a2e2b6a40000000049454e44ae426082", "hex");+ const frames = async (n: number) => {+ const { saveFile } = await import("@/server/storage");+ return Array.from({ length: n }, () => saveFile({ data: png, contentType: "image/png", source: "upload" }).url);+ };++ it("renders one Wan 2.2 start/end-frame clip per pair of frames, as long as each gap, then joins them", async () => {+ const images = await frames(4);+ const items = gens.createGenerations({+ feature: "video",+ modelId: "oss-wan22-14b-fast",+ op: "keyframes",+ prompt: "A paper boat drifts down the gutter",+ inputs: { images },+ params: { aspectRatio: "16:9", resolution: "480p", duration: 8, keyframeTimes: [0, 2.5, 4, 6.5] },+ });+ const [film, ...clips] = items;+ expect(film).toMatchObject({ modelId: "oss-join-clips", op: "concat" });+ expect(film.request.step?.label).toBe("Film · 4 frames");+ // Three pairs, then the 1.5 s after the last frame from that frame alone.+ expect(clips.map((c) => c.op)).toEqual(["flf2v", "flf2v", "flf2v", "i2v"]);+ expect(clips.map((c) => c.request.step?.label)).toEqual(["Frames 1 → 2", "Frames 2 → 3", "Frames 3 → 4", "After frame 4"]);+ expect(clips.map((c) => [c.request.inputs?.images, c.request.inputs?.endImage])).toEqual([+ [[images[0]], images[1]],+ [[images[1]], images[2]],+ [[images[2]], images[3]],+ [[images[3]], undefined],+ ]);+ // Seconds in Wan's 4n + 1 frame steps at 16 fps: 41, 25, 41 and 21 frames (128 in all, 8 s).+ expect(clips.map((c) => c.request.params?.duration)).toEqual([2.5, 1.5, 2.5, 1.25]);+ expect(clips.every((c) => c.request.params?.keyframeTimes === undefined && c.batchId === film.batchId)).toBe(true);+ expect(dependsOn(film.id)).toEqual(clips.map((c) => c.id));+ expect(film.costUsd).toBe(0);+ expect((await settle(film.id, 60_000)).status).toBe("succeeded");+ }, 70_000);++ it("makes one clip and no join for a start and an end frame", async () => {+ const images = await frames(2);+ const items = gens.createGenerations({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "dawn breaks", inputs: { images }, params: { duration: 5, keyframeTimes: [0, 5] } });+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ op: "flf2v", modelId: "oss-wan22-14b-fast" });+ expect(items[0].request.inputs).toEqual({ images: [images[0]], endImage: images[1] });+ expect(items[0].request.step).toBeUndefined();+ });++ it("checks the whole film before any clip starts", async () => {+ const images = await frames(3);+ const before = gens.listGenerations({ limit: 500 }).length;+ expect(() =>+ gens.createGenerations({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "x", inputs: { images }, params: { duration: 10, keyframeTimes: [0, 2, 9] } }),+ ).toThrow(/Frames 2 and 3 are 7 s apart/);+ expect(() => gens.createGenerations({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "", inputs: { images }, params: { duration: 5, keyframeTimes: [0, 2, 5] } })).toThrow(/prompt/);+ expect(gens.listGenerations({ limit: 500 }).length).toBe(before);+ });++ it("refuses to wait for another step's images", () => {+ expect(() =>+ gens.createGenerations({ feature: "canvas", modelId: "oss-wan22-14b-fast", op: "keyframes", prompt: "x", chain: [{ slot: "images" }, { slot: "images" }] }, { dependsOn: ["a", "b"] }),+ ).toThrow(/uploaded images, not another step's output/);+ });+});diff --git a/tests/keyframes-comfy.test.ts b/tests/keyframes-comfy.test.tsnew file mode 100644index 00000000..ed3b1a30--- /dev/null+++ b/tests/keyframes-comfy.test.ts@@ -0,0 +1,50 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, describe, expect, it } from "vitest";+import type { GenInput, Operation } from "@/lib/catalog/types";+import { keyframeChain, planKeyframeClips } from "@/lib/catalog/keyframes";++// The open keyframe film's clips through the comfyui provider: each pair's start and end frames and its+// frame count land in the Wan 2.2 start/end-frame graph exactly as the per-pair plan counted them.+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-keyframes-comfy-"));+process.env.FUOBE_DATA_DIR = tmp;+process.env.COMFYUI_URL = "http://comfy.test:8188";+const { getWorkflow, prepareWorkflow } = await import("@/server/providers/comfyui");+const { getModel } = await import("@/lib/catalog");+afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));++const prepare = (id: string, input: Partial<GenInput>, op: Operation) =>+ prepareWorkflow(id, { prompt: "a paper boat", aspectRatio: "16:9", resolution: "480p", ...input } as GenInput, { generationId: "g1", op, upload: async (_d, _t, name) => `up_${name}` });+const at = (wf: Record<string, { inputs: Record<string, unknown> }>, node: string, input: string) => wf[node]?.inputs[input];++describe("keyframe film clips on ComfyUI", () => {+ it("chains the model's own start/end-frame workflow, with its fps and frame step", () => {+ const route = keyframeChain(getModel("oss-wan22-14b-fast")!)!;+ expect(route).toMatchObject({ provider: "comfyui", endpoint: "wan22-flf2v-14b", chained: true });+ const { manifest } = getWorkflow(route.endpoint);+ expect(manifest.capability).toBe("flf2v");+ expect([manifest.defaults.fps, manifest.defaults.frameStep, manifest.limits?.maxFrames]).toEqual([16, 4, 121]);+ });++ it("binds each pair's frames and its frame count", async () => {+ const { manifest } = getWorkflow("wan22-flf2v-14b");+ const clips = planKeyframeClips([0, 1.3, 4, 7.7], 10, { name: "Wan 2.2 14B", maxSeconds: 7, fps: 16, step: 4, maxFrames: manifest.limits?.maxFrames });+ const frames = ["a.png", "b.png", "c.png", "d.png"];+ for (const c of clips.filter((x) => x.to !== null)) {+ const { workflow: wf } = await prepare("wan22-flf2v-14b", { images: [frames[c.from]], endImage: frames[c.to!], duration: c.seconds }, "flf2v");+ expect(at(wf, "81", "length"), `clip ${c.from + 1} → ${c.to! + 1}`).toBe(c.frames);+ expect(String(at(wf, "80", "image"))).toContain(frames[c.from].replace(".png", ""));+ expect(String(at(wf, "89", "image"))).toContain(frames[c.to!].replace(".png", ""));+ expect(at(wf, "86", "fps")).toBe(16);+ }+ expect(clips.map((c) => c.frames)).toEqual([21, 45, 57, 37]);+ // The stretch after the last frame runs on the image-to-video graph from that frame alone.+ const tail = clips.at(-1)!;+ expect(tail.to).toBeNull();+ const i2v = getModel("oss-wan22-14b-fast")!.routes.find((r) => r.op === "i2v")!.endpoint;+ const { workflow: wf, manifest: m } = await prepare(i2v, { images: ["d.png"], duration: tail.seconds }, "i2v");+ const lengthAt = m.bindings.frames![0];+ expect(at(wf, lengthAt.node, lengthAt.input)).toBe(tail.frames);+ });+});