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.

Keyframes: up to 10 frames with times, what each model does with them, and Wan 2.2 14B takes them on the open engine

Claude9b47f7b03c06
diff --git a/src/lib/catalog/keyframes.ts b/src/lib/catalog/keyframes.ts
new file mode 100644
index 00000000..936f7906
--- /dev/null
+++ b/src/lib/catalog/keyframes.ts
@@ -0,0 +1,243 @@
+/**
+ * Frames mode (Kling 4.0's "Frames", Higgsfield gap G02): up to 10 stills, each at its own time in
+ * the clip, the first one the start frame. Pure logic shared by the Video studio composer, the
+ * planner and the open engine's keyframe film (src/server/chains.ts createKeyframeFilm):
+ *
+ * - Frame positions are kept as fractions of the clip (0 = start, 1 = end), so a longer or shorter
+ * clip stretches them; they become seconds, snapped to 0.1 s, only when shown or sent.
+ * - What a model does with them: every frame at its time (FLUX 3 Max keyframes-to-video, or the
+ * open engine's chain of start/end-frame clips), only the first and the last (start + end frame
+ * models such as Kling O3), or nothing (start-frame-only and text-only models: a blocker).
+ * - The open plan: 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 (Wan 2.2: n·4 + 1 frames at 16 fps), then joined.
+ *
+ * No catalog import (types only), so the composer can use it in the browser.
+ */
+import type { Engine, ModelDef, ModelRoute } from "./types";
+
+/** Kling 4.0 and FLUX 3 Max take up to 10 frames. */
+export const MAX_KEYFRAMES = 10;
+/** Frame times snap to a tenth of a second. */
+export const KEYFRAME_SNAP = 0.1;
+/** The open chain's shortest clip between two frames (a start/end-frame clip under half a second is a jump cut). */
+export const OPEN_MIN_GAP = 0.5;
+/** Clip lengths the open chain offers in Frames mode (it joins as many clips as the frames need). */
+export const CHAIN_DURATIONS = [3, 5, 8, 10, 15, 20, 30];
+
+export const FRAMES_HINT = "Up to 10 frames. The first is the start frame.";
+
+const EPS = 1e-6;
+const snap = (s: number) => Math.round(s / KEYFRAME_SNAP) * KEYFRAME_SNAP;
+const round1 = (s: number) => Math.round(s * 10) / 10;
+/** "2.5 s", "3 s". */
+export const secondsLabel = (s: number) => `${round1(s).toFixed(round1(s) % 1 ? 1 : 0)} s`;
+
+// ---------------------------------------------------------------------------
+// What a model does with frames
+
+/** "all": every frame at its time · "ends": the first and the last only · "start": the first only · "none": no frames. */
+export type FrameSupport = "all" | "ends" | "start" | "none";
+
+/** A ComfyUI keyframes route that runs as a chain of its start/end-frame workflow (one clip per pair, joined). */
+export function keyframeChain(model: Pick<ModelDef, "routes">): ModelRoute | undefined {
+ return model.routes.find((r) => r.op === "keyframes" && r.chained);
+}
+
+export function frameSupport(model: Pick<ModelDef, "routes" | "options">): FrameSupport {
+ const ops = new Set(model.routes.map((r) => r.op));
+ if (ops.has("keyframes")) return "all";
+ if (ops.has("flf2v") || (ops.has("i2v") && model.options.endFrame)) return "ends";
+ return ops.has("i2v") ? "start" : "none";
+}
+
+/** The model to suggest for every frame on each engine (it must be in the Video studio's list). */
+export const FRAMES_MODELS: Record<Engine, { id: string; name: string }> = {
+ cloud: { id: "flux-3-max", name: "FLUX 3 Max" },
+ open: { id: "oss-wan22-14b-fast", name: "Wan 2.2 14B Lightning" },
+};
+
+/** What stops Generate in Frames mode before the planner speaks: no start frame, or a model that can't follow frames. */
+export function framesBlocker(model: Pick<ModelDef, "name" | "engine" | "routes" | "options">, count: number): { message: string; slot?: "frames" } | null {
+ const support = frameSupport(model);
+ const alt = FRAMES_MODELS[model.engine].name;
+ if (support === "start") return { message: `${model.name} takes a start frame only — pick ${alt} to follow your frames, or turn Frames off` };
+ if (support === "none") return { message: `${model.name} can't start from frames — pick ${alt}, or turn Frames off` };
+ if (!count) return { message: "Add the start frame", slot: "frames" };
+ return null;
+}
+
+/**
+ * The line under the strip: what the model will do with the frames (said before anything runs).
+ * Null when every frame is used as placed.
+ */
+export function framesNote(model: Pick<ModelDef, "name" | "engine" | "routes" | "options">, count: number, lastAt = 1): string | null {
+ const support = frameSupport(model);
+ if (support !== "ends" || count < 2) return null;
+ const alt = FRAMES_MODELS[model.engine].name;
+ if (count > 2) {
+ const middle = count - 2;
+ return `${model.name} takes a start and an end frame, so it uses frames 1 and ${count} and leaves out the ${middle === 1 ? "middle one" : `${middle} in between`} — ${alt} follows every frame.`;
+ }
+ return lastAt < 1 - EPS ? `${model.name} puts the last frame at the end of the clip — ${alt} keeps it at its time.` : null;
+}
+
+/** Clip lengths to offer in Frames mode: the open chain's own list, else the model's. */
+export function framesDurations(model: Pick<ModelDef, "routes" | "options">): number[] {
+ if (keyframeChain(model)) return CHAIN_DURATIONS;
+ return model.options.durations?.length ? model.options.durations : [5];
+}
+
+/** The clip length Frames mode uses: the one asked for when the model offers it, else the nearest it does. */
+export function framesDuration(model: Pick<ModelDef, "routes" | "options" | "defaults">, asked: number | undefined): number {
+ const list = framesDurations(model);
+ const want = asked ?? model.defaults?.duration ?? list[0];
+ return list.reduce((best, d) => (Math.abs(d - want) < Math.abs(best - want) ? d : best), list[0]);
+}
+
+// ---------------------------------------------------------------------------
+// Positions (fractions of the clip)
+
+/** n frames spread evenly from the start to the end. */
+export function spread(n: number): number[] {
+ if (n <= 0) return [];
+ if (n === 1) return [0];
+ return Array.from({ length: n }, (_, i) => i / (n - 1));
+}
+
+const isSpread = (ats: number[]) => ats.length > 1 && spread(ats.length).every((x, i) => Math.abs(x - ats[i]) < 0.005);
+
+/**
+ * Where the frames sit after one more is added at the end: evenly spaced frames stay evenly spaced
+ * (start, then end, then the middle); frames you placed keep their places and the new one goes at
+ * the end (the old last frame steps to halfway when it was there already).
+ */
+export function addFrameAt(ats: number[]): number[] {
+ const n = ats.length;
+ if (n === 0) return [0];
+ if (n === 1 || isSpread(ats)) return spread(n + 1);
+ if (ats[n - 1] < 1 - EPS) return [...ats, 1];
+ return [...ats.slice(0, -1), (ats[n - 2] + 1) / 2, 1];
+}
+
+/** Where the frames sit after frame i goes: evenly spaced ones re-space; the first is always the start frame. */
+export function removeFrameAt(ats: number[], i: number): number[] {
+ const left = ats.filter((_, j) => j !== i);
+ if (isSpread(ats)) return spread(left.length);
+ if (left.length) left[0] = 0;
+ return left;
+}
+
+/**
+ * The frames as seconds in a clip of `duration`: snapped to 0.1 s, the first at 0, each at least
+ * 0.1 s after the one before and none past the end (frames squeezed at the end step back).
+ */
+export function frameTimes(ats: number[], duration: number): number[] {
+ const out = ats.map((a, i) => (i === 0 ? 0 : round1(snap(Math.max(0, Math.min(1, a)) * duration))));
+ for (let i = 1; i < out.length; i++) out[i] = round1(Math.max(out[i], out[i - 1] + KEYFRAME_SNAP));
+ for (let i = out.length - 1; i > 0; i--) out[i] = round1(Math.min(out[i], i === out.length - 1 ? duration : out[i + 1] - KEYFRAME_SNAP));
+ return out;
+}
+
+/** The range frame i can be dragged in (s): after the frame before it, before the next (or the clip's end). The first never moves. */
+export function frameRange(times: number[], i: number, duration: number): [number, number] {
+ if (i <= 0) return [0, 0];
+ const lo = round1(times[i - 1] + KEYFRAME_SNAP);
+ const hi = round1(i === times.length - 1 ? duration : times[i + 1] - KEYFRAME_SNAP);
+ return [lo, Math.max(lo, hi)];
+}
+
+/** Frame i moved to `seconds` (snapped to 0.1 s and kept between its neighbours), as new positions. */
+export function moveFrameAt(ats: number[], i: number, seconds: number, duration: number): number[] {
+ if (i <= 0 || i >= ats.length || duration <= 0) return ats;
+ const times = frameTimes(ats, duration);
+ const [lo, hi] = frameRange(times, i, duration);
+ const t = round1(Math.min(hi, Math.max(lo, snap(seconds))));
+ return ats.map((a, j) => (j === i ? t / duration : j === 0 ? 0 : times[j] / duration));
+}
+
+/** Positions back from seconds (Reuse of a keyframes run). */
+export function positionsFrom(times: number[], duration: number): number[] {
+ return times.map((t, i) => (i === 0 || duration <= 0 ? 0 : Math.max(0, Math.min(1, t / duration))));
+}
+
+/**
+ * The inputs Frames mode sends for the model: every frame with its time, the first and the last as
+ * start and end frame, or the start frame alone. One frame is a plain image-to-video start.
+ */
+export function framesInputs(refs: string[], times: number[], support: FrameSupport): { images?: string[]; endImage?: string; keyframeTimes?: number[] } {
+ if (!refs.length) return {};
+ if (refs.length === 1 || support === "start" || support === "none") return { images: [refs[0]] };
+ if (support === "ends") return { images: [refs[0]], endImage: refs[refs.length - 1] };
+ return { images: refs, keyframeTimes: times };
+}
+
+// ---------------------------------------------------------------------------
+// Checks and the open engine's plan
+
+export interface ChainTiming {
+ /** The model's name, for messages. */
+ name: string;
+ /** The longest clip the model makes between two frames (s). */
+ maxSeconds: number;
+ /** The shortest (s). */
+ minSeconds?: number;
+}
+
+/**
+ * The open chain's rule for the gaps: each pair of neighbouring frames (and the stretch after the
+ * last frame, when it isn't at the end) is one clip the model can make. Returns the message for the
+ * first gap that doesn't fit, or null.
+ */
+export function chainGapProblem(times: number[], duration: number, t: ChainTiming): string | null {
+ const min = t.minSeconds ?? OPEN_MIN_GAP;
+ for (let i = 1; i < times.length; i++) {
+ const gap = round1(times[i] - times[i - 1]);
+ if (gap > t.maxSeconds + EPS) return `Frames ${i} and ${i + 1} are ${secondsLabel(gap)} apart — ${t.name} makes up to ${secondsLabel(t.maxSeconds)} between two frames. Move them closer or add a frame between them`;
+ if (gap < min - EPS) return `Frames ${i} and ${i + 1} are only ${secondsLabel(gap)} apart — keep at least ${secondsLabel(min)} between frames on ${t.name}`;
+ }
+ const tail = round1(duration - (times[times.length - 1] ?? 0));
+ if (times.length > 1 && tail > t.maxSeconds + EPS) return `The clip runs ${secondsLabel(tail)} past the last frame — ${t.name} makes up to ${secondsLabel(t.maxSeconds)} from one frame. Move the last frame later or make the clip shorter`;
+ return null;
+}
+
+export interface KeyframeClip {
+ /** The frame the clip starts on. */
+ from: number;
+ /** The frame it ends on, or null for the stretch after the last frame (from that frame alone). */
+ to: number | null;
+ /** Frames in the clip (n·step + 1, the workflow's own count) and the seconds to ask for ((frames − 1) / fps). */
+ frames: number;
+ seconds: number;
+}
+
+/**
+ * One start/end-frame clip per pair of neighbouring frames, then the stretch after the last frame
+ * when it isn't at the end (shorter than the minimum: the film ends on the last frame). Each clip's
+ * last frame is the next one's first, so frame k lands on the film's frame Σ(earlier clips) − 1;
+ * the counts are chosen against the film's running total, so the frames stay on their times within
+ * half a frame step (Wan 2.2: ±2 frames at 16 fps) however many clips there are.
+ */
+export function planKeyframeClips(times: number[], duration: number, t: ChainTiming & { fps: number; step: number; maxFrames?: number }): KeyframeClip[] {
+ if (times.length < 2) throw new Error("A keyframe film needs at least two frames");
+ const problem = chainGapProblem(times, duration, t);
+ if (problem) throw new Error(problem);
+ const min = t.minSeconds ?? OPEN_MIN_GAP;
+ const cap = Math.min(t.maxFrames ?? Infinity, Math.round(t.maxSeconds * t.fps) + 1);
+ const fit = (want: number) => {
+ let n = Math.max(t.step + 1, Math.round((want - 1) / t.step) * t.step + 1);
+ while (n > cap) n -= t.step;
+ return n;
+ };
+ const stops = [...times];
+ if (duration - times[times.length - 1] >= min - EPS) stops.push(duration);
+ const clips: KeyframeClip[] = [];
+ let total = 0;
+ for (let i = 1; i < stops.length; i++) {
+ // The film's frame count once this clip is in: its last frame (the next frame) sits at stops[i].
+ const target = Math.round(stops[i] * t.fps) + 1;
+ const frames = fit(target - total);
+ total += frames;
+ clips.push({ from: i - 1, to: i < times.length ? i : null, frames, seconds: Math.round(((frames - 1) / t.fps) * 1e4) / 1e4 });
+ }
+ return clips;
+}
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 6ab3bd22..f53e6055 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -25,6 +25,12 @@ const CHATTERBOX_SLIDERS = [
{ param: "temperature", label: "Variety", min: 0.05, max: 2, step: 0.05, default: 0.8 },
];
+/**
+ * Frames mode on the open engine (Kling 4.0's up to 10 keyframes): one Wan 2.2 start/end-frame clip
+ * per pair of frames, as long as the gap between them, then joined (createKeyframeFilm in src/server/chains.ts).
+ */
+const KEYFRAME_FILM: ModelRoute = { ...comfy("keyframes", "wan22-flf2v-14b", "one start/end-frame clip per pair of frames, joined"), chained: true };
+
/** 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;
@@ -254,7 +260,7 @@ const open: ModelDef[] = [
kind: "video",
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")],
+ routes: [comfy("t2v", "wan22-t2v-14b-lightx2v", "Lightx2v 4-step"), comfy("i2v", "wan22-i2v-14b-lightx2v", "Lightx2v 4-step"), comfy("flf2v", "wan22-flf2v-14b"), KEYFRAME_FILM],
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" },
}),
@@ -265,7 +271,7 @@ const open: ModelDef[] = [
family: "wan",
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")],
+ routes: [comfy("t2v", "wan22-t2v-14b"), comfy("i2v", "wan22-i2v-14b"), comfy("flf2v", "wan22-flf2v-14b"), KEYFRAME_FILM],
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" },
}),
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index f5e2e698..1fdb95a5 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -10,6 +10,7 @@ import type {
PresetRoute,
Pricing,
} from "./types";
+import { chainGapProblem, frameTimes, keyframeChain, MAX_KEYFRAMES, spread } from "./keyframes";
/** Infer the operation from what the user attached. */
export function inferOperation(model: ModelDef, req: Pick<GenerationRequest, "op" | "inputs" | "params">): Operation {
@@ -286,17 +287,27 @@ function checkVideoToolOptions(model: ModelDef, op: "bg-remove-video" | "depth-v
if (params.sideBySide && !o.sideBySide) throw new Error(`${model.name} can't put the original next to the depth map`);
}
-/** Keyframes: one time per image, from 0 up, inside the clip, no more than the model takes. */
+/**
+ * Keyframes: one time per image, from 0 up, inside the clip, no more than the model takes. The open
+ * chain (one start/end-frame clip per pair) also needs every gap to be a clip its model can make.
+ */
function checkKeyframes(model: ModelDef, n: number, params: GenParams) {
- const max = model.options.maxImages;
+ const chain = keyframeChain(model);
+ const max = chain ? MAX_KEYFRAMES : model.options.maxImages;
if (max && n > max) throw new Error(`${model.name} takes up to ${max} keyframes`);
const times = params.keyframeTimes;
- if (!times?.length) return;
- if (times.length !== n) throw new Error(`Give each of the ${n} keyframes a time`);
- if (times.some((t, i) => !Number.isFinite(t) || t < 0 || (i > 0 && t <= times[i - 1]))) throw new Error("Keyframe times start at 0 or later and go up");
const duration = params.duration ?? model.defaults?.duration;
- const last = times[times.length - 1];
- if (duration !== undefined && last > duration) throw new Error(`The last keyframe is at ${last}s — make the clip at least that long`);
+ if (times?.length) {
+ if (times.length !== n) throw new Error(`Give each of the ${n} keyframes a time`);
+ if (times.some((t, i) => !Number.isFinite(t) || t < 0 || (i > 0 && t <= times[i - 1]))) throw new Error("Keyframe times start at 0 or later and go up");
+ const last = times[times.length - 1];
+ if (duration !== undefined && last > duration) throw new Error(`The last keyframe is at ${last}s — make the clip at least that long`);
+ }
+ if (chain && n > 1) {
+ const length = duration ?? 5;
+ const problem = chainGapProblem(times?.length ? times : frameTimes(spread(n), length), length, { name: model.name, maxSeconds: Math.max(...(model.options.durations ?? [5])) });
+ if (problem) throw new Error(problem);
+ }
}
type InputKey = keyof NonNullable<GenerationRequest["inputs"]>;
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index e7e40732..64a15ec1 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -434,6 +434,11 @@ export interface ModelRoute {
note?: string;
/** Same model with LoRA support (fal's `/lora` variants): used when a trained identity is mentioned. */
loraEndpoint?: string;
+ /**
+ * The route runs as several jobs of its workflow, built on the server (ComfyUI keyframes: one
+ * start/end-frame clip of `endpoint` per pair of frames, then joined; src/server/chains.ts).
+ */
+ chained?: true;
}
export type Badge = "new" | "top" | "fast" | "audio" | "4k" | "hd" | "pro" | "open" | "uncensored" | "beta";
diff --git a/tests/keyframes.test.ts b/tests/keyframes.test.ts
new file mode 100644
index 00000000..3e236aa8
--- /dev/null
+++ b/tests/keyframes.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, it } from "vitest";
+import { getModel, getPreset } from "@/lib/catalog";
+import {
+ addFrameAt,
+ chainGapProblem,
+ frameRange,
+ frameSupport,
+ framesBlocker,
+ framesDuration,
+ framesDurations,
+ framesInputs,
+ framesNote,
+ frameTimes,
+ keyframeChain,
+ moveFrameAt,
+ planKeyframeClips,
+ positionsFrom,
+ removeFrameAt,
+ spread,
+} from "@/lib/catalog/keyframes";
+import { buildPayload } from "@/lib/catalog/payload";
+import { inferOperation, planGeneration } from "@/lib/catalog/plan";
+import { computeFrames } from "@/lib/comfy";
+
+const m = (id: string) => getModel(id)!;
+const plan = (r: Record<string, unknown>) => planGeneration({ feature: "video", prompt: "a fox runs through snow", ...r } as Parameters<typeof planGeneration>[0], getModel, getPreset);
+const fails = (r: Record<string, unknown>) => {
+ try {
+ plan(r);
+ return null;
+ } catch (e) {
+ return (e as Error).message;
+ }
+};
+const imgs = (n: number) => Array.from({ length: n }, (_, i) => `/f${i}.png`);
+
+describe("frame times", () => {
+ it("spreads frames evenly and keeps doing so while they're untouched", () => {
+ expect(spread(1)).toEqual([0]);
+ expect(spread(3)).toEqual([0, 0.5, 1]);
+ // Start, then end, then the middle.
+ expect(addFrameAt([])).toEqual([0]);
+ expect(addFrameAt([0])).toEqual([0, 1]);
+ expect(addFrameAt([0, 1])).toEqual([0, 0.5, 1]);
+ expect(addFrameAt(spread(4))).toEqual(spread(5));
+ expect(removeFrameAt([0, 0.5, 1], 1)).toEqual([0, 1]);
+ });
+
+ it("keeps frames you placed where they are", () => {
+ // The last frame isn't at the end: the new one goes there.
+ expect(addFrameAt([0, 0.3])).toEqual([0, 0.3, 1]);
+ // It is: it steps to halfway between its neighbour and the end.
+ expect(addFrameAt([0, 0.2, 1])).toEqual([0, 0.2, 0.6, 1]);
+ // Removing the start frame makes the next one the start.
+ expect(removeFrameAt([0, 0.2, 0.7], 0)).toEqual([0, 0.7]);
+ expect(removeFrameAt([0, 0.2, 0.7], 2)).toEqual([0, 0.2]);
+ });
+
+ it("turns positions into seconds snapped to 0.1 s, in order, inside the clip", () => {
+ expect(frameTimes([0, 0.5, 1], 5)).toEqual([0, 2.5, 5]);
+ expect(frameTimes(spread(4), 5)).toEqual([0, 1.7, 3.3, 5]);
+ // Squeezed frames keep 0.1 s apart and step back from the end.
+ expect(frameTimes([0, 0.99, 1, 1], 5)).toEqual([0, 4.8, 4.9, 5]);
+ expect(frameTimes([0.4, 0.5], 4)).toEqual([0, 2]); // the first is always the start frame
+ // A longer clip stretches them.
+ expect(frameTimes([0, 0.5, 1], 8)).toEqual([0, 4, 8]);
+ });
+
+ it("drags a frame between its neighbours, snapped to 0.1 s; the start frame never moves", () => {
+ const at = [0, 0.5, 1];
+ expect(frameTimes(moveFrameAt(at, 1, 1.234, 5), 5)).toEqual([0, 1.2, 5]);
+ expect(frameTimes(moveFrameAt(at, 1, 9, 5), 5)).toEqual([0, 4.9, 5]);
+ expect(frameTimes(moveFrameAt(at, 1, -3, 5), 5)).toEqual([0, 0.1, 5]);
+ expect(frameTimes(moveFrameAt(at, 2, 3.06, 5), 5)).toEqual([0, 2.5, 3.1]);
+ expect(moveFrameAt(at, 0, 2, 5)).toBe(at);
+ expect(frameRange([0, 2.5, 5], 1, 5)).toEqual([0.1, 4.9]);
+ expect(frameRange([0, 2.5, 5], 2, 5)).toEqual([2.6, 5]);
+ expect(frameRange([0, 2.5, 5], 0, 5)).toEqual([0, 0]);
+ expect(positionsFrom([0, 2, 8], 8)).toEqual([0, 0.25, 1]);
+ });
+});
+
+describe("what each model does with frames", () => {
+ it("reads every frame, the ends only, or none", () => {
+ expect(frameSupport(m("flux-3-max"))).toBe("all");
+ expect(frameSupport(m("oss-wan22-14b-fast"))).toBe("all");
+ expect(frameSupport(m("oss-wan22-14b"))).toBe("all");
+ expect(frameSupport(m("kling-o3"))).toBe("ends");
+ expect(frameSupport(m("seedance-2-5"))).toBe("ends");
+ expect(frameSupport(m("oss-wan22-5b"))).toBe("start");
+ expect(keyframeChain(m("oss-wan22-14b-fast"))?.endpoint).toBe("wan22-flf2v-14b");
+ expect(keyframeChain(m("flux-3-max"))).toBeUndefined();
+ });
+
+ it("blocks models that can't follow frames, and asks for the start frame", () => {
+ expect(framesBlocker(m("oss-wan22-5b"), 3)?.message).toBe("Wan 2.2 5B takes a start frame only — pick Wan 2.2 14B Lightning to follow your frames, or turn Frames off");
+ const t2vOnly = { name: "Text Only", engine: "cloud" as const, routes: [{ op: "t2v" as const, provider: "fal" as const, endpoint: "x" }], options: {} };
+ expect(framesBlocker(t2vOnly, 2)?.message).toBe("Text Only can't start from frames — pick FLUX 3 Max, or turn Frames off");
+ expect(framesBlocker(m("flux-3-max"), 0)).toEqual({ message: "Add the start frame", slot: "frames" });
+ expect(framesBlocker(m("flux-3-max"), 4)).toBeNull();
+ expect(framesBlocker(m("kling-o3"), 4)).toBeNull();
+ });
+
+ it("says when a start + end frame model leaves frames out", () => {
+ expect(framesNote(m("kling-o3"), 4)).toBe("Kling O3 Omni takes a start and an end frame, so it uses frames 1 and 4 and leaves out the 2 in between — FLUX 3 Max follows every frame.");
+ expect(framesNote(m("kling-o3"), 3)).toMatch(/leaves out the middle one/);
+ expect(framesNote(m("kling-o3"), 2, 0.6)).toBe("Kling O3 Omni puts the last frame at the end of the clip — FLUX 3 Max keeps it at its time.");
+ expect(framesNote(m("kling-o3"), 2, 1)).toBeNull();
+ expect(framesNote(m("flux-3-max"), 6)).toBeNull();
+ expect(framesNote(m("oss-wan22-14b-fast"), 6)).toBeNull();
+ });
+
+ it("sends every frame with its time, or the first and last as start and end", () => {
+ const refs = ["/a.png", "/b.png", "/c.png"];
+ expect(framesInputs(refs, [0, 2, 5], "all")).toEqual({ images: refs, keyframeTimes: [0, 2, 5] });
+ expect(framesInputs(refs, [0, 2, 5], "ends")).toEqual({ images: ["/a.png"], endImage: "/c.png" });
+ expect(framesInputs(["/a.png"], [0], "all")).toEqual({ images: ["/a.png"] });
+ expect(framesInputs([], [], "all")).toEqual({});
+ });
+
+ it("offers the model's lengths, or the open chain's longer films", () => {
+ expect(framesDurations(m("flux-3-max"))).toEqual([5, 6, 8, 10, 12, 15, 20]);
+ expect(framesDurations(m("oss-wan22-14b-fast"))).toEqual([3, 5, 8, 10, 15, 20, 30]);
+ expect(framesDuration(m("flux-3-max"), 7)).toBe(6);
+ expect(framesDuration(m("flux-3-max"), undefined)).toBe(5);
+ expect(framesDuration(m("kling-o3"), 30)).toBe(15);
+ });
+});
+
+describe("keyframes through the planner", () => {
+ it("plans FLUX 3 Max keyframes and its payload at 24 fps", () => {
+ const p = plan({ modelId: "flux-3-max", inputs: { images: imgs(4) }, params: { keyframeTimes: [0, 1.5, 3.2, 8], duration: 8 } });
+ expect(p.op).toBe("keyframes");
+ const route = getModel("flux-3-max")!.routes.find((r) => r.op === "keyframes")!;
+ const body = buildPayload(route.map!, { prompt: p.prompt, images: imgs(4), keyframeTimes: [0, 1.5, 3.2, 8], duration: 8, aspectRatio: "16:9", resolution: "720p" });
+ expect(body.keyframes).toEqual([
+ { image_url: "/f0.png", frame_index: 0 },
+ { image_url: "/f1.png", frame_index: 36 },
+ { image_url: "/f2.png", frame_index: 77 },
+ { image_url: "/f3.png", frame_index: 192 },
+ ]);
+ expect(body.duration).toBe(8);
+ expect(body.image_url).toBeUndefined();
+ });
+
+ it("checks times and order on both engines", () => {
+ expect(fails({ modelId: "flux-3-max", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 3, 2] } })).toBe("Keyframe times start at 0 or later and go up");
+ expect(fails({ modelId: "oss-wan22-14b-fast", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 3] } })).toBe("Give each of the 3 keyframes a time");
+ expect(fails({ modelId: "oss-wan22-14b-fast", op: "keyframes", inputs: { images: imgs(11) } })).toBe("Wan 2.2 14B Lightning takes up to 10 keyframes");
+ });
+
+ it("makes Frames mode a keyframes job on the open chain, and checks each gap against the model", () => {
+ const wan = m("oss-wan22-14b-fast");
+ expect(inferOperation(wan, { inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 2, 5] } })).toBe("keyframes");
+ expect(inferOperation(wan, { inputs: { images: ["/a.png"], endImage: "/b.png" } })).toBe("flf2v");
+ expect(plan({ modelId: "oss-wan22-14b-fast", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 4, 8], duration: 8 } }).op).toBe("keyframes");
+ expect(fails({ modelId: "oss-wan22-14b-fast", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 6, 8], duration: 8 } })).toBe(
+ "Frames 1 and 2 are 6 s apart — Wan 2.2 14B Lightning makes up to 5 s between two frames. Move them closer or add a frame between them",
+ );
+ expect(fails({ modelId: "oss-wan22-14b-fast", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 2, 2.3], duration: 5 } })).toBe(
+ "Frames 2 and 3 are only 0.3 s apart — keep at least 0.5 s between frames on Wan 2.2 14B Lightning",
+ );
+ expect(fails({ modelId: "oss-wan22-14b-fast", inputs: { images: imgs(2) }, params: { keyframeTimes: [0, 2], duration: 10 } })).toMatch(/^The clip runs 8 s past the last frame/);
+ // Wan 2.2 14B (full quality) makes up to 7 s.
+ expect(fails({ modelId: "oss-wan22-14b", inputs: { images: imgs(3) }, params: { keyframeTimes: [0, 6, 12], duration: 12 } })).toBeNull();
+ // Without times (Assist, MCP, a canvas node) the frames are spread over the clip.
+ expect(fails({ modelId: "oss-wan22-14b-fast", op: "keyframes", inputs: { images: imgs(3) }, params: { duration: 8 } })).toBeNull();
+ expect(fails({ modelId: "oss-wan22-14b-fast", op: "keyframes", inputs: { images: imgs(3) }, params: { duration: 30 } })).toMatch(/15 s apart/);
+ });
+});
+
+describe("the open per-pair plan", () => {
+ const wan = { name: "Wan 2.2 14B Lightning", maxSeconds: 5, fps: 16, step: 4, maxFrames: 121 };
+
+ it("makes one clip per gap, as long as the gap in Wan's 4n + 1 frame steps", () => {
+ const clips = planKeyframeClips([0, 2.5, 5], 5, wan);
+ expect(clips.map((c) => [c.from, c.to, c.frames])).toEqual([
+ [0, 1, 41],
+ [1, 2, 41],
+ ]);
+ expect(clips.map((c) => c.seconds)).toEqual([2.5, 2.5]);
+ // The seconds asked for give the workflow exactly that frame count.
+ for (const c of clips) expect(computeFrames(c.seconds, 16, 4, 121)).toBe(c.frames);
+ expect(planKeyframeClips([0, 5], 5, wan).map((c) => c.frames)).toEqual([81]);
+ });
+
+ it("keeps every frame on its time within half a frame step, however many clips", () => {
+ const times = [0, 1.3, 2.9, 3.4, 5.6, 7.7, 9.1, 12.4, 15, 19.8];
+ const clips = planKeyframeClips(times, 20, wan);
+ // Nine gaps; the 0.2 s after the last frame is under the minimum, so the film ends on it.
+ expect(clips).toHaveLength(9);
+ let total = 0;
+ clips.forEach((c, i) => {
+ expect((c.frames - 1) % 4).toBe(0);
+ total += c.frames;
+ if (c.to !== null) expect(Math.abs((total - 1) / 16 - times[i + 1])).toBeLessThanOrEqual(2 / 16 + 1e-9);
+ });
+ });
+
+ it("adds the stretch after the last frame from that frame alone, unless it's too short", () => {
+ const clips = planKeyframeClips([0, 2, 4], 6, wan);
+ expect(clips.map((c) => [c.from, c.to])).toEqual([
+ [0, 1],
+ [1, 2],
+ [2, null],
+ ]);
+ expect(clips[2].frames).toBe(33);
+ expect(planKeyframeClips([0, 2, 4.8], 5, wan).map((c) => c.to)).toEqual([1, 2]);
+ });
+
+ it("refuses gaps the model can't make", () => {
+ expect(() => planKeyframeClips([0, 5.5], 6, wan)).toThrow(/5.5 s apart/);
+ expect(() => planKeyframeClips([0], 5, wan)).toThrow(/at least two frames/);
+ expect(chainGapProblem([0, 2, 5], 5, wan)).toBeNull();
+ });
+});