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
Skills W2 fixes: a stack is one step, Explainer refused, open captions keep their languages
Claude3ae4de90a22d
diff --git a/src/lib/recipe-builder.ts b/src/lib/recipe-builder.tsindex 32cce773..6533bc46 100644--- a/src/lib/recipe-builder.ts+++ b/src/lib/recipe-builder.ts@@ -113,6 +113,9 @@ const STUDIOS: [RegExp, StudioInfo][] = [[/^layers$/, { name: "Layers", tool: "split_layers" }],[/^shorts$/, { name: "Shorts Studio", tool: "restyle_footage" }],[/^faceless/, { name: "Faceless Studio", tool: "faceless_episode" }],+ // An Explainer episode is Faceless's graph (scene stills, narration, Ken Burns, joins), but faceless_episode makes+ // channel episodes only.+ [/^explainer$/, { name: "Explainer" }],[/^ads$/, { name: "Ads Studio", tool: "create_ads" }],[/^ad-multiplier$/, { name: "Ad Multiplier" }],[/^click-to-ad$/, { name: "Click to Ad" }],@@ -135,13 +138,21 @@ const STUDIOS: [RegExp, StudioInfo][] = [[/^skill-check$/, { name: "a skill's check" }],];+/**+ * Studios whose own results are plain requests (a Marketing Studio picture replays as it was asked) but whose helper+ * steps (`<feature>-step`: a UGC video's shots, a text-to-3D's still) are their planner's, named when refused.+ */+const HELPER_STUDIOS: Record<string, string> = { marketing: "Marketing Studio", "image-to-3d": "Image to 3D" };+/*** The studio a feature belongs to when that studio plans its own steps (a helper step `<feature>-step` belongs to its* feature's studio), or undefined for a plain request (Image, Video, Edit, Assist, an app…).*/export function studioOf(feature: string): StudioInfo | undefined {const base = feature.replace(/(-frame)?-step$/, "").replace(/-(preview|avatar|voice)$/, "");- return STUDIOS.find(([re]) => re.test(base))?.[1] ?? (base !== feature ? { name: "another studio" } : undefined);+ const found = STUDIOS.find(([re]) => re.test(base))?.[1];+ if (found || base === feature) return found;+ return { name: HELPER_STUDIOS[base] ?? "another studio" };}export const notSupported = (studio: string) => `Made in ${studio}: making a skill from it isn't supported yet`;@@ -308,7 +319,7 @@ const idOf = (c: DraftCandidate, choices: BuilderChoices) => choices.ids?.[c.id]* The recipe the choices make: each candidate that varies becomes an input and `{{id}}` where its value was (an element* is put in for its @handle in the words), each accepted slot replaces its words in every prompt that still has them,* and the checks follow (a count or a shape that varies is checked against the input; a length that varies isn't- * checked). An element or slot that ends up nowhere (its prompt varies as a whole) adds no input.+ * checked). An element or slot that ends up nowhere (every prompt naming it varies as a whole) adds no input.*/export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, choices: BuilderChoices): Recipe {const recipe = clone(draft.recipe);@@ -316,8 +327,9 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, chconst byKey = new Map(recipe.steps.map((s) => [s.key, s]));const checks = recipe.checks ?? {};const varying = draft.candidates.filter((c) => choices.varies[c.id] && !c.locked);- // Elements first: their @handles are put in before a prompt that varies as a whole replaces the words.- const order = [...varying.filter((c) => c.kind === "element"), ...varying.filter((c) => c.kind !== "element")];+ // Elements last: a prompt that varies as a whole has replaced its words by then, so an element named only there+ // finds no @handle and adds no input (the whole prompt's input carries it).+ const order = [...varying.filter((c) => c.kind !== "element"), ...varying.filter((c) => c.kind === "element")];const placed: RecipeParam[] = [];for (const c of order) {const id = idOf(c, choices);@@ -339,12 +351,13 @@ export function buildRecipe(draft: Pick<SkillDraft, "recipe" | "candidates">, ch}setAt(body, spot.path, `{{${id}}}`);used++;- // A count that varies is checked against the input when one job made every result (else it isn't checked).- if (c.setting === "numOutputs") {- const cur = checks[spot.step]?.count;+ // A count that varies is checked against the input when one job made every result (else it isn't checked: a+ // step whose results came as several jobs has no count check to follow).+ if (c.setting === "numOutputs" && checks[spot.step]) {+ const cur = checks[spot.step].count;const rest = { ...checks[spot.step] };delete rest.count;- checks[spot.step] = cur === undefined || cur === c.example ? { ...rest, count: `{{${id}}}` } : rest;+ checks[spot.step] = cur === c.example ? { ...rest, count: `{{${id}}}` } : rest;}if (c.setting === "aspectRatio" && checks[spot.step]) checks[spot.step] = { ...checks[spot.step], aspect: `{{${id}}}` };if (c.setting === "duration" && checks[spot.step]) {diff --git a/src/server/chains.ts b/src/server/chains.tsindex 77563904..73238547 100644--- a/src/server/chains.ts+++ b/src/server/chains.ts@@ -4,7 +4,7 @@ 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 { faceMosaicStep } from "@/lib/catalog/open-tools";-import { onEngine } from "@/lib/catalog/engines";+import { dualEngine, onEngine } from "@/lib/catalog/engines";import { routesFor } from "@/lib/catalog/plan";import type { ChainSlot, Engine, GenParams, Generation, GenerationRequest, LoraRef, ModelDef, ModelRoute, Operation } from "@/lib/catalog/types";import { db } from "./db";@@ -58,10 +58,11 @@ export function assertOneMode(steps: ModeStep[]): void {* the result (src/server/recipe-builder.ts) rebuilds that one request, not the rows it expanded into, whose number* changes with the input (a film of 3 shots is 4 rows, of 5 shots 6).*/-function withAsked(made: Generation[], asked: GenerationRequest): Generation[] {+function withAsked(made: Generation[], asked: GenerationRequest, engine: Engine): Generation[] {const [first, ...rest] = made;if (!first) return made;- const request = { ...asked };+ // A Fuobe Original keeps the engine it ran on, as a plain row's request does (createGenerations).+ const request = { ...asked, ...(dualEngine(getModel(asked.modelId)) && { engine }) };for (const k of ["asked", "chainFilled", "chainSkipped", "notice"] as const) delete request[k];const stored: GenerationRequest = { ...first.request, asked: request };db().prepare("UPDATE generations SET request_json = ? WHERE id = ?").run(JSON.stringify(stored), first.id);@@ -200,7 +201,7 @@ export function createShotFilm(original: GenerationRequest, model: ModelDef): Gestep: { label: `Film · ${n} shots`, index: n, of: n + 1 },},);- return withAsked([film, ...clips], original);+ return withAsked([film, ...clips], original, model.engine);} catch (e) {// Don't leave shots rendering for a film that can't be made.for (const g of clips) void cancelGeneration(g.id);@@ -255,7 +256,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,};made.push(createGenerations(request, { batchId })[0]);}- if (n === 1) return withAsked(made, original);+ if (n === 1) return withAsked(made, original, model.engine);const film = joinClips(made.map((c) => c.id),{@@ -269,7 +270,7 @@ export function createKeyframeFilm(original: GenerationRequest, model: ModelDef,step: { label: `Film · ${images.length} frames`, index: n, of: n + 1 },},);- return withAsked([film, ...made], original);+ return withAsked([film, ...made], original, model.engine);} catch (e) {// Don't leave half a film rendering.for (const g of made) void cancelGeneration(g.id);@@ -320,7 +321,7 @@ export function createExtendChain(original: GenerationRequest, model: ModelDef):before: [video],step: { label: "Extended video", index: 2, of: 3 },});- return withAsked([film, clip, frame], original);+ return withAsked([film, clip, frame], original, model.engine);} catch (e) {for (const g of made) void cancelGeneration(g.id);throw e;@@ -373,7 +374,7 @@ export function createStillTo3d(original: GenerationRequest, model: ModelDef, ro},{ batchId, dependsOn: still.id },)[0];- return withAsked([built, still], original);+ return withAsked([built, still], original, model.engine);} catch (e) {void cancelGeneration(still.id);throw e;@@ -426,7 +427,7 @@ export function createRelitClip(},{ batchId, dependsOn: relit.id },)[0];- return withAsked([clip, relit], original);+ return withAsked([clip, relit], original, engine);} catch (e) {void cancelGeneration(relit.id);throw e;diff --git a/src/server/recipe-builder.ts b/src/server/recipe-builder.tsindex 752b41ea..9d0e3879 100644--- a/src/server/recipe-builder.ts+++ b/src/server/recipe-builder.ts@@ -1,6 +1,7 @@import "server-only";import fs from "node:fs";import { getModel } from "@/lib/catalog";+import { inferOperation } from "@/lib/catalog/plan";import { OPERATION_LABELS, type ChainSlot, type Generation, type GenerationRequest, type OutputFile } from "@/lib/catalog/types";import { dubLanguageFor } from "@/lib/assist-studios";import { isHelperFeature } from "@/lib/library";@@ -59,6 +60,30 @@ function batchRows(batch: string | null): Generation[] {return ids.map((id) => getGeneration(id, { includeDeleted: true })).filter((g): g is Generation => !!g);}+/**+ * The other rows of the request a row was made by, when the run split it into jobs (a route that can't batch, such as a+ * ComfyUI graph or Replicate without num_outputs, makes one row per result; a count over a route's maximum makes+ * several): the same batch, the same stored request and the same dependencies. Oldest first.+ */+function jobsOf(id: string): string[] {+ const r = db().prepare("SELECT batch_id, request_json, depends_on FROM generations WHERE id = ?").get(id) as { batch_id: string | null; request_json: string; depends_on: string | null } | undefined;+ if (!r?.batch_id) return [];+ const rows = db()+ .prepare("SELECT id FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS ? AND id != ? ORDER BY created_at, id")+ .all(r.batch_id, r.request_json, r.depends_on, id) as { id: string }[];+ return rows.map((x) => x.id);+}++/** A request with what differs between the pictures of one PixeletedFace run (createMosaicRun) left out. */+function mosaicShape(req: GenerationRequest): string {+ const rest: GenerationRequest = { ...req };+ delete rest.step;+ const params = { ...rest.params };+ delete params.seed;+ delete params.numOutputs;+ return JSON.stringify({ ...rest, params });+}+/** Request fields a step keeps (GenerationRequestSchema's, less the server's own): everything else is dropped. */const KEEP: (keyof GenerationRequest)[] = ["feature", "presetId", "modelId", "op", "prompt", "negativePrompt", "inputs", "params", "presetOptions", "presetStrength", "mix", "loras", "engine", "signature"];@@ -81,8 +106,10 @@ interface Node {key: string;/** The result the step stands for (its thumbnail, its checks). */gen: Generation;- /** Every row the step covers (an expansion's rows, a face mosaic's picture). */+ /** Every row the step covers (an expansion's rows, a face mosaic's picture, the jobs of one request). */rows: string[];+ /** The request ran as this many jobs (a route that can't batch makes one row per result): no count is checked. */+ jobs?: number;step: RecipeStep;label: string;modelName: string;@@ -156,7 +183,11 @@ class Walk {if (known) return known;const moved = currentRequest(head.request.asked!);const rows = [head.id, ...this.batchAncestors(head)];- const node = this.add(head, rows, { request: moved.request }, this.moved(moved.note));+ // The step is named by what was asked (a multi-shot film asked without an operation is text to video, not the+ // join its first row is).+ const m = getModel(moved.request.modelId);+ const op = moved.request.op ?? (m ? inferOperation(m, moved.request) : undefined);+ const node = this.add(head, rows, { request: moved.request, op }, this.moved(moved.note));node.notes.push(`Rebuilt as the one request it was asked as (it ran as ${rows.length} steps)`);return node;}@@ -181,33 +212,63 @@ class Walk {const deps = given ?? depIds(rowOf(source.id)?.depends_on).map((id) => getGeneration(id, { includeDeleted: true }));const moved = currentRequest(source.request);const notes = this.moved(moved.note);- const rows = picture ? [g.id, picture.id] : [g.id];+ let rows = picture ? [g.id, picture.id] : [g.id];+ let jobs = 1;if (picture) {const req = { ...moved.request };delete req.postMade;+ // The other pictures of the same PixeletedFace run, each with its mosaic: one request for that many.+ const shape = mosaicShape(picture.request);+ const pictures = batchRows(rowOf(picture.id)?.batch_id ?? null)+ .filter((b) => b.request.postMade && mosaicShape(b.request) === shape)+ .sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1));+ if (pictures.length > 1) {+ const ids = new Set(pictures.map((p) => p.id));+ const mosaics = batchRows(rowOf(picture.id)?.batch_id ?? null).filter((b) => depIds(rowOf(b.id)?.depends_on).some((d) => ids.has(d)));+ rows = [...new Set([g.id, picture.id, ...pictures.map((p) => p.id), ...mosaics.map((x) => x.id)])];+ jobs = pictures.length;+ const seeds = pictures.map((p) => p.request.params?.seed);+ const seed = seeds.every((x): x is number => typeof x === "number") ? Math.min(...seeds) : undefined;+ req.params = { ...req.params, numOutputs: pictures.length, ...(seed !== undefined && { seed }) };+ if (seed === undefined && req.params) delete req.params.seed;+ notes.push(`Rebuilt as the one request it was asked as (${pictures.length} pictures, each with its face mosaic)`);+ }moved.request = req;+ } else {+ // A Library stack whose request ran as one job per result: one step, as it was asked.+ const others = jobsOf(g.id);+ if (others.length) {+ rows = [g.id, ...others];+ jobs = rows.length;+ notes.push(`Ran as ${jobs} jobs of one request: one step here`);+ }}- if (!deps.length) return this.add(g, rows, { request: moved.request }, notes);- if (deps.some((d) => !d)) {- // A step it waited for is gone: what it gave this one stays as a fixed input.- notes.push("A step before it is gone, so what it gave this step is used as it is");- const filled = { ...moved.request };- delete filled.chain;- delete filled.chainFrom;- return this.add(g, rows, { request: filled }, notes);- }- const before = deps.map((d) => this.visit(d!, new Set(path)));- const chain = chainOf(moved.request, deps.length);- const request = unfilledRequest(moved.request, deps.length);- return this.add(g, rows, { request, after: before.map((n) => n.key), chain }, notes);+ const node = (() => {+ if (!deps.length) return this.add(g, rows, { request: moved.request }, notes);+ if (deps.some((d) => !d)) {+ // A step it waited for is gone: what it gave this one stays as a fixed input.+ notes.push("A step before it is gone, so what it gave this step is used as it is");+ const filled = { ...moved.request };+ delete filled.chain;+ delete filled.chainFrom;+ return this.add(g, rows, { request: filled }, notes);+ }+ const before = deps.map((d) => this.visit(d!, new Set(path)));+ const chain = chainOf(moved.request, deps.length);+ const request = unfilledRequest(moved.request, deps.length);+ return this.add(g, rows, { request, after: before.map((n) => n.key), chain }, notes);+ })();+ if (jobs > 1) node.jobs = jobs;+ return node;}- add(gen: Generation, rows: string[], s: { request: GenerationRequest; after?: string[]; chain?: ChainSlot[] }, notes: string[]): Node {+ add(gen: Generation, rows: string[], s: { request: GenerationRequest; after?: string[]; chain?: ChainSlot[]; op?: string }, notes: string[]): Node {const req = s.request;const m = getModel(req.modelId);- const label = opLabel(req.op ?? gen.op);+ const op = s.op ?? req.op ?? gen.op;+ const label = opLabel(op);const step: RecipeStep = {- key: this.key(req.op ?? gen.op ?? "step"),+ key: this.key(op ?? "step"),kind: "generate",label,...(s.after?.length && { after: s.after.length === 1 ? s.after[0] : s.after }),@@ -245,9 +306,9 @@ function linkByFile(walk: Walk): void {const src = typeof url === "string" ? made.get(url) : undefined;return src && src !== n && src.gen.createdAt <= n.gen.createdAt && !after.includes(src.key) ? src : undefined;};- const link = (src: Node, slot: ChainSlot) => {- after.push(src.key);- chain.push(slot);+ const link = (src: Node, slot: ChainSlot, at = chain.length) => {+ after.splice(at, 0, src.key);+ chain.splice(at, 0, slot);const p = (src.step as Extract<RecipeStep, { kind: "generate" }>).request.params as Record<string, unknown> | undefined;if (typeof p?.numOutputs === "number" && p.numOutputs > 1) {p.numOutputs = 1;@@ -257,12 +318,33 @@ function linkByFile(walk: Walk): void {for (const k of ["images", "videos", "audios"] as const) {const list = inputs[k];if (!list?.length) continue;- const keep: string[] = [];- list.forEach((url, i) => {+ // Which items another picked step made (each step once: a second use of the same file stays a file).+ const taken = new Set<string>();+ const srcs = list.map((url) => {const src = from(url);- if (!src) return void keep.push(url);- link(src, { slot: k, ...(k === "images" && { position: i === 0 ? ("first" as const) : ("last" as const) }) });+ if (!src || taken.has(src.key)) return undefined;+ taken.add(src.key);+ return src;+ });+ if (!taken.size) continue;+ // A run puts the chained items before ("first") or after ("last") the step's own, in chain order+ // (withChainInputs): the ones before its first own item go first, the rest last, and a new "last" goes ahead of+ // the step's earlier "last" slots, which came after every item it has here. An item between two of its own+ // can't stay there: it goes last, and the step says so.+ const own = srcs.flatMap((src, i) => (src ? [] : [i]));+ const firstOwn = own[0] ?? list.length;+ const lastOwn = own.at(-1) ?? -1;+ srcs.forEach((src, i) => src && i < firstOwn && link(src, { slot: k, position: "first" }));+ let lastAt = chain.findIndex((c) => c.slot === k && (c.position ?? "last") === "last");+ if (lastAt < 0) lastAt = chain.length;+ let moved = false;+ srcs.forEach((src, i) => {+ if (!src || i < firstOwn) return;+ if (i < lastOwn) moved = true;+ link(src, { slot: k, position: "last" }, lastAt++);});+ if (moved) n.notes.push(`Its ${k === "images" ? "pictures" : k === "videos" ? "clips" : "audio files"} come in another order: the ones earlier steps make go after yours`);+ const keep = list.filter((_, i) => !srcs[i]);if (keep.length) inputs[k] = keep;else delete inputs[k];}@@ -365,8 +447,23 @@ function liftStudio(g: Generation, tool: string, studio: string): Lifted | nullconst burn = g.op === "captions" ? g : batchRows(rowOf(g.id)?.batch_id ?? null).find((b) => b.op === "captions" && b.feature === g.feature);const video = burn?.request.inputs?.video;if (!burn || !video) return null;- const p = burn.request.params ?? {};- const input = { video, ...(langName(p.sourceLanguage) && { spoken_language: langName(p.sourceLanguage) }), ...(p.targetLanguage && { translate_to: langName(p.targetLanguage) ?? p.targetLanguage }) };+ // The languages: on the burn itself (VEED transcribes and translates in one job), else on the steps it waited for+ // (the open engine's transcript, then its translation).+ let { sourceLanguage: spoken, targetLanguage: target } = burn.request.params ?? {};+ const todo = depIds(rowOf(burn.id)?.depends_on);+ const seen = new Set<string>();+ while (todo.length && seen.size < 8) {+ const id = todo.shift()!;+ if (seen.has(id)) continue;+ seen.add(id);+ const d = getGeneration(id, { includeDeleted: true });+ if (!d) continue;+ const dp = d.request.params ?? {};+ if (target === undefined && d.op === "translate" && dp.targetLanguage) target = dp.targetLanguage;+ if (spoken === undefined && dp.sourceLanguage) spoken = dp.sourceLanguage;+ todo.push(...depIds(rowOf(id)?.depends_on));+ }+ const input = { video, ...(langName(spoken) && { spoken_language: langName(spoken) }), ...(target && { translate_to: langName(target) ?? target }) };return { tool, studio, record: `captions:${burn.id}`, input, inputs: [{ path: ["video"], type: "video", label: "Video to caption" }], texts: [] };}return null;@@ -553,7 +650,8 @@ function proposeCheck(n: Node): RecipeCheck {const g = n.gen;const main = g.outputs.filter((o) => o.kind === g.kind);const check: RecipeCheck = { kind: g.kind as RecipeCheck["kind"] };- if (main.length) check.count = main.length;+ // A request that ran as several jobs makes as many rows as its route splits it into: its count isn't checked.+ if (main.length && !(n.jobs && n.jobs > 1)) check.count = main.length;const asked = (n.step.kind === "generate" ? (n.step.request.params as Record<string, unknown> | undefined)?.aspectRatio : undefined) ?? undefined;// The demo provider's stand-ins say nothing about a real result's shape or length: only what was asked.if (g.provider === "mock") {diff --git a/tests/recipe-builder.test.ts b/tests/recipe-builder.test.tsindex 724aa1e7..73489c88 100644--- a/tests/recipe-builder.test.ts+++ b/tests/recipe-builder.test.ts@@ -18,6 +18,7 @@ const gens = await import("@/server/generations");const { createPipeline } = await import("@/server/chains");const { db } = await import("@/server/db");const { saveFile } = await import("@/server/storage");+const { createElement } = await import("@/server/elements");const { encodePng } = await import("@/server/png");const builder = await import("@/server/recipe-builder");const recipes = await import("@/server/recipes");@@ -174,6 +175,13 @@ describe("draftFromGenerations", () => {// A shot of the same film stands for the film too.const shot = gens.listGenerations({ batchId: film.batchId! }).find((g) => g.request.step?.label === "Shot 1 of 2")!;expect(builder.draftFromGenerations([shot.id]).draft!.recipe.steps).toHaveLength(1);+ // Asked without an operation (Assist, MCP, the API), the step is named by what was asked, not by the join it ran as.+ const [bare] = gens.createGenerations({ feature: "video", modelId: "oss-wan22-14b-fast", prompt: "a heron in the reeds", params: { shots: [{ prompt: "it waits", duration: 3 }, { prompt: "it strikes", duration: 3 }] } });+ await settle([bare.id]);+ const named = builder.draftFromGenerations([bare.id]).draft!;+ expect(named.steps[0].label).toBe("Text to video");+ expect(named.recipe.steps[0].key).toBe("t2v");+ expect(named.recipe.steps[0].kind === "generate" && named.recipe.steps[0].request.op).toBeUndefined();// The same film made before W2: the rows, labelled, and no `asked`.row({ id: "old-shot-1", batch: "oldfilm", feature: "video", kind: "video", request: { feature: "video", modelId: "oss-wan22-14b-fast", op: "t2v", prompt: "a fox. it sniffs", step: { label: "Shot 1 of 2", index: 0, of: 3 } } });@@ -237,6 +245,13 @@ describe("draftFromGenerations", () => {row({ id: "cap-burn", feature: "captions", kind: "video", op: "captions", request: { feature: "captions", modelId: "veed-subtitles", op: "captions", inputs: { video: clip }, params: { sourceLanguage: "en", targetLanguage: "Spanish" } }, outputs: [{ url: clip, kind: "video" }] });const cap = builder.draftFromGenerations(["cap-burn"]).draft!;expect(cap.recipe.steps).toEqual([expect.objectContaining({ kind: "tool", tool: "add_captions", input: { video: clip, spoken_language: "English", translate_to: "Spanish" } })]);++ // On the open engine the languages are on the transcript and the translation the burn waited for.+ row({ id: "cap-words", batch: "capopen", feature: "captions", kind: "text", op: "transcribe", request: { feature: "captions", modelId: "oss-qwen3-asr", op: "transcribe", inputs: { video: clip }, params: { sourceLanguage: "es" } } });+ row({ id: "cap-tr", batch: "capopen", feature: "captions", kind: "text", op: "translate", request: { feature: "captions", modelId: "oss-text-llm", op: "translate", params: { targetLanguage: "French" }, chain: [{ slot: "prompt" }] }, dependsOn: "cap-words" });+ row({ id: "cap-open", batch: "capopen", feature: "captions", kind: "video", op: "captions", request: { feature: "captions", modelId: "oss-captions-burnin", op: "captions", inputs: { video: clip }, params: { extra: { fontSize: 48 } }, chain: [{ slot: "prompt" }] }, dependsOn: "cap-tr", outputs: [{ url: clip, kind: "video" }] });+ const open = builder.draftFromGenerations(["cap-open"]).draft!;+ expect(open.recipe.steps).toEqual([expect.objectContaining({ kind: "tool", tool: "add_captions", input: { video: clip, spoken_language: "Spanish", translate_to: "French" } })]);});it("links results handed on by hand (the composer's Animate) into a chain", async () => {@@ -270,6 +285,86 @@ describe("draftFromGenerations", () => {expect(Object.keys(draft!.recipe.checks ?? {})).toHaveLength(2);});+ it("makes a Library stack whose request ran as one job per result one step, as it was asked", () => {+ // A route that can't batch (a ComfyUI graph, Replicate without num_outputs) stores one row per result, each with the request.+ const req = { feature: "image", modelId: "nano-banana-pro", op: "t2i", prompt: "a teal armchair", params: { numOutputs: 4, aspectRatio: "1:1" } };+ const ids = [1, 2, 3, 4].map((i) => row({ id: `stack-${i}`, batch: "stackbatch", request: req, outputs: [{ url: `/api/files/outputs/stack-${i}.png`, kind: "image", width: 64, height: 64 }] }));+ for (const pick of [ids, [ids[2]]]) {+ const { draft, refusals } = builder.draftFromGenerations(pick);+ expect(refusals).toEqual([]);+ expect(draft!.recipe.steps).toHaveLength(1);+ const step = draft!.recipe.steps[0] as { key: string; request: { params?: { numOutputs?: number } } };+ // Four results, as asked: not four steps of four.+ expect(step.request.params?.numOutputs).toBe(4);+ expect(draft!.steps[0].notes).toContain("Ran as 4 jobs of one request: one step here");+ // How many rows a run makes depends on the route: the count isn't checked, even when it varies.+ expect(draft!.recipe.checks?.[step.key]).toEqual({ kind: "image", aspect: "1:1" });+ const takes = draft!.candidates.find((c) => c.setting === "numOutputs")!;+ expect(takes.example).toBe(4);+ const recipe = lib.buildRecipe(draft!, { varies: { [takes.id]: true } });+ expect(recipe.checks?.[step.key]?.count).toBeUndefined();+ expect(recipeProblems(recipe)).toEqual([]);+ }+ });++ it("makes a PixeletedFace run of several pictures one step", async () => {+ const made = gens.createGenerations({ feature: "image", modelId: "fuobe-soul", prompt: "a skater", engine: "cloud", presetId: "v1-pixeletedface", params: { numOutputs: 2, seed: 42 } });+ await settle(made.map((g) => g.id));+ const mosaics = made.filter((g) => !g.request.postMade);+ expect(mosaics).toHaveLength(2);+ const { draft, refusals } = builder.draftFromGenerations(mosaics.map((g) => g.id));+ expect(refusals).toEqual([]);+ expect(draft!.recipe.steps).toHaveLength(1);+ const step = draft!.recipe.steps[0] as { request: Record<string, unknown> & { params?: { numOutputs?: number; seed?: number } } };+ expect(step.request).toMatchObject({ modelId: "fuobe-soul", presetId: "v1-pixeletedface", engine: "cloud" });+ expect(step.request).not.toHaveProperty("postMade");+ expect(step.request.params).toMatchObject({ numOutputs: 2, seed: 42 });+ });++ it("refuses an Explainer episode and a Marketing Studio video's steps by name, and replays a Marketing picture", () => {+ row({ id: "ex-a", feature: "explainer", request: { feature: "explainer", modelId: "nano-banana-pro", op: "t2i", prompt: "scene 1" } });+ row({ id: "ex-b", feature: "explainer", kind: "video", request: { feature: "explainer", modelId: "kling-3", op: "i2v", prompt: "scene 1 moves", chain: [{ slot: "images" }] }, dependsOn: "ex-a" });+ row({ id: "mk-shot", feature: "marketing-step", kind: "video", request: { feature: "marketing-step", modelId: "kling-3", op: "t2v", prompt: "shot 1" } });+ row({ id: "mk-video", feature: "marketing", kind: "video", op: "concat", request: { feature: "marketing", modelId: "join-clips", op: "concat", chain: [{ slot: "videos" }] }, dependsOn: "mk-shot" });+ row({ id: "mk-photo", feature: "marketing", request: { feature: "marketing", modelId: "nano-banana-pro", op: "t2i", prompt: "Commercial product photograph of a lamp", params: { aspectRatio: "1:1" } } });+ const { draft, refusals } = builder.draftFromGenerations(["ex-b", "mk-video", "mk-photo"]);+ const why = Object.fromEntries(refusals.map((r) => [r.id, r.reason]));+ expect(why["ex-b"]).toBe(lib.notSupported("Explainer"));+ expect(why["mk-video"]).toBe(lib.notSupported("Marketing Studio"));+ expect(draft!.recipe.steps).toHaveLength(1);+ expect(draft!.steps[0].generation).toBe("mk-photo");+ });++ it("keeps the order of a list whose items earlier steps made, and says when it can't", () => {+ const out = (id: string, kind = "video") => [{ url: `/api/files/outputs/${id}.${kind === "video" ? "mp4" : "png"}`, kind }];+ const t = Date.now() - 60_000;+ const at = (id: string, ms: number) => db().prepare("UPDATE generations SET created_at = ? WHERE id = ?").run(t + ms, id);+ // A clip made first, then joined with an upload after it: the clip goes first, as it did.+ row({ id: "ord-c1", feature: "video", kind: "video", request: { feature: "video", modelId: "kling-3", op: "t2v", prompt: "a wave" }, outputs: out("ord-c1") });+ row({ id: "ord-join", feature: "video", kind: "video", op: "concat", request: { feature: "video", modelId: "join-clips", op: "concat", inputs: { videos: [out("ord-c1")[0].url, clip] } }, outputs: out("ord-join") });+ at("ord-c1", 0);+ at("ord-join", 1000);+ const join = builder.draftFromGenerations(["ord-join", "ord-c1"]).draft!;+ const j = join.recipe.steps.find((s) => s.kind === "generate" && s.request.op === "concat") as Extract<(typeof join.recipe.steps)[number], { kind: "generate" }>;+ expect(j.chain).toEqual([{ slot: "videos", position: "first" }]);+ expect(j.request.inputs).toEqual({ videos: [clip] });+ // A picture between two of the step's own goes last, and the step says so.+ row({ id: "ord-p", feature: "image", request: { feature: "image", modelId: "nano-banana-pro", op: "t2i", prompt: "a lamp" }, outputs: out("ord-p", "image") });+ row({ id: "ord-edit", feature: "edit", request: { feature: "edit", modelId: "nano-banana-pro", op: "edit", prompt: "together", inputs: { images: [photo, out("ord-p", "image")[0].url, "/api/files/uploads/other.png"] } }, outputs: out("ord-edit", "image") });+ at("ord-p", 2000);+ at("ord-edit", 3000);+ const edit = builder.draftFromGenerations(["ord-edit", "ord-p"]).draft!;+ const e = edit.recipe.steps.find((s) => s.kind === "generate" && s.request.op === "edit") as Extract<(typeof edit.recipe.steps)[number], { kind: "generate" }>;+ expect(e.chain).toEqual([{ slot: "images", position: "last" }]);+ expect(e.request.inputs).toEqual({ images: [photo, "/api/files/uploads/other.png"] });+ expect(edit.steps.find((s) => s.key === e.key)!.notes.some((n) => /another order/.test(n))).toBe(true);+ });++ it("keeps the engine an Original ran on in the request as asked", () => {+ const [clip0] = gens.createGenerations({ feature: "motion", modelId: "fuobe-dop", presetId: "effect-window", prompt: "a woman reading", inputs: { images: [photo] } });+ expect(clip0.request.asked?.engine).toBe(clip0.engine);+ });+it("answers over the API, refusing what isn't there", async () => {const res = await draftRoute.POST(json({ generations: ["nope"] }));expect(res.status).toBe(200);@@ -336,6 +431,24 @@ describe("choices, body, check and save", () => {expect(body).toContain("## Using Fuobe from an agent");});+ it("puts an element in for its @handle, and asks only for the prompt when the whole prompt varies too", () => {+ createElement({ name: "Maya", kind: "character", references: [photo] });+ row({ id: "el-shot", feature: "image", request: { feature: "image", modelId: "nano-banana-pro", op: "t2i", prompt: "@Maya walks on the beach" } });+ const { draft } = builder.draftFromGenerations(["el-shot"]);+ const el = draft!.candidates.find((c) => c.kind === "element")!;+ const words = draft!.candidates.find((c) => c.kind === "text")!;+ expect(el).toMatchObject({ type: "element", example: "@Maya" });+ const alone = lib.buildRecipe(draft!, { varies: { [el.id]: true } });+ expect(alone.params.map((p) => [p.id, p.type])).toEqual([[el.id, "element"]]);+ expect((alone.steps[0] as { request: { prompt: string } }).request.prompt).toBe(`{{${el.id}}} walks on the beach`);+ expect(recipeProblems(alone)).toEqual([]);+ // Both: the whole prompt carries the element, and there is no input left that nothing uses.+ const both = lib.buildRecipe(draft!, { varies: { [el.id]: true, [words.id]: true } });+ expect(both.params.map((p) => p.id)).toEqual([words.id]);+ expect((both.steps[0] as { request: { prompt: string } }).request.prompt).toBe(`{{${words.id}}}`);+ expect(recipeProblems(both)).toEqual([]);+ });+it("checks a draft for free with Demo mode off and no keys, saves it with what passed, and runs it", async () => {const p = await turntable();const { draft } = builder.draftFromGenerations([p.byKey.spin.id]);