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.

N7-6: a keyframe film can wait for frames earlier steps make (ChainSlot.at)

Claudeea5ea4c53265
diff --git a/src/lib/catalog/cinema.ts b/src/lib/catalog/cinema.ts
index 12badc29..3513088e 100644
--- a/src/lib/catalog/cinema.ts
+++ b/src/lib/catalog/cinema.ts
@@ -1212,13 +1212,21 @@ export function withPlaceholders(step: CinemaStep): GenerationRequest {
const req = step.request;
if (!req.chain?.length) return req;
const inputs = { ...req.inputs };
+ // Images with a place (ChainSlot.at: a film's frames that earlier steps make) go in after the others, as the runner puts them.
+ const placed = req.chain.filter((c) => c.slot === "images" && c.at !== undefined && c.at >= 0).sort((a, b) => a.at! - b.at!);
for (const c of req.chain) {
+ if (placed.includes(c)) continue;
if (c.slot === "images") inputs.images = c.position === "first" ? [PLACEHOLDER.image, ...(inputs.images ?? [])] : [...(inputs.images ?? []), PLACEHOLDER.image];
else if (c.slot === "videos") inputs.videos = [...(inputs.videos ?? []), PLACEHOLDER.video];
else if (c.slot === "endImage") inputs.endImage = PLACEHOLDER.image;
else if (c.slot === "video") inputs.video = PLACEHOLDER.video;
else if (c.slot === "audio" || c.slot === "voiceAudio") inputs[c.slot] = PLACEHOLDER.audio;
}
+ for (const c of placed) {
+ const list = [...(inputs.images ?? [])];
+ list.splice(Math.min(c.at!, list.length), 0, PLACEHOLDER.image);
+ inputs.images = list;
+ }
return { ...req, inputs };
}
diff --git a/src/lib/catalog/keyframes.ts b/src/lib/catalog/keyframes.ts
index 72b5d652..64adfd5a 100644
--- a/src/lib/catalog/keyframes.ts
+++ b/src/lib/catalog/keyframes.ts
@@ -13,7 +13,7 @@
*
* No catalog import (types only), so the composer can use it in the browser.
*/
-import type { Engine, ModelDef, ModelRoute, Operation } from "./types";
+import type { Engine, GenerationRequest, ModelDef, ModelRoute, Operation } from "./types";
/** Kling 4.0 and FLUX 3 Max take up to 10 frames. */
export const MAX_KEYFRAMES = 10;
@@ -69,6 +69,15 @@ export const chainedWaitMessage = (name: string, op?: Operation) =>
? `${name} draws the object first, then builds it in 3D, from words typed in when it starts — give it a typed description, not another step's output`
: `${name} builds this film from several clips of the images you add when it starts — give it uploaded images and a typed prompt, not another step's output`;
+/**
+ * A keyframe film some of whose frames earlier steps make (Turnaround video: the sides the Angles app draws): every
+ * chain slot is a frame with its place among the request's own (ChainSlot.at). The open engine's film can wait for those,
+ * clip by clip; any other chained input is refused as before (chainedWaitMessage).
+ */
+export function framesWait(req: Pick<GenerationRequest, "chain">): boolean {
+ return !!req.chain?.length && req.chain.every((s) => s.slot === "images" && s.at !== undefined && s.at >= 0);
+}
+
/** 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);
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 89062397..24167b2a 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -947,6 +947,12 @@ export interface ChainSlot {
slot: "images" | "endImage" | "video" | "videos" | "audio" | "voiceAudio" | "audio2" | "audios" | "model3d" | "mask" | "prompt";
/** For list slots: put it before or after the request's own items (default last). */
position?: "first" | "last";
+ /**
+ * For list slots: the place it takes in the finished list (0-based) among the request's own items, instead of before or
+ * after them. Slots with `at` go in after the others, in order of `at`, so each lands where it says: a keyframe film's
+ * frames that earlier steps make (Turnaround video: the sides the Angles app draws go between the photo's own views).
+ */
+ at?: number;
/**
* Audio slots: take the dependency's output whose `meta.stem` is this (separate-audio makes
* "voice" and "background", DBS also "music" and "effects"; "voice" also matches vocals/speech/target,
diff --git a/src/server/chains.ts b/src/server/chains.ts
index 73238547..b2b429dc 100644
--- a/src/server/chains.ts
+++ b/src/server/chains.ts
@@ -2,7 +2,7 @@ import "server-only";
import { nanoid } from "nanoid";
import { getModel, supportsOp } from "@/lib/catalog";
import { MODEL3D_STEP_FEATURE, stillPromptFor3d } from "@/lib/av/model3d";
-import { chainTiming, frameTimes, planKeyframeClips, spread } from "@/lib/catalog/keyframes";
+import { chainTiming, chainedWaitMessage, frameTimes, framesWait, planKeyframeClips, spread } from "@/lib/catalog/keyframes";
import { faceMosaicStep } from "@/lib/catalog/open-tools";
import { dualEngine, onEngine } from "@/lib/catalog/engines";
import { routesFor } from "@/lib/catalog/plan";
@@ -214,11 +214,29 @@ export function createShotFilm(original: GenerationRequest, model: ModelDef): Ge
* 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.
+ *
+ * Frames can come from earlier steps (`waits.dependsOn`, one per chain slot, each an image with its place among the
+ * request's own: framesWait). Each clip then waits for the frames it starts or ends on (Turnaround video: the sides the
+ * Angles app draws), and the clips between the request's own frames start at once.
*/
-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 ?? [];
+export function createKeyframeFilm(original: GenerationRequest, model: ModelDef, route: ModelRoute, waits: { batchId?: string; dependsOn?: string | string[] } = {}): Generation[] {
+ const deps = waits.dependsOn === undefined ? [] : Array.isArray(waits.dependsOn) ? waits.dependsOn : [waits.dependsOn];
+ const slots = original.chain ?? [];
+ if (deps.length && (!framesWait(original) || slots.length !== deps.length)) throw new Error(chainedWaitMessage(model.name, "keyframes"));
+ // A film whose frames came from earlier steps, asked again on its own (Run again): those steps are gone.
+ if (slots.length && !deps.length) throw new Error(`Some of this film's frames were made by earlier steps — make it again where it was made, so ${model.name} gets them`);
+ // The film's frames in order: the request's own, and the ones earlier steps make put in at their places.
+ type Frame = { url: string } | { dep: string };
+ const frames: Frame[] = (original.inputs?.images ?? []).map((url) => ({ url }));
+ slots
+ .map((s, i) => ({ at: s.at!, dep: deps[i] }))
+ .sort((a, b) => a.at - b.at)
+ .forEach((x) => frames.splice(Math.min(x.at, frames.length), 0, { dep: x.dep }));
+ // The whole request is checked first (prompt, frame count, gaps), so no clip starts for a film that can't be made; frames
+ // still to come are checked as placeholders.
+ const asChecked: GenerationRequest = { ...original, op: "keyframes", chain: undefined, inputs: { ...original.inputs, images: frames.map((f) => ("url" in f ? f.url : WAITING_FRAME)) } };
+ previewGeneration(asChecked);
+ const images = asChecked.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);
@@ -234,7 +252,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
...(tail ? [{ label: `${model.name} after the last frame`, modelId: model.id, op: "i2v" as const, engine: model.engine }] : []),
...(clips.length > 1 ? [{ label: "Joining the clips", modelId: joinModelId(model.engine), op: "concat" as const }] : []),
]);
- const batchId = nanoid(10);
+ const batchId = waits.batchId ?? nanoid(10);
const params = { ...original.params };
delete params.keyframeTimes;
delete params.shots;
@@ -247,14 +265,31 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
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}`;
+ // A frame an earlier step makes reaches the clip through its chain: the start as its image, the end as its end frame.
+ const inputs: GenerationRequest["inputs"] = { ...rest };
+ const chain: ChainSlot[] = [];
+ const after: string[] = [];
+ const start = frames[c.from];
+ if ("url" in start) inputs.images = [start.url];
+ else {
+ chain.push({ slot: "images" });
+ after.push(start.dep);
+ }
+ const end = c.to === null ? undefined : frames[c.to];
+ if (end && "url" in end) inputs.endImage = end.url;
+ else if (end) {
+ chain.push({ slot: "endImage" });
+ after.push(end.dep);
+ }
const request: GenerationRequest = {
...original,
op: c.to === null ? "i2v" : "flf2v",
- inputs: { ...rest, images: [images[c.from]], ...(c.to !== null && { endImage: images[c.to] }) },
+ inputs: Object.keys(inputs).length ? inputs : undefined,
+ chain: chain.length ? chain : undefined,
params: { ...params, duration: c.seconds, numOutputs: 1 },
...(n > 1 ? { step: { label, index: i, of: n + 1 } } : {}),
};
- made.push(createGenerations(request, { batchId })[0]);
+ made.push(createGenerations(request, { batchId, ...(after.length && { dependsOn: after }) })[0]);
}
if (n === 1) return withAsked(made, original, model.engine);
const film = joinClips(
@@ -278,6 +313,9 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,
}
}
+/** Where a frame an earlier step makes sits while the film is checked (it is never sent). */
+const WAITING_FRAME = "/api/files/placeholder.png";
+
/** 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.ts
index 2d670902..cc532fe5 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -11,7 +11,7 @@ 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 { upscaleTier } from "@/lib/av/upscale";
-import { chainedWaitMessage, keyframeChain } from "@/lib/catalog/keyframes";
+import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";
import { clipWindowProblem } from "@/lib/catalog/clip-windows";
import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
import { framedLength, keepMatte } from "@/lib/catalog/payload";
@@ -675,7 +675,8 @@ export function previewChained(req: GenerationRequest, deps: number) {
// A waiting step always runs as one job (createGenerations doesn't batch dependents).
const p = previewGeneration(withChainInputs(req, slotsFor(req, deps).map(placeholderFor)));
// Refused before anything starts, as createGenerations refuses it.
- if (routesFor(p.model, p.op).some((r) => r.chained)) throw new Error(chainedWaitMessage(p.model.name, p.op));
+ // A keyframe film waits for frames earlier steps make (framesWait): its clips are created then, each waiting for its own.
+ if (routesFor(p.model, p.op).some((r) => r.chained) && !(p.op === "keyframes" && framesWait(req))) throw new Error(chainedWaitMessage(p.model.name, p.op));
const jobs = Math.max(1, p.jobs);
return { ...p, jobs: 1, outputs: p.outputs / jobs, costUsd: p.costUsd === null ? null : p.costUsd / jobs };
}
@@ -711,7 +712,10 @@ export function createGenerations(asked: GenerationRequest, opts: CreateOptions
}
// 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);
+ // Its frames can come from earlier steps (framesWait): each clip then waits for the frames it starts and ends on.
+ if (filmRoute && inferOperation(shotModel, original) === "keyframes" && (!opts.dependsOn || framesWait(original))) {
+ return createKeyframeFilm(original, shotModel, filmRoute, { batchId: opts.batchId, dependsOn: opts.dependsOn });
+ }
// Text to 3D on the open engine: a still first, then the 3D model of it. The operation is read as the planner
// reads it (Assist, MCP and API clients usually leave op out).
const stillTo3d = !opts.dependsOn && shotModel && inferOperation(shotModel, original) === "text-to-3d" ? routesFor(shotModel, "text-to-3d").find((r) => r.chained) : undefined;
@@ -877,6 +881,9 @@ export async function chainValue(o: OutputFile | undefined, s: ChainSlot, op?: G
.catch(() => undefined);
}
+/** A list slot with its own place in the list (ChainSlot.at). */
+const placed = (s: ChainSlot) => s.at !== undefined && s.at >= 0;
+
/**
* Put the dependencies' outputs into the request's inputs, slot by slot (lists keep dependency order).
* A "prompt" slot gets the dependency's text: it fills "{text}" in the prompt, or becomes the prompt.
@@ -886,10 +893,16 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generat
let prompt = req.prompt;
const slots = slotsFor(req, urls.length);
for (const k of ["images", "videos", "audios"] as const) {
- const at = (pos: "first" | "last") => slots.flatMap((s, i) => (s.slot === k && (s.position ?? "last") === pos ? [urls[i]] : []));
+ const at = (pos: "first" | "last") => slots.flatMap((s, i) => (s.slot === k && !placed(s) && (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 with a place go in last, in order of it, so each lands where it says (a film's frames made by earlier steps).
+ const inserts = slots.flatMap((s, i) => (s.slot === k && placed(s) ? [{ at: s.at!, url: urls[i] }] : [])).sort((a, b) => a.at - b.at);
+ if (first.length || last.length || inserts.length) {
+ const list = [...first, ...(inputs[k] ?? []), ...last];
+ for (const x of inserts) list.splice(Math.min(x.at, list.length), 0, x.url);
+ inputs[k] = list;
+ }
}
slots.forEach((s, i) => {
if (s.slot === "prompt") prompt = prompt?.includes("{text}") ? prompt.replaceAll("{text}", urls[i]) : urls[i];
@@ -914,8 +927,10 @@ export function unfilledRequest(req: GenerationRequest, deps: number): Generatio
const slots = filledSlots({ ...rest, chainSkipped }, 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 count = (pos: "first" | "last") => slots.filter((s) => s.slot === k && !placed(s) && (s.position ?? "last") === pos).length;
+ const list = [...(inputs[k] ?? [])];
+ // Placed items come out first, the last placed first, as they went in.
+ for (const at of slots.filter((s) => s.slot === k && placed(s)).map((s) => s.at!).sort((a, b) => b - a)) if (at < list.length) list.splice(at, 1);
const own = list.slice(count("first"), list.length - count("last"));
if (own.length) inputs[k] = own;
else delete inputs[k];
diff --git a/tests/chains.test.ts b/tests/chains.test.ts
index 01226b68..94f199ab 100644
--- a/tests/chains.test.ts
+++ b/tests/chains.test.ts
@@ -49,6 +49,23 @@ describe("chain inputs", () => {
// 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"]);
});
+
+ it("puts a slot with a place where it says among the request's own items, and takes it out again for a retry", () => {
+ // A turnaround's frames: the photo's front and back are its own; the sides come from earlier steps, in either order.
+ const req = {
+ feature: "turnaround",
+ modelId: "flux-3-max",
+ inputs: { images: ["front.png", "back.png", "front.png"] },
+ chain: [{ slot: "images" as const, at: 3 }, { slot: "images" as const, at: 1 }, { slot: "images" as const, position: "first" as const }],
+ };
+ const filled = gens.withChainInputs(req, ["left.png", "right.png", "lead.png"]);
+ expect(gens.withChainInputs({ ...req, chain: req.chain.slice(0, 2) }, ["left.png", "right.png"]).inputs?.images).toEqual(["front.png", "right.png", "back.png", "left.png", "front.png"]);
+ const two = { ...req, chain: req.chain.slice(0, 2) };
+ expect(gens.unfilledRequest({ ...gens.withChainInputs(two, ["left.png", "right.png"]), chainFilled: true }, 2).inputs?.images).toEqual(["front.png", "back.png", "front.png"]);
+ // With an unplaced slot too: placed ones go in after it, at their places in the finished list.
+ expect(filled.inputs?.images).toEqual(["lead.png", "right.png", "front.png", "left.png", "back.png", "front.png"]);
+ expect(gens.unfilledRequest({ ...filled, chainFilled: true }, 3).inputs?.images).toEqual(["front.png", "back.png", "front.png"]);
+ });
});
describe("open multi-shot", () => {
@@ -206,6 +223,47 @@ describe("keyframe film (Frames mode on the open engine)", () => {
expect(gens.previewChained({ feature: "canvas", modelId: "oss-wan22-14b-fast", prompt: "x", chainFrom: "first" }, 1).op).toBe("i2v");
});
+ it("waits for frames earlier steps make: each clip waits only for the frames it starts and ends on", async () => {
+ // A turnaround on the open engine: the photo's front and back, the sides drawn first by the Angles route.
+ const [front, back] = await frames(2);
+ const side = (words: string) =>
+ gens.createGenerations({ feature: "turnaround", modelId: "oss-qwen-edit", op: "edit", prompt: `<sks> ${words} eye-level shot medium shot.`, inputs: { images: [front] }, params: { numOutputs: 1 } })[0];
+ const right = side("right side view");
+ const left = side("left side view");
+ const film = {
+ feature: "turnaround",
+ modelId: "oss-wan22-14b",
+ op: "keyframes" as const,
+ prompt: "The camera orbits 360 degrees around the person at a constant height; the person stands naturally",
+ inputs: { images: [front, back, front] },
+ chain: [{ slot: "images" as const, at: 1 }, { slot: "images" as const, at: 3 }],
+ params: { aspectRatio: "16:9", resolution: "480p", duration: 8, keyframeTimes: [0, 2, 4, 6, 8] },
+ };
+ // Priced and checked like any waiting step, with the frames still to come as placeholders.
+ expect(gens.previewChained(film, 2)).toMatchObject({ op: "keyframes", costUsd: 0 });
+ const [joined, ...clips] = gens.createGenerations(film, { dependsOn: [right.id, left.id], batchId: "turn-1" });
+ expect(joined).toMatchObject({ modelId: "oss-join-clips", op: "concat", batchId: "turn-1" });
+ expect(clips.map((c) => c.request.step?.label)).toEqual(["Frames 1 → 2", "Frames 2 → 3", "Frames 3 → 4", "Frames 4 → 5"]);
+ expect(clips.map((c) => dependsOn(c.id))).toEqual([[right.id], [right.id], [left.id], [left.id]]);
+ expect(clips.map((c) => [c.request.inputs?.images, c.request.inputs?.endImage, c.request.chain?.map((x) => x.slot)])).toEqual([
+ [[front], undefined, ["endImage"]],
+ [undefined, back, ["images"]],
+ [[back], undefined, ["endImage"]],
+ [undefined, front, ["images"]],
+ ]);
+ // 2 s a quarter in Wan's 4n + 1 frame steps, each frame kept on its time across the joins (33, 33, 33 and 29 frames).
+ expect(clips.map((c) => c.request.params?.duration)).toEqual([2, 2, 2, 1.75]);
+ const done = await settle(joined.id, 60_000);
+ expect(done.status).toBe("succeeded");
+ // Each clip got its frames from the steps it waited for.
+ const second = gens.getGeneration(clips[1].id)!;
+ expect(second.request.inputs?.images?.[0]).toBe(gens.getGeneration(right.id)!.outputs[0].url);
+ // Asked again on its own, the film can't find those steps: it says so rather than making a film with gaps.
+ expect(() => gens.createGenerations(film)).toThrow(/made by earlier steps/);
+ // A film's other inputs still can't wait.
+ expect(() => gens.createGenerations({ ...film, chain: [{ slot: "images" as const }, { slot: "images" as const, at: 3 }] }, { dependsOn: [right.id, left.id] })).toThrow(/not another step's output/);
+ }, 70_000);
+
it("keeps a start frame and a leftover reference an image-to-video clip, not a film", async () => {
// A Seedance reference tile carried over to Wan when the engine switches: no times, no film.
const images = await frames(2);