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.

Catalog: the Genjutsu planner — four modes on both engines, Lite and full, setup codes

Claudedc390af28fdb
diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.ts
new file mode 100644
index 00000000..2b3e5532
--- /dev/null
+++ b/src/lib/catalog/genjutsu.ts
@@ -0,0 +1,919 @@
+/**
+ * Genjutsu (Higgsfield's /genjutsu): keep a clip's motion, camera and framing, change what is in it. Four modes:
+ * Motion transfer (your character does what the clip's person does), Object swap (a thing, a person or an outfit in
+ * the clip becomes your reference), Restyle (every frame takes a look) and Insert (your reference is added where you
+ * say). Higgsfield runs the first three on its Genjutsu models (Lite: motion and swap only, cheaper); Fuobe also runs
+ * every mode without a Higgsfield key (Kling O3 edit, Kling 3.0 Motion Control, hosted Wan 2.2 VACE, P-Video Replace,
+ * the Shorts restyle models) and on the open engine (Wan Animate 2, Wan 2.1 VACE swap and insert, the Shorts
+ * Fun VACE restyle chain).
+ *
+ * Every model takes a part of the clip (Genjutsu Lite 15 s, Kling 3–15 s, VACE 81 or 241 frames…), so longer
+ * selections are cut into pieces or windows, made one by one, joined, and the clip's own sound put back (the
+ * remove-object plumbing). Pure module (models per mode and engine, limits, prompts, prices, the pipeline's steps and
+ * the shareable setup code), shared by the page, the server (src/server/genjutsu.ts) and the tests.
+ * Research: docs/research/higgsfield-delta-4.md §4.2, paid-model-apis-4.md §4, comfyui-oss-4.md §c.
+ */
+import {
+ joinWithSound,
+ MASK_TRACKER,
+ planCloudPieces,
+ planFrameCuts,
+ planWindows,
+ REMOVE_TOOLS,
+ targetPhrase,
+ VACE_WINDOW,
+ wholeClip,
+ type FrameWindow,
+ type Piece,
+ type RemoveMode,
+ type RemoveRange,
+ type RemoveSource,
+} from "./remove-object";
+import { getShortsPreset, lookFromPreset, planShorts, type PlanStep, type ShortsLook } from "./shorts";
+import type { ChainSlot, Engine, GenerationRequest, PixelPoint } from "./types";
+
+export type GenjutsuMode = "motion" | "swap" | "restyle" | "insert";
+/** How you say what changes (Object swap and Insert): words, clicks on the first frame, or paint on it. */
+export type GenjutsuTarget = RemoveMode;
+export type GenjutsuQuality = "480p" | "720p" | "1080p";
+/** Genjutsu Lite ("standard") or Genjutsu ("high"). */
+export type GenjutsuTier = "standard" | "high";
+
+export const GENJUTSU = {
+ feature: "genjutsu",
+ /** Cuts, tracks, pieces, joins and the sound: kept apart from the finished videos. */
+ stepFeature: "genjutsu-step",
+ /** Higgsfield's source window: "Choose a source video between 4 and 30 seconds". */
+ minSeconds: 4,
+ maxSeconds: 30,
+ maxBytes: 200 * 1024 * 1024,
+ /** "Transfer motion or swap objects with up to 10 reference images". */
+ maxReferences: 10,
+ /** A custom Restyle look: RESTYLE_CUSTOM_PRESET_IMAGE_LIMIT. */
+ maxLookImages: 8,
+ maxPoints: 12,
+ maxPromptChars: 2000,
+ qualities: ["480p", "720p", "1080p"] as GenjutsuQuality[],
+ defaultQuality: "720p" as GenjutsuQuality,
+ accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",
+} as const;
+
+export const GENJUTSU_MODES: { id: GenjutsuMode; label: string; hint: string; refs: string }[] = [
+ { id: "motion", label: "Motion transfer", hint: "The movement and camera stay exactly as filmed. Swap in your character.", refs: "Your character" },
+ { id: "swap", label: "Object swap", hint: "Swap a thing, a person or an outfit in the clip for your reference — everything else stays.", refs: "What goes in" },
+ { id: "restyle", label: "Restyle", hint: "Pick a style or bring your own images. Every frame takes the look — motion, camera, and framing stay as filmed.", refs: "Characters (optional)" },
+ { id: "insert", label: "Insert", hint: "Add your reference to the shot — say where, or paint the spot on the first frame.", refs: "What to add" },
+];
+
+export const getMode = (id: GenjutsuMode) => GENJUTSU_MODES.find((m) => m.id === id)!;
+
+/** The ways of saying what changes, per mode (Motion transfer and Restyle change the whole shot). */
+export const MODE_TARGETS: Record<GenjutsuMode, GenjutsuTarget[]> = { motion: [], restyle: [], swap: ["type", "click", "paint"], insert: ["type", "paint"] };
+
+export const TARGET_LABELS: Record<GenjutsuMode, Partial<Record<GenjutsuTarget, { label: string; hint: string }>>> = {
+ motion: {},
+ restyle: {},
+ swap: {
+ type: { label: "Type it", hint: "Name what to swap" },
+ click: { label: "Click it", hint: "Click it on the first frame" },
+ paint: { label: "Paint it", hint: "Brush over it on the first frame" },
+ },
+ insert: {
+ type: { label: "Say where", hint: "Describe where it goes" },
+ paint: { label: "Paint the spot", hint: "Brush where it goes on the first frame" },
+ },
+};
+
+// ---------------------------------------------------------------------------
+// Models ("makers")
+
+export interface Maker {
+ /** The catalog model. */
+ id: string;
+ engine: Engine;
+ modes: GenjutsuMode[];
+ /** Object swap and Insert: how it is told what changes. */
+ targets?: GenjutsuTarget[];
+ label: string;
+ /** One line for the picker: what it's good at and its limits (open: GPU and licence). */
+ note: string;
+ /** Runs on Higgsfield's own API (a Higgsfield key; demo mode without one). */
+ higgsfield?: boolean;
+ /** Genjutsu Lite or Genjutsu, and the other one. */
+ tier?: GenjutsuTier;
+ pair?: string;
+ /** Reference images it takes (extra ones are left out, said in a note). */
+ refs: { min: number; max: number };
+ /** Cloud: the longest piece one call takes, in seconds. */
+ maxSeconds?: number;
+ minSeconds?: number;
+ /** Routes that count frames: one call per window of whole frames (see remove-object's FrameWindow). */
+ window?: FrameWindow;
+ maxFps?: number;
+ /** The result carries the piece's own sound (otherwise the clip's sound is put back). */
+ keepsSound: boolean;
+ /** The resolutions it renders; the quality asked for goes to the nearest (none: it keeps the clip's size). */
+ qualities?: string[];
+ /** Words aren't needed (Genjutsu and P-Video find what to swap from the references). */
+ promptOptional?: boolean;
+ /** Swaps the person on camera only. */
+ people?: boolean;
+ /** The fewest pixels a frame may have (Genjutsu Object Swap: 409,600). */
+ minPixels?: number;
+ /** Each side of the picture must be within this many pixels (Kling O3 edit: 720–3840). */
+ sides?: { min: number; max: number };
+ /** Restyle: the looks it takes — Higgsfield's own list, or Fuobe's presets and custom looks. */
+ looks?: "higgsfield" | "fuobe";
+ /** Restyle on Fuobe looks: it reads the look's reference images. */
+ readsLookImages?: number;
+}
+
+/** fal's hosted Wan 2.2 VACE Fun: 17–241 frames (4n+1, the clip's own count and rate), at most 30 fps. */
+const VACE_CLOUD_WINDOW: FrameWindow = { cap: 241, step: 4, base: 1, min: 17 };
+const VACE_CLOUD = "wan-22-vace-inpaint";
+const HIGH_RES = ["480p", "720p", "1080p"];
+
+export const MAKERS: Maker[] = [
+ // Motion transfer (cloud).
+ {
+ id: "genjutsu-lite-motion-transfer",
+ engine: "cloud",
+ modes: ["motion"],
+ label: "Genjutsu Lite",
+ note: "Higgsfield's own · up to 15 s a call · up to 8 references · sound kept",
+ higgsfield: true,
+ tier: "standard",
+ pair: "genjutsu-motion-transfer",
+ refs: { min: 1, max: 8 },
+ maxSeconds: 15,
+ minSeconds: 4,
+ keepsSound: true,
+ qualities: HIGH_RES,
+ },
+ {
+ id: "genjutsu-motion-transfer",
+ engine: "cloud",
+ modes: ["motion"],
+ label: "Genjutsu",
+ note: "Higgsfield's full model · up to 30 s · up to 8 references · sound kept",
+ higgsfield: true,
+ tier: "high",
+ pair: "genjutsu-lite-motion-transfer",
+ refs: { min: 1, max: 8 },
+ maxSeconds: 30,
+ minSeconds: 4,
+ keepsSound: true,
+ qualities: HIGH_RES,
+ },
+ {
+ id: "kling-motion-control",
+ engine: "cloud",
+ modes: ["motion"],
+ label: "Kling 3.0 Motion Control",
+ note: "No Higgsfield key needed · one character image · pieces of up to 10 s",
+ refs: { min: 1, max: 1 },
+ maxSeconds: 10,
+ minSeconds: 3,
+ keepsSound: false,
+ },
+ // Object swap (cloud).
+ {
+ id: "genjutsu-lite-object-swap",
+ engine: "cloud",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "Genjutsu Lite",
+ note: "Higgsfield's own · objects, characters or clothes · up to 15 s a call · words optional",
+ higgsfield: true,
+ tier: "standard",
+ pair: "genjutsu-object-swap",
+ refs: { min: 1, max: 8 },
+ maxSeconds: 15,
+ minSeconds: 4,
+ keepsSound: true,
+ qualities: HIGH_RES,
+ promptOptional: true,
+ },
+ {
+ id: "genjutsu-object-swap",
+ engine: "cloud",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "Genjutsu",
+ note: "Higgsfield's full model · up to 30 s · words optional",
+ higgsfield: true,
+ tier: "high",
+ pair: "genjutsu-lite-object-swap",
+ refs: { min: 1, max: 8 },
+ maxSeconds: 30,
+ minSeconds: 4,
+ keepsSound: true,
+ qualities: HIGH_RES,
+ promptOptional: true,
+ minPixels: 409_600,
+ },
+ {
+ id: "kling-o3",
+ engine: "cloud",
+ modes: ["swap", "insert"],
+ targets: ["type"],
+ label: "Kling O3 Omni edit",
+ note: "No Higgsfield key needed · up to 4 references as @Image · 3–15 s a piece · keeps the clip's size",
+ refs: { min: 1, max: 4 },
+ maxSeconds: 15,
+ minSeconds: 3,
+ keepsSound: true,
+ sides: { min: 720, max: 3840 },
+ },
+ {
+ id: "p-video-replace",
+ engine: "cloud",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "P-Video Replace",
+ note: "Swaps the person on camera for 1–3 photos of someone · motion, timing and scene kept",
+ refs: { min: 1, max: 3 },
+ keepsSound: true,
+ qualities: ["720p", "1080p"],
+ promptOptional: true,
+ people: true,
+ },
+ {
+ id: VACE_CLOUD,
+ engine: "cloud",
+ modes: ["swap", "insert"],
+ targets: ["click", "paint"],
+ label: "Wan 2.2 VACE (hosted)",
+ note: "Changes exactly the area you mark · up to 4 references · 241 frames a piece · up to 30 fps",
+ refs: { min: 1, max: 4 },
+ window: VACE_CLOUD_WINDOW,
+ maxFps: 30,
+ keepsSound: false,
+ qualities: ["480p", "580p", "720p"],
+ },
+ // Restyle (cloud).
+ {
+ id: "genjutsu-restyle",
+ engine: "cloud",
+ modes: ["restyle"],
+ label: "Genjutsu Restyle",
+ note: "Higgsfield's own looks · up to 30 s · up to 5 character references · sound kept",
+ higgsfield: true,
+ refs: { min: 0, max: 5 },
+ maxSeconds: 30,
+ minSeconds: 4,
+ keepsSound: true,
+ qualities: HIGH_RES,
+ looks: "higgsfield",
+ },
+ {
+ id: "gemini-omni-flash",
+ engine: "cloud",
+ modes: ["restyle"],
+ label: "Gemini Omni Flash 1.1",
+ note: "Higgsfield's Shorts engine · restyles from the look's words · pieces of up to 10 s",
+ refs: { min: 0, max: 0 },
+ keepsSound: false,
+ qualities: ["720p", "1080p"],
+ looks: "fuobe",
+ },
+ {
+ id: "kling-o3-4k-edit",
+ engine: "cloud",
+ modes: ["restyle"],
+ label: "Kling O3 4K Edit",
+ note: "Reads up to 4 of the look's images · 4K · pieces of up to 10 s",
+ refs: { min: 0, max: 0 },
+ keepsSound: false,
+ looks: "fuobe",
+ readsLookImages: 4,
+ },
+ {
+ id: "happy-horse-video-edit",
+ engine: "cloud",
+ modes: ["restyle"],
+ label: "Happy Horse Video Edit",
+ note: "Reads up to 4 of the look's images · billed on the clip's seconds too",
+ refs: { min: 0, max: 0 },
+ keepsSound: false,
+ qualities: ["720p", "1080p"],
+ looks: "fuobe",
+ readsLookImages: 4,
+ },
+ // Open (workflows/comfyui/manifest.json).
+ {
+ id: "oss-wan22-animate",
+ engine: "open",
+ modes: ["motion"],
+ label: "Wan Animate 2",
+ note: "Your character copies the clip's performance, in 81-frame fragments · one character image · 24 GB GPU · Apache-2.0",
+ refs: { min: 1, max: 1 },
+ keepsSound: true,
+ qualities: ["480p", "720p"],
+ },
+ {
+ id: "oss-vace-swap",
+ engine: "open",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "Wan 2.1 VACE + SAM 3.1",
+ note: "SAM 3.1 follows what you name, VACE paints your first reference in · 24 GB GPU · Apache-2.0",
+ refs: { min: 1, max: 1 },
+ window: VACE_WINDOW,
+ keepsSound: true,
+ qualities: ["480p", "720p"],
+ },
+ {
+ id: "oss-vace-insert",
+ engine: "open",
+ modes: ["insert"],
+ targets: ["paint"],
+ label: "Wan 2.1 VACE",
+ note: "Your first reference in the painted spot, held for the whole shot (a still or slow camera) · 24 GB GPU · Apache-2.0",
+ refs: { min: 1, max: 1 },
+ window: VACE_WINDOW,
+ keepsSound: true,
+ qualities: ["480p", "720p"],
+ },
+ {
+ id: "oss-wan22-vace-restyle",
+ engine: "open",
+ modes: ["restyle"],
+ label: "Wan 2.2 Fun VACE",
+ note: "The Shorts chain: the first frame restyled (Qwen-Image-Edit, 2 of the look's images), then every frame with depth · 5 s segments at 16 fps, 480p",
+ refs: { min: 0, max: 0 },
+ keepsSound: false,
+ looks: "fuobe",
+ readsLookImages: 2,
+ },
+];
+
+export const getMaker = (id: string | undefined) => MAKERS.find((m) => m.id === id);
+
+/** The models you can pick for this engine, mode and way of pointing (and, for Restyle, kind of look). */
+export function makersFor(engine: Engine, mode: GenjutsuMode, target?: GenjutsuTarget, look?: GenjutsuLook): Maker[] {
+ return MAKERS.filter((m) => {
+ if (m.engine !== engine || !m.modes.includes(mode)) return false;
+ if (MODE_TARGETS[mode].length && !(m.targets ?? []).includes(target ?? MODE_TARGETS[mode][0])) return false;
+ // Genjutsu Lite and Genjutsu are one choice in the picker (Quality: Standard / High).
+ if (m.tier === "high") return false;
+ if (mode === "restyle" && look) return m.looks === (look.kind === "higgsfield" ? "higgsfield" : "fuobe");
+ return true;
+ });
+}
+
+export const OPEN_TARGET_PROBLEM: Partial<Record<GenjutsuMode, string>> = {
+ swap: "On your ComfyUI, name what to swap — clicking and painting are on the cloud engine",
+ insert: "On your ComfyUI, paint where it goes — saying it in words is on the cloud engine",
+};
+
+/**
+ * The model a request runs on, or why there is none. Without a modelId: Genjutsu (Lite unless Quality is High) with a
+ * Higgsfield key, else the keyless route for the mode; on the open engine, the one graph that does the mode.
+ */
+export function chooseMaker(o: {
+ engine: Engine;
+ mode: GenjutsuMode;
+ target?: GenjutsuTarget;
+ tier?: GenjutsuTier;
+ look?: GenjutsuLook;
+ modelId?: string;
+ /** A Higgsfield key is set. */
+ higgsfield: boolean;
+}): { maker: Maker } | { problem: string } {
+ const target = MODE_TARGETS[o.mode].length ? (o.target ?? MODE_TARGETS[o.mode][0]) : undefined;
+ if (target && !MODE_TARGETS[o.mode].includes(target)) return { problem: `${getMode(o.mode).label} doesn't take ${target === "click" ? "clicks" : "that"} — pick another way` };
+ const options = makersFor(o.engine, o.mode, target, o.look);
+ if (!options.length) return { problem: (o.engine === "open" && OPEN_TARGET_PROBLEM[o.mode]) || "Nothing on this engine does that yet" };
+ const withTier = (m: Maker) => (m.pair && o.tier && m.tier !== o.tier ? (getMaker(m.pair) ?? m) : m);
+ const picked = getMaker(o.modelId);
+ if (picked) {
+ // The picker lists the Lite model; a High pick (or an old setup naming the full model) is the same choice.
+ const lite = picked.tier === "high" && picked.pair ? getMaker(picked.pair)! : picked;
+ if (options.includes(lite)) return { maker: withTier(lite) };
+ }
+ const first = (o.higgsfield ? options.find((m) => m.higgsfield) : undefined) ?? options.find((m) => !m.higgsfield) ?? options[0];
+ // Restyle with a custom look: a model that reads its images.
+ if (o.mode === "restyle" && o.look?.kind === "custom" && o.engine === "cloud") return { maker: options.find((m) => m.readsLookImages) ?? first };
+ return { maker: withTier(first) };
+}
+
+// ---------------------------------------------------------------------------
+// Looks (Restyle)
+
+export type GenjutsuLook =
+ /** One of the 44 Shorts presets (Fuobe's words). */
+ | { kind: "preset"; id: string }
+ /** One of Higgsfield's live Genjutsu looks (its preset_id). */
+ | { kind: "higgsfield"; id: string; name?: string }
+ /** Your own look from up to 8 images, and words if you like. */
+ | { kind: "custom"; images: string[]; words?: string };
+
+/** The Shorts look a Fuobe look restyles with (null: Higgsfield's own, or an unknown preset). */
+export function shortsLook(look: GenjutsuLook): ShortsLook | null {
+ if (look.kind === "preset") {
+ const p = getShortsPreset(look.id);
+ return p ? lookFromPreset(p) : null;
+ }
+ if (look.kind !== "custom") return null;
+ const words = look.words?.trim().replace(/[.\s]+$/, "");
+ return {
+ presetId: "genjutsu-custom",
+ name: "Your look",
+ look: words ? `the look of the reference images: ${words}` : "the look of the reference images: their colours, textures, lighting and graphic style",
+ references: look.images.slice(0, GENJUTSU.maxLookImages),
+ custom: true,
+ described: !!words,
+ };
+}
+
+export function lookName(look: GenjutsuLook | undefined): string {
+ if (!look) return "a look";
+ if (look.kind === "preset") return getShortsPreset(look.id)?.name ?? "a look";
+ if (look.kind === "higgsfield") return look.name || "a Higgsfield look";
+ return "your look";
+}
+
+// ---------------------------------------------------------------------------
+// Prices
+
+/**
+ * Per-second list prices the catalog doesn't carry per resolution: Higgsfield's Genjutsu tiers (billed on whole
+ * seconds; higgsfield-api.json, 50% off on 2026-10-22 and not counted here) and Kling O3's video edit ($0.168/s,
+ * paid-model-apis-4.md §4; the catalog's Kling O3 price is its text-to-video one).
+ */
+export const MAKER_USD: Record<string, Record<string, number>> = {
+ "genjutsu-motion-transfer": { "480p": 0.318, "720p": 0.681, "1080p": 1.632 },
+ "genjutsu-object-swap": { "480p": 0.318, "720p": 0.681, "1080p": 1.632 },
+ "genjutsu-restyle": { "480p": 0.318, "720p": 0.681, "1080p": 1.632 },
+ "genjutsu-lite-motion-transfer": { "480p": 0.05, "720p": 0.1, "1080p": 0.2 },
+ "genjutsu-lite-object-swap": { "480p": 0.05, "720p": 0.1, "1080p": 0.2 },
+ "kling-o3": { any: 0.168 },
+};
+
+/** A step's own price when MAKER_USD has it (null: the catalog's price applies). */
+export function makerStepUsd(modelId: string, params: { duration?: number; resolution?: string } | undefined): number | null {
+ const table = MAKER_USD[modelId];
+ if (!table) return null;
+ const usd = table[params?.resolution ?? ""] ?? table.any ?? table["720p"];
+ const secs = params?.duration ?? 0;
+ // Higgsfield rounds each call up to whole seconds.
+ return usd * (modelId.startsWith("genjutsu") ? Math.ceil(secs - 1e-6) : secs);
+}
+
+/** The resolution a model is asked for: the quality picked, or the nearest it renders (the largest not above, else its smallest). */
+export function qualityFor(m: Maker, quality: string): string | undefined {
+ if (!m.qualities?.length) return undefined;
+ if (m.qualities.includes(quality)) return quality;
+ const p = (q: string) => parseInt(q, 10) || 0;
+ const below = m.qualities.filter((q) => p(q) <= p(quality)).sort((a, b) => p(b) - p(a));
+ return below[0] ?? [...m.qualities].sort((a, b) => p(a) - p(b))[0];
+}
+
+// ---------------------------------------------------------------------------
+// Words
+
+const tidy = (s: string | undefined) => (s ?? "").trim().replace(/[.\s]+$/, "");
+const cap = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);
+const imageTags = (n: number) => Array.from({ length: n }, (_, i) => `@Image${i + 1}`).join(", ");
+
+const SWAP = /^\s*(?:please\s+)?(?:replace|swap(?:\s+out)?|change|turn|exchange|substitute)\s+(.+?)\s+(?:with|for|into|by|to)\s+(.+)$/i;
+
+/** "Replace the red car with a horse" → what goes ("the red car") and what comes in ("a horse"); a bare name is what goes. */
+export function swapParts(text: string): { what: string; into?: string } {
+ const m = SWAP.exec(text.trim());
+ return m ? { what: tidy(m[1]), into: tidy(m[2]) } : { what: tidy(text) };
+}
+
+/**
+ * What a sentence says to swap, for SAM 3.1 to track on the open engine: "Replace the red car with a horse" → "the red
+ * car"; a bare name stays as it is (as remove-object's targetPhrase: the objects alone, comma-separated).
+ */
+export function swapTarget(text: string): string {
+ return targetPhrase(swapParts(text).what);
+}
+
+export interface PromptInput {
+ mode: GenjutsuMode;
+ maker: Maker;
+ /** Object swap: what goes. */
+ subject?: string;
+ /** Guidance: the result (swap), where it goes (insert), the character (motion), extra words (restyle). */
+ prompt?: string;
+ refs: number;
+}
+
+/** Each model's words for the request (undefined: none needed). */
+export function makerPrompt(p: PromptInput): string | undefined {
+ const m = p.maker;
+ const words = tidy(p.prompt);
+ const { what, into } = swapParts(p.subject ?? "");
+ const also = into ? ` (${into})` : "";
+ if (m.id === "kling-o3") {
+ const refs = imageTags(Math.max(1, p.refs));
+ if (p.mode === "insert") return `Add ${refs} to @Video1${words ? `: ${words}` : ""}. Keep everything else the same: the motion, camera, framing and light.`;
+ return `Replace ${what || "the main subject"} in @Video1 with ${refs}${also}${words ? `. ${cap(words)}` : ""}. Keep everything else the same: the motion, camera, framing and light.`;
+ }
+ if (m.id === VACE_CLOUD || m.id === "oss-vace-swap" || m.id === "oss-vace-insert") {
+ // VACE's prompt describes the result; the mask (or SAM's track) says where.
+ if (words) return `${cap(words)}, matching the light, perspective and motion of the shot.`;
+ if (p.mode === "insert") return "The object from the reference image in the marked area, matching the light, perspective and motion of the shot.";
+ if (into) return `${cap(into)} in place of ${what}, matching the light, perspective and motion of the shot.`;
+ return `${what ? `${cap(what)} replaced by` : "The marked area becomes"} the object from the reference image, matching the light, perspective and motion of the shot.`;
+ }
+ if (p.mode === "swap") {
+ const lead = what ? `Replace ${what} with the reference${p.refs > 1 ? "s" : ""}${also}.` : "";
+ const out = [lead, words ? `${cap(words)}.` : ""].filter(Boolean).join(" ");
+ return out || undefined;
+ }
+ if (p.mode === "restyle" && m.looks === "higgsfield") return words ? `${cap(words)}.` : "Keep the motion, camera and framing exactly as filmed.";
+ return words ? `${cap(words)}.` : undefined;
+}
+
+/** A short name for the result ("Genjutsu · Motion transfer"). */
+export function genjutsuTitle(o: { mode: GenjutsuMode; subject?: string; look?: GenjutsuLook }): string {
+ if (o.mode === "restyle") return `Genjutsu · ${lookName(o.look)}`;
+ const s = tidy(o.subject);
+ if (o.mode === "swap" && s) return `Genjutsu · swap ${s.length > 48 ? `${s.slice(0, 45)}…` : s}`;
+ return `Genjutsu · ${getMode(o.mode).label.toLowerCase()}`;
+}
+
+// ---------------------------------------------------------------------------
+// Checks
+
+export interface GenjutsuCheck {
+ mode: GenjutsuMode;
+ maker: Maker;
+ source: RemoveSource;
+ range: RemoveRange;
+ references: number;
+ target?: GenjutsuTarget;
+ subject?: string;
+ prompt?: string;
+ points?: number;
+ mask?: boolean;
+ look?: GenjutsuLook;
+}
+
+/** What's wrong with the selection whatever the model, or null. */
+export function rangeProblem(source: Pick<RemoveSource, "duration">, range: RemoveRange): string | null {
+ const len = range.end - range.start;
+ if (!(len > 0) || range.start < 0) return "Pick a part of the clip";
+ if (source.duration !== undefined && range.end > source.duration + 0.05) return "The selection runs past the end of the clip";
+ if (len < GENJUTSU.minSeconds - 0.05) return `Choose a part between ${GENJUTSU.minSeconds} and ${GENJUTSU.maxSeconds} seconds (this is ${len.toFixed(1)} s)`;
+ if (len > GENJUTSU.maxSeconds + 0.05) return `Choose up to ${GENJUTSU.maxSeconds} seconds — trim the clip with the handles`;
+ return null;
+}
+
+const REFS_MISSING: Record<GenjutsuMode, string> = {
+ motion: "Add a picture of your character",
+ swap: "Add a picture of what goes in",
+ insert: "Add a picture of what to add",
+ restyle: "",
+};
+
+/** The first thing that stops this request, in words, or null. */
+export function genjutsuProblem(c: GenjutsuCheck): string | null {
+ const general = rangeProblem(c.source, c.range);
+ if (general) return general;
+ const m = c.maker;
+ const len = c.range.end - c.range.start;
+ const { width: w, height: h } = c.source;
+ if (m.minSeconds && len < m.minSeconds - 0.01) return `${m.label} needs at least ${m.minSeconds} s`;
+ if (m.sides && w && h) {
+ if (Math.min(w, h) < m.sides.min) return `${m.label} needs a clip at least ${m.sides.min} px on each side (this one is ${w}×${h})`;
+ if (Math.max(w, h) > m.sides.max) return `${m.label} takes clips up to ${m.sides.max} px on a side (this one is ${w}×${h})`;
+ }
+ if (m.minPixels && w && h && w * h < m.minPixels) return `${m.label} needs a sharper clip (at least ${Math.round(m.minPixels / 1000)} thousand pixels a frame; this one is ${w}×${h}) — Genjutsu Lite takes it`;
+ if (m.window && !c.source.fps) return "Couldn't read this clip's frame rate — save it as an MP4 (H.264) and try again";
+ if (m.maxFps && c.source.fps && c.source.fps > m.maxFps + 0.01) return `${m.label} takes up to ${m.maxFps} fps (this clip is ${Math.round(c.source.fps)} fps) — pick another model`;
+ if (c.mode !== "restyle" && c.references < Math.max(1, m.refs.min)) return REFS_MISSING[c.mode];
+ if (c.mode === "restyle") {
+ if (!c.look) return "Pick a look";
+ if (c.look.kind === "custom" && !c.look.images.length) return "Add up to 8 images for your look";
+ if (m.looks === "higgsfield" && c.look.kind !== "higgsfield") return "Genjutsu Restyle takes Higgsfield's looks — pick one of them";
+ if (m.looks === "fuobe" && c.look.kind === "higgsfield") return "Higgsfield's looks run on Genjutsu Restyle";
+ if (c.look.kind === "custom" && !m.readsLookImages && !c.look.words?.trim()) return `${m.label} restyles from words only — describe your look, or pick Kling O3 4K Edit`;
+ }
+ const target = MODE_TARGETS[c.mode].length ? (c.target ?? MODE_TARGETS[c.mode][0]) : undefined;
+ if (target === "type") {
+ if (c.mode === "swap" && !m.promptOptional && !c.subject?.trim()) return "Say what to swap, e.g. “the red car”";
+ if (c.mode === "insert" && !c.prompt?.trim()) return "Say where it goes, e.g. “on the table, next to the cup”";
+ }
+ if (target === "click" && !c.points) return "Click what to swap on the first frame";
+ if (target === "paint" && !c.mask) return c.mode === "insert" ? "Paint where it goes on the first frame" : "Paint over what to swap";
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Pieces
+
+/** The pieces a selection is made in: windows on the open engine, frame cuts or equal cuts on the cloud, or one. */
+export function planMakerPieces(m: Maker, source: RemoveSource, range: RemoveRange): Piece[] {
+ if (m.window) {
+ if (!source.fps) return [];
+ return m.engine === "open" ? planWindows(range, source.fps, m.window) : planFrameCuts(range, source.fps, m.window);
+ }
+ if (m.maxSeconds) return planCloudPieces(range, m.maxSeconds, source.fps);
+ return [{ index: 0, start: range.start, end: range.end }];
+}
+
+// ---------------------------------------------------------------------------
+// The pipeline
+
+export interface GenjutsuPlanInput {
+ engine: Engine;
+ mode: GenjutsuMode;
+ maker: Maker;
+ title: string;
+ source: RemoveSource;
+ range: RemoveRange;
+ quality: string;
+ /** Reference images (the model takes its first refs.max). */
+ references: string[];
+ target?: GenjutsuTarget;
+ subject?: string;
+ prompt?: string;
+ /** Click it: points on the range's first frame, in the clip's pixels (paint on the cloud: points found in the paint). */
+ points?: PixelPoint[];
+ /** Paint it: the mask of the range's first frame (white = what changes, or where it goes). */
+ mask?: string;
+ look?: GenjutsuLook;
+ seed?: number;
+}
+
+export interface GenjutsuPlan {
+ steps: PlanStep[];
+ /** The finished video's step. */
+ final: string;
+ /** Pieces (cloud), windows (open) or segments (Restyle on Fuobe looks). */
+ pieces: number;
+ /** The clip's own sound is put back on the joined result. */
+ sound: boolean;
+ /** Cloud clicks and paint: SAM 3.1 follows the object through the selection first. */
+ tracked: boolean;
+}
+
+const r3 = (n: number) => Math.round(n * 1000) / 1000;
+const r6 = (n: number) => Math.round(n * 1e6) / 1e6;
+const pieceLabel = (p: Piece, n: number, what: string) => ({ label: n > 1 ? `Piece ${p.index + 1} of ${n} · ${what}` : what[0].toUpperCase() + what.slice(1), index: p.index, of: n });
+
+const OP: Record<GenjutsuMode, GenerationRequest["op"]> = { motion: "motion-transfer", swap: "video-swap", insert: "video-insert", restyle: "v2v" };
+
+/**
+ * The whole job, as steps for createPipeline (src/server/chains.ts):
+ * - Restyle on Fuobe looks: the Shorts chain (segments restyled, joined, the sound put back) in the clip's own shape;
+ * - open VACE swap / insert: one window per job straight from the upload (the graph reads its own window), the
+ * painted spot the same in every window; Wan Animate 2: the selection in one job (it loops its own fragments);
+ * - cloud: the selection cut into pieces, each made with the references; marked areas for the hosted VACE come from
+ * the paint (one piece) or SAM 3.1's track of it (clicks, or paint over several pieces: each piece's first frame);
+ * - then the pieces joined and the clip's own sound put back.
+ */
+export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
+ if (input.mode === "restyle" && input.maker.looks === "fuobe") return planFuobeRestyle(input);
+ const m = input.maker;
+ const t = REMOVE_TOOLS[m.engine];
+ const pieces = planMakerPieces(m, input.source, input.range);
+ if (!pieces.length) throw new Error(genjutsuProblem({ ...input, references: input.references.length, points: input.points?.length, mask: !!input.mask }) ?? "Select a little more of the clip");
+ const n = pieces.length;
+ const whole = wholeClip(input.range, input.source.duration);
+ const base = { feature: GENJUTSU.feature, batchTitle: input.title };
+ const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };
+ const steps: PlanStep[] = [];
+ const op = OP[input.mode];
+ const sound = !!input.source.hasAudio && (n > 1 || !m.keepsSound);
+ const own = (one: boolean) => (one && !sound ? { ...base, title: input.title } : helper);
+ const refs = input.references.slice(0, m.refs.max);
+ const images = refs.length ? { images: refs } : {};
+ const seed = input.seed !== undefined ? { seed: input.seed } : {};
+ const resolution = qualityFor(m, input.quality);
+ const prompt = makerPrompt({ mode: input.mode, maker: m, subject: input.subject, prompt: input.prompt, refs: refs.length });
+ const words = prompt ? { prompt } : {};
+ const target = MODE_TARGETS[input.mode].length ? (input.target ?? MODE_TARGETS[input.mode][0]) : undefined;
+ const lookParams = input.mode === "restyle" && input.look?.kind === "higgsfield" ? { extra: { preset_id: input.look.id } } : {};
+ const keys = pieces.map((_, i) => `make${i}`);
+
+ if (m.engine === "open" && m.window) {
+ // VACE windows: the graph reads [startTime, endTime) of the upload itself.
+ pieces.forEach((p, i) => {
+ steps.push({
+ key: keys[i],
+ request: {
+ ...own(n === 1),
+ modelId: m.id,
+ op,
+ ...words,
+ inputs: { video: input.source.url, ...images, ...(input.mask ? { mask: input.mask } : {}) },
+ params: {
+ startTime: p.startTime,
+ endTime: p.endTime,
+ aspectRatio: "auto",
+ ...(resolution ? { resolution } : {}),
+ ...seed,
+ ...(input.mode === "swap" && input.subject?.trim() ? { extra: { maskPrompt: swapTarget(input.subject) } } : {}),
+ },
+ step: pieceLabel(p, n, input.mode === "insert" ? "add it" : "swap it"),
+ },
+ });
+ });
+ } else if (m.engine === "open") {
+ // Wan Animate 2 runs the whole selection (its graph loops 81-frame fragments) and keeps the clip's fps and sound.
+ const cut = !whole;
+ if (cut) steps.push({ key: "cut0", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Cut the selection", index: 0, of: 1 } } });
+ steps.push({
+ key: keys[0],
+ request: {
+ ...own(true),
+ modelId: m.id,
+ op,
+ ...words,
+ inputs: { ...(cut ? {} : { video: input.source.url }), ...images },
+ params: { aspectRatio: "auto", ...(resolution ? { resolution } : {}), ...seed },
+ step: { label: "Transfer the motion", index: 0, of: 1 },
+ },
+ ...(cut ? { after: ["cut0"], chain: [{ slot: "video" as const }] } : {}),
+ });
+ } else {
+ // Cloud. The hosted VACE reads a still mask of its piece's first frame and tracks it: the paint for one piece,
+ // else SAM 3.1's track of the clicks or the paint, cut like the clip, its first frame for each piece.
+ const tracked = m.id === VACE_CLOUD && input.mode === "swap" && (target === "click" || n > 1);
+ const cutRange = tracked && !whole;
+ if (cutRange) {
+ steps.push({ key: "range", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Cut the selection", index: 0, of: 1 } } });
+ }
+ if (tracked) {
+ steps.push({
+ key: "track",
+ request: {
+ ...helper,
+ modelId: MASK_TRACKER,
+ op: "bg-remove-video",
+ ...(cutRange ? {} : { inputs: { video: input.source.url } }),
+ params: { points: input.points, duration: r3(input.range.end - input.range.start) },
+ step: { label: "Follow what you marked (SAM 3.1)", index: 0, of: 1 },
+ },
+ ...(cutRange ? { after: ["range"], chain: [{ slot: "video" as const }] } : {}),
+ });
+ }
+ pieces.forEach((p, i) => {
+ // One piece that is the whole upload is read as it is (a frame-count piece only when it is every frame).
+ const one = n === 1 && whole && (!p.frames || p.end >= (input.source.duration ?? 0) - 0.05);
+ const after: string[] = [];
+ const chain: ChainSlot[] = [];
+ if (n === 1 && cutRange) {
+ after.push("range");
+ chain.push({ slot: "video" });
+ } else if (!one) {
+ steps.push({ key: `cut${i}`, request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: p.start, endTime: p.end }, step: pieceLabel(p, n, "cut") } });
+ after.push(`cut${i}`);
+ chain.push({ slot: "video" });
+ }
+ let mask: string | undefined;
+ if (m.id === VACE_CLOUD) {
+ // Insert holds the painted spot in every piece; a swap's paint marks the first piece only.
+ if (input.mode === "insert" || (!tracked && input.mask)) mask = input.mask;
+ else if (i === 0 && target === "paint" && input.mask) mask = input.mask;
+ else {
+ let from = "track";
+ if (n > 1) {
+ const at = { startTime: r3(p.start - input.range.start), endTime: r3(p.end - input.range.start) };
+ steps.push({ key: `mcut${i}`, request: { ...helper, modelId: t.cut, op: "trim", params: at, step: pieceLabel(p, n, "cut the mask") }, after: ["track"], chain: [{ slot: "video" }] });
+ from = `mcut${i}`;
+ }
+ steps.push({ key: `mframe${i}`, request: { ...helper, modelId: "extract-frame", op: "frame", params: { extra: { frame_type: "first" } }, step: pieceLabel(p, n, "mask's first frame") }, after: [from], chain: [{ slot: "video" }] });
+ after.push(`mframe${i}`);
+ chain.push({ slot: "mask" });
+ }
+ }
+ // What per-second prices count: the piece's seconds (VACE bills video seconds at 16 fps: frames ÷ 16).
+ const secs = m.window && p.frames ? r6(p.frames / 16) : r3(p.end - p.start);
+ steps.push({
+ key: keys[i],
+ request: {
+ ...own(n === 1),
+ modelId: m.id,
+ op,
+ ...words,
+ inputs: { ...(one ? { video: input.source.url } : {}), ...images, ...(mask ? { mask } : {}) },
+ params: { duration: secs, sourceDuration: r3(p.end - p.start), ...(resolution ? { resolution } : {}), ...(m.window ? { aspectRatio: "auto" } : {}), ...(input.source.fps ? { fps: input.source.fps } : {}), ...lookParams, ...seed },
+ step: pieceLabel(p, n, input.mode === "motion" ? "transfer the motion" : input.mode === "insert" ? "add it" : input.mode === "restyle" ? "restyle" : "swap it"),
+ },
+ ...(after.length ? { after, chain } : {}),
+ });
+ });
+ const end = m.window ? pieces[n - 1].end : input.range.end;
+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound, end });
+ return { steps, final, pieces: n, sound, tracked };
+ }
+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: m.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound });
+ return { steps, final, pieces: n, sound, tracked: false };
+}
+
+/** Restyle on a Fuobe look: the Shorts chain in the clip's own shape, under Genjutsu's features. */
+function planFuobeRestyle(input: GenjutsuPlanInput): GenjutsuPlan {
+ const look = input.look && shortsLook(input.look);
+ if (!look) throw new Error("Pick a look");
+ const m = input.maker;
+ const plan = planShorts({
+ engine: m.engine,
+ title: input.title,
+ source: { url: input.source.url, duration: input.source.duration, hasAudio: input.source.hasAudio, width: input.source.width, height: input.source.height },
+ range: input.range,
+ look,
+ aspectRatio: (input.source.width ?? 16) >= (input.source.height ?? 9) ? "16:9" : "9:16",
+ keepShape: true,
+ language: "auto",
+ modelId: m.id,
+ maxRefs: m.readsLookImages ?? 0,
+ ...(qualityFor(m, input.quality) ? { resolution: qualityFor(m, input.quality) } : {}),
+ ...(input.seed !== undefined ? { seed: input.seed } : {}),
+ });
+ // Only the finished video is a result; the segments are steps (Shorts keeps each take as a result of its own).
+ const final = plan.final ?? plan.takes[0].look;
+ const steps = plan.steps.map((s) => ({
+ ...s,
+ request: s.key === final ? { ...s.request, feature: GENJUTSU.feature, title: input.title } : { ...s.request, feature: GENJUTSU.stepFeature },
+ }));
+ return { steps, final, pieces: plan.segments.length, sound: !!input.source.hasAudio, tracked: false };
+}
+
+// ---------------------------------------------------------------------------
+// Setup codes ("share by code", done locally: the settings as base64url JSON)
+
+export interface GenjutsuSetup {
+ mode: GenjutsuMode;
+ engine?: Engine;
+ model?: string;
+ tier?: GenjutsuTier;
+ quality?: GenjutsuQuality;
+ target?: GenjutsuTarget;
+ subject?: string;
+ prompt?: string;
+ look?: GenjutsuLook;
+ /** Reference images (files in this install's library). */
+ references?: string[];
+}
+
+const MODES = new Set<string>(GENJUTSU_MODES.map((m) => m.id));
+const FILE = /^\/api\/files\/[\w./-]{1,200}$/;
+const str = (v: unknown, max: number) => (typeof v === "string" && v.trim() ? v.slice(0, max) : undefined);
+const files = (v: unknown, max: number) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string" && FILE.test(x)).slice(0, max) : []);
+
+function toBase64Url(text: string): string {
+ const bytes = new TextEncoder().encode(text);
+ let bin = "";
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+function fromBase64Url(code: string): string {
+ const b64 = code.replace(/-/g, "+").replace(/_/g, "/");
+ const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
+ return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
+}
+
+/** A setup as a short code ("gj1." + base64url JSON with short keys; empty fields left out). */
+export function encodeSetup(s: GenjutsuSetup): string {
+ const look = s.look && (s.look.kind === "custom" ? { k: "c", i: s.look.images, w: s.look.words || undefined } : { k: s.look.kind === "preset" ? "p" : "h", id: s.look.id, n: s.look.kind === "higgsfield" ? s.look.name : undefined });
+ const o = { m: s.mode, e: s.engine, x: s.model, t: s.tier, q: s.quality, g: s.target, s: s.subject?.trim() || undefined, p: s.prompt?.trim() || undefined, l: look, r: s.references?.length ? s.references : undefined };
+ return `gj1.${toBase64Url(JSON.stringify(o))}`;
+}
+
+/** A setup read back from a code (or a link with ?setup=…), checked field by field; null when it isn't one. */
+export function decodeSetup(input: string): GenjutsuSetup | null {
+ let code = input.trim();
+ const fromLink = /[?&]setup=([^&#\s]+)/.exec(code);
+ if (fromLink) code = decodeURIComponent(fromLink[1]);
+ if (!code.startsWith("gj1.")) return null;
+ let o: Record<string, unknown>;
+ try {
+ o = JSON.parse(fromBase64Url(code.slice(4).replace(/\s+/g, ""))) as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+ if (!o || typeof o !== "object" || typeof o.m !== "string" || !MODES.has(o.m)) return null;
+ const mode = o.m as GenjutsuMode;
+ const out: GenjutsuSetup = { mode };
+ if (o.e === "cloud" || o.e === "open") out.engine = o.e;
+ const model = str(o.x, 80);
+ if (model && getMaker(model)) out.model = model;
+ if (o.t === "standard" || o.t === "high") out.tier = o.t;
+ if (typeof o.q === "string" && (GENJUTSU.qualities as string[]).includes(o.q)) out.quality = o.q as GenjutsuQuality;
+ if (typeof o.g === "string" && MODE_TARGETS[mode].includes(o.g as GenjutsuTarget)) out.target = o.g as GenjutsuTarget;
+ const subject = str(o.s, 300);
+ if (subject) out.subject = subject;
+ const prompt = str(o.p, GENJUTSU.maxPromptChars);
+ if (prompt) out.prompt = prompt;
+ const l = o.l as Record<string, unknown> | undefined;
+ if (mode === "restyle" && l && typeof l === "object") {
+ if (l.k === "p" && typeof l.id === "string" && getShortsPreset(l.id)) out.look = { kind: "preset", id: l.id };
+ else if (l.k === "h" && typeof l.id === "string" && /^[\w-]{1,64}$/.test(l.id)) out.look = { kind: "higgsfield", id: l.id, ...(str(l.n, 80) ? { name: str(l.n, 80) } : {}) };
+ else if (l.k === "c") {
+ const images = files(l.i, GENJUTSU.maxLookImages);
+ if (images.length) out.look = { kind: "custom", images, ...(str(l.w, 300) ? { words: str(l.w, 300) } : {}) };
+ }
+ }
+ const refs = files(o.r, GENJUTSU.maxReferences);
+ if (refs.length) out.references = refs;
+ return out;
+}
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 11568156..5fc773a7 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -574,6 +574,32 @@ const open: ModelDef[] = [
routes: [comfy("remove-object", "video-erase-void", "SAM 3.1 text track + VOID (CogVideoX-5B fine-tune), two passes; up to 197 frames per window")],
options: { seed: true, negativePrompt: true },
}),
+ // Genjutsu's Object swap and Insert on the open engine (docs/research/comfyui-oss-4.md §c). Swap: params.extra.maskPrompt
+ // names what goes (else the "replace … with" part of the prompt, see swapTarget), the first reference image is what comes
+ // in, the prompt describes the result. Insert: a painted region held for the whole window. One window per job, as the
+ // eraser: src/lib/catalog/genjutsu.ts tiles longer clips and joins them.
+ o({
+ id: "oss-vace-swap",
+ name: "Wan 2.1 VACE Swap",
+ vendor: "Alibaba Wan",
+ family: "wan",
+ kind: "video",
+ tagline: "Name what to swap: SAM 3.1 follows it, VACE paints your reference in its place, every other pixel stays the original · 81 frames a run (Genjutsu does whole clips) · 24 GB GPU · Apache-2.0",
+ badges: ["new"],
+ routes: [comfy("video-swap", "video-swap-wan-vace", "SAM 3.1 text track + Wan 2.1 VACE 14B with the first reference image; up to 81 frames per window")],
+ options: { seed: true, negativePrompt: true, maxImages: 1 },
+ }),
+ o({
+ id: "oss-vace-insert",
+ name: "Wan 2.1 VACE Insert",
+ vendor: "Alibaba Wan",
+ family: "wan",
+ kind: "video",
+ tagline: "Paint where it goes on the first frame: VACE adds your reference there, held for the whole shot (a still or slow camera) · 81 frames a run (Genjutsu does whole clips) · 24 GB GPU · Apache-2.0",
+ badges: ["new"],
+ routes: [comfy("video-insert", "video-insert-wan-vace", "painted region (white = where it goes) held for every frame + Wan 2.1 VACE 14B with the first reference image")],
+ options: { seed: true, negativePrompt: true, maxImages: 1, requires: { mask: true, msg: "Paint where it goes on the first frame" } },
+ }),
o({
id: "oss-qwen-relight",
name: "Qwen-Image-Edit Relight",
diff --git a/src/lib/catalog/remove-object.ts b/src/lib/catalog/remove-object.ts
index 0e3ba7fb..bd104acd 100644
--- a/src/lib/catalog/remove-object.ts
+++ b/src/lib/catalog/remove-object.ts
@@ -97,7 +97,7 @@ export interface FrameWindow {
overlap?: number;
}
-const VACE_WINDOW: FrameWindow = { cap: 81, step: 4, base: 1 };
+export const VACE_WINDOW: FrameWindow = { cap: 81, step: 4, base: 1 };
/**
* The painted eraser hands on the tracked mask of a window's last frame, and a mask must be of the window's first
* frame: so each window starts on the last frame of the one before (a one-frame overlap, cut off before the join).
@@ -701,8 +701,39 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {
});
}
- // Join the pieces in order (folding when the join takes fewer clips than there are).
- let level = joined;
+ // Erasers that work in whole frames leave out the last few (fewer than a step): the sound is cut to the picture's end,
+ // except on the open engine, whose mux trims the sound to the picture itself.
+ const end = e.window && e.engine === "cloud" ? pieces[n - 1].end : input.range.end;
+ const final = joinWithSound(steps, { engine: input.engine, title: input.title, base, helper, source: input.source, range: input.range, pieces: joined, sound, end });
+ return { steps, final, pieces, sound, tracked };
+}
+
+export interface JoinInput {
+ engine: Engine;
+ title: string;
+ /** The finished video's feature, and the steps' in between. */
+ base: { feature: string; batchTitle: string };
+ helper: { feature: string; batchTitle: string };
+ source: RemoveSource;
+ range: RemoveRange;
+ /** The keys of the pieces' videos, in order. */
+ pieces: string[];
+ /** Put the clip's own sound back under the joined picture. */
+ sound: boolean;
+ /** Where the sound ends in the source (the last piece's end, when pieces stop a few frames short). */
+ end?: number;
+ /** What the sound step says (default "Put the sound back"). */
+ soundLabel?: string;
+}
+
+/**
+ * Join pieces in order (folding when the join takes fewer clips than there are), then put the clip's own sound
+ * back: the upload's (the whole clip) or the range cut out of it. Pushes the steps; returns the finished video's key
+ * (a lone piece with no sound to add is the result itself; its step should carry the finished feature).
+ */
+export function joinWithSound(steps: PlanStep[], j: JoinInput): string {
+ const t = REMOVE_TOOLS[j.engine];
+ let level = j.pieces;
let depth = 0;
while (level.length > 1) {
const groups = joinGroups(level.length, t.joinMax);
@@ -713,12 +744,12 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {
steps.push({
key,
request: {
- ...(last && !sound ? { ...base, title: input.title } : helper),
+ ...(last && !j.sound ? { ...j.base, title: j.title } : j.helper),
modelId: t.join,
op: "concat",
- prompt: input.title,
+ prompt: j.title,
// The open join scales to one size: the clip's own shape at its own size.
- params: input.engine === "open" ? { aspectRatio: "auto", resolution: tierFor(input.source) } : {},
+ params: j.engine === "open" ? { aspectRatio: "auto", resolution: tierFor(j.source) } : {},
step: { label: last ? "Join the pieces" : "Joining", index: 1000 + depth, of: 1000 },
},
after,
@@ -729,28 +760,25 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {
depth++;
}
const picture = level[0];
- if (!sound) return { steps, final: picture, pieces, sound, tracked };
+ if (!j.sound) return picture;
- // The clip's own sound under the erased picture: the upload (whole clip), or the range cut out of it. Erasers that
- // work in whole frames leave out the last few (fewer than a step): the sound is cut to the picture's end, except on
- // the open engine, whose mux trims the sound to the picture itself.
const after = [picture];
const chain: ChainSlot[] = [{ slot: "video" }];
const inputs: GenerationRequest["inputs"] = {};
- const end = e.window && e.engine === "cloud" ? pieces[n - 1].end : input.range.end;
- if (whole && end >= (input.source.duration ?? 0) - 0.05) inputs.audio = input.source.url;
+ const end = j.end ?? j.range.end;
+ if (wholeClip(j.range, j.source.duration) && end >= (j.source.duration ?? 0) - 0.05) inputs.audio = j.source.url;
else {
- steps.push({ key: "sound", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: end }, step: { label: "Original sound", index: 1100, of: 1000 } } });
+ steps.push({ key: "sound", request: { ...j.helper, modelId: t.cut, op: "trim", inputs: { video: j.source.url }, params: { startTime: j.range.start, endTime: end }, step: { label: "Original sound", index: 1100, of: 1000 } } });
after.push("sound");
chain.push({ slot: "audio" });
}
steps.push({
key: "final",
- request: { ...base, title: input.title, modelId: t.mux, op: "mux", ...(Object.keys(inputs).length ? { inputs } : {}), step: { label: "Put the sound back", index: 1200, of: 1000 } },
+ request: { ...j.base, title: j.title, modelId: t.mux, op: "mux", ...(Object.keys(inputs).length ? { inputs } : {}), step: { label: j.soundLabel ?? "Put the sound back", index: 1200, of: 1000 } },
after,
chain,
});
- return { steps, final: "final", pieces, sound, tracked };
+ return "final";
}
/** The open join's size tier: the clip's own (480p, 720p or 1080p by its short side). */
diff --git a/src/lib/catalog/shorts.ts b/src/lib/catalog/shorts.ts
index c545ccf0..b383a23f 100644
--- a/src/lib/catalog/shorts.ts
+++ b/src/lib/catalog/shorts.ts
@@ -384,6 +384,11 @@ export interface ShortsPlanInput {
aspectRatio: ShortsRatio;
/** Cloud: the restyle model can be asked for the ratio itself; otherwise each cut is cropped to it first (it keeps its input's shape). */
reframes?: boolean;
+ /**
+ * Keep the clip's own shape instead of `aspectRatio` (Genjutsu Restyle: framing stays as filmed): no crop, no ratio
+ * asked of the cloud model, and the open cuts and join follow the clip ("auto").
+ */
+ keepShape?: boolean;
language: string;
/** The restyle model (cloud: SHORTS_MODELS.cloud; open: oss-wan22-vace-restyle). */
modelId: string;
@@ -408,6 +413,10 @@ export interface TakeKeys {
look: string;
}
+/** The ratio a step is asked for: the session's, or (keepShape) the clip's own on the open engine and none on the cloud. */
+const ratioParams = (input: Pick<ShortsPlanInput, "engine" | "aspectRatio" | "keepShape">): { aspectRatio?: string } =>
+ !input.keepShape ? { aspectRatio: input.aspectRatio } : input.engine === "open" ? { aspectRatio: "auto" } : {};
+
const segLabel = (s: ShortsSegment, n: number, what: string) => ({ label: `Segment ${s.index + 1} of ${n} · ${what}`, index: s.index, of: n });
/** Which references go where: the cloud model's own reference slot, or images 2–3 of the open first-frame edit. */
@@ -437,7 +446,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb
modelId: t.cut,
op: "trim",
inputs: { video: input.source.url },
- params: { startTime: seg.start, endTime: seg.end, fps: SHORTS.openFps, aspectRatio: input.aspectRatio, resolution: "480p" },
+ params: { startTime: seg.start, endTime: seg.end, fps: SHORTS.openFps, ...ratioParams(input), resolution: "480p" },
step: segLabel(seg, total, "cut"),
},
},
@@ -462,7 +471,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb
modelId: input.modelId,
op: "v2v",
prompt: segmentPrompt(input.look),
- params: { aspectRatio: input.aspectRatio, resolution: "480p", duration: (seg.frames ?? Math.round((seg.end - seg.start) * SHORTS.openFps)) / SHORTS.openFps, ...seed },
+ params: { ...ratioParams(input), resolution: "480p", duration: (seg.frames ?? Math.round((seg.end - seg.start) * SHORTS.openFps)) / SHORTS.openFps, ...seed },
step: segLabel(seg, total, "restyle"),
},
after: [keys.cut, keys.frame!],
@@ -471,7 +480,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb
],
};
}
- const fit = !input.reframes && needsFit(input.source, input.aspectRatio);
+ const fit = !input.keepShape && !input.reframes && needsFit(input.source, input.aspectRatio);
const keys: TakeKeys = { cut: k("cut"), ...(fit ? { fit: k("fit") } : {}), look: k("look") };
const seconds = seg.end - seg.start;
return {
@@ -508,7 +517,7 @@ export function planTake(input: ShortsPlanInput, seg: ShortsSegment, total: numb
inputs: refs.length ? { images: refs } : undefined,
// The segment's exact length: what per-second prices count. No restyle route is sent a length
// (each keeps its clip's), so the restyled segments add up to the selection and stay on the sound.
- params: { aspectRatio: input.aspectRatio, duration: r3(seconds), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },
+ params: { ...ratioParams(input), duration: r3(seconds), ...(input.resolution ? { resolution: input.resolution } : {}), ...seed },
step: segLabel(seg, total, "restyle"),
},
after: [keys.fit ?? keys.cut],
@@ -543,7 +552,7 @@ export function planStitch(input: ShortsPlanInput, clips: ClipRef[], suffix = ""
const base = { feature: SHORTS_FEATURE, batchTitle: input.title };
const helper = { feature: SHORTS_STEP_FEATURE, batchTitle: input.title };
const steps: PlanStep[] = [];
- const params = input.engine === "open" ? { aspectRatio: input.aspectRatio, resolution: "480p" } : { aspectRatio: input.aspectRatio };
+ const params = input.engine === "open" ? { ...ratioParams(input), resolution: "480p" } : ratioParams(input);
// Each join step takes its clips either chained (key) or as files (url).
let level: ClipRef[] = clips;
let depth = 0;
diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.ts
new file mode 100644
index 00000000..94f31238
--- /dev/null
+++ b/tests/genjutsu.test.ts
@@ -0,0 +1,294 @@
+import { describe, expect, it } from "vitest";
+import {
+ chooseMaker,
+ decodeSetup,
+ encodeSetup,
+ genjutsuProblem,
+ getMaker,
+ makerPrompt,
+ makersFor,
+ makerStepUsd,
+ planGenjutsu,
+ planMakerPieces,
+ qualityFor,
+ swapParts,
+ swapTarget,
+ type GenjutsuPlanInput,
+ type Maker,
+} from "@/lib/catalog/genjutsu";
+import { planGeneration } from "@/lib/catalog/plan";
+import { getModel, getPreset } from "@/lib/catalog";
+
+const clip = { url: "/api/files/clip.mp4", duration: 20, fps: 30, width: 1280, height: 720, hasAudio: true };
+const ref = "/api/files/hero.png";
+const maker = (id: string) => getMaker(id)!;
+const plan = (o: Partial<GenjutsuPlanInput> & { maker: Maker }) =>
+ planGenjutsu({ engine: o.maker.engine, mode: "motion", title: "Genjutsu", source: clip, range: { start: 0, end: 20 }, quality: "720p", references: [ref], ...o });
+const step = (p: ReturnType<typeof planGenjutsu>, key: string) => p.steps.find((s) => s.key === key)!;
+
+describe("Genjutsu: which model runs", () => {
+ it("Genjutsu Lite by default with a Higgsfield key, the full model as Quality: High", () => {
+ expect(chooseMaker({ engine: "cloud", mode: "motion", higgsfield: true })).toEqual({ maker: maker("genjutsu-lite-motion-transfer") });
+ expect(chooseMaker({ engine: "cloud", mode: "motion", higgsfield: true, tier: "high" })).toEqual({ maker: maker("genjutsu-motion-transfer") });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "type", higgsfield: true })).toEqual({ maker: maker("genjutsu-lite-object-swap") });
+ // A setup naming the full model is the same pick (the list shows Lite; the tier says High).
+ expect(chooseMaker({ engine: "cloud", mode: "swap", higgsfield: true, modelId: "genjutsu-object-swap", tier: "high" })).toEqual({ maker: maker("genjutsu-object-swap") });
+ expect(makersFor("cloud", "swap", "type").map((m) => m.id)).not.toContain("genjutsu-object-swap");
+ });
+
+ it("without a key: Kling Motion Control, Kling O3 edit, hosted VACE for marked areas, the Shorts models for looks", () => {
+ expect("maker" in chooseMaker({ engine: "cloud", mode: "motion", higgsfield: false }) && chooseMaker({ engine: "cloud", mode: "motion", higgsfield: false })).toMatchObject({ maker: { id: "kling-motion-control" } });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "type", higgsfield: false })).toMatchObject({ maker: { id: "kling-o3" } });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "paint", higgsfield: true })).toMatchObject({ maker: { id: "wan-22-vace-inpaint" } });
+ expect(chooseMaker({ engine: "cloud", mode: "insert", target: "type", higgsfield: false })).toMatchObject({ maker: { id: "kling-o3" } });
+ expect(chooseMaker({ engine: "cloud", mode: "restyle", look: { kind: "preset", id: "shorts-claymation" }, higgsfield: true })).toMatchObject({ maker: { id: "gemini-omni-flash" } });
+ expect(chooseMaker({ engine: "cloud", mode: "restyle", look: { kind: "custom", images: [ref] }, higgsfield: false })).toMatchObject({ maker: { id: "kling-o3-4k-edit" } });
+ expect(chooseMaker({ engine: "cloud", mode: "restyle", look: { kind: "higgsfield", id: "abc" }, higgsfield: true })).toMatchObject({ maker: { id: "genjutsu-restyle" } });
+ // P-Video Replace is there to pick for people.
+ expect(makersFor("cloud", "swap", "type").map((m) => m.id)).toEqual(["genjutsu-lite-object-swap", "kling-o3", "p-video-replace"]);
+ });
+
+ it("open: Wan Animate 2, VACE swap by name, VACE insert by paint, the Fun VACE restyle; other ways are refused in words", () => {
+ expect(chooseMaker({ engine: "open", mode: "motion", higgsfield: false })).toMatchObject({ maker: { id: "oss-wan22-animate" } });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "type", higgsfield: false })).toMatchObject({ maker: { id: "oss-vace-swap" } });
+ expect(chooseMaker({ engine: "open", mode: "insert", target: "paint", higgsfield: false })).toMatchObject({ maker: { id: "oss-vace-insert" } });
+ expect(chooseMaker({ engine: "open", mode: "restyle", look: { kind: "preset", id: "shorts-watercolor" }, higgsfield: false })).toMatchObject({ maker: { id: "oss-wan22-vace-restyle" } });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "paint", higgsfield: false })).toEqual({ problem: expect.stringMatching(/name what to swap/) });
+ expect(chooseMaker({ engine: "open", mode: "insert", target: "type", higgsfield: false })).toEqual({ problem: expect.stringMatching(/paint where it goes/) });
+ });
+
+ it("every maker is a catalog model that does its mode's operation", () => {
+ const ops = { motion: "motion-transfer", swap: "video-swap", insert: "video-insert", restyle: "v2v" } as const;
+ for (const m of [...makersFor("cloud", "motion"), ...makersFor("open", "motion")]) expect(m.modes).toContain("motion");
+ for (const id of ["genjutsu-lite-motion-transfer", "genjutsu-motion-transfer", "kling-motion-control", "genjutsu-lite-object-swap", "genjutsu-object-swap", "kling-o3", "p-video-replace", "wan-22-vace-inpaint", "genjutsu-restyle", "gemini-omni-flash", "kling-o3-4k-edit", "happy-horse-video-edit", "oss-wan22-animate", "oss-vace-swap", "oss-vace-insert", "oss-wan22-vace-restyle"]) {
+ const m = maker(id);
+ const model = getModel(id);
+ expect(model, id).toBeDefined();
+ expect(model!.engine).toBe(m.engine);
+ for (const mode of m.modes) expect(model!.routes.some((r) => r.op === ops[mode]), `${id} ${mode}`).toBe(true);
+ }
+ });
+});
+
+describe("Genjutsu: checks", () => {
+ const base = { mode: "motion" as const, maker: maker("genjutsu-lite-motion-transfer"), source: clip, range: { start: 0, end: 20 }, references: 1 };
+
+ it("the source window is 4–30 s", () => {
+ expect(genjutsuProblem({ ...base, range: { start: 0, end: 3 } })).toMatch(/between 4 and 30 seconds/);
+ expect(genjutsuProblem({ ...base, source: { ...clip, duration: 40 }, range: { start: 0, end: 31 } })).toMatch(/up to 30 seconds/);
+ expect(genjutsuProblem(base)).toBeNull();
+ });
+
+ it("references, words, clicks and paint are asked for per mode", () => {
+ expect(genjutsuProblem({ ...base, references: 0 })).toBe("Add a picture of your character");
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("kling-o3"), target: "type" })).toMatch(/Say what to swap/);
+ // Genjutsu and P-Video find it from the references.
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("genjutsu-lite-object-swap"), target: "type" })).toBeNull();
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("wan-22-vace-inpaint"), target: "click" })).toMatch(/Click what to swap/);
+ expect(genjutsuProblem({ ...base, mode: "insert", maker: maker("oss-vace-insert"), target: "paint" })).toMatch(/Paint where it goes/);
+ expect(genjutsuProblem({ ...base, mode: "insert", maker: maker("kling-o3"), target: "type" })).toMatch(/Say where it goes/);
+ expect(genjutsuProblem({ ...base, mode: "restyle", maker: maker("gemini-omni-flash"), references: 0 })).toBe("Pick a look");
+ expect(genjutsuProblem({ ...base, mode: "restyle", maker: maker("gemini-omni-flash"), references: 0, look: { kind: "custom", images: [ref] } })).toMatch(/restyles from words only/);
+ expect(genjutsuProblem({ ...base, mode: "restyle", maker: maker("kling-o3-4k-edit"), references: 0, look: { kind: "custom", images: [ref] } })).toBeNull();
+ });
+
+ it("each model's own limits", () => {
+ const small = { ...clip, width: 640, height: 360 };
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("genjutsu-object-swap"), source: small, target: "type" })).toMatch(/Genjutsu Lite takes it/);
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("kling-o3"), source: small, target: "type", subject: "the cup" })).toMatch(/at least 720 px/);
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("wan-22-vace-inpaint"), source: { ...clip, fps: 60 }, target: "paint", mask: true })).toMatch(/up to 30 fps/);
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("oss-vace-swap"), source: { ...clip, fps: undefined }, target: "type", subject: "the cup" })).toMatch(/frame rate/);
+ });
+});
+
+describe("Genjutsu: plans", () => {
+ it("cloud motion on Genjutsu Lite: 15 s calls, joined, the sound put back; whole seconds priced per quality", () => {
+ const p = plan({ maker: maker("genjutsu-lite-motion-transfer"), prompt: "a knight in silver armour", quality: "1080p" });
+ expect(p.pieces).toBe(2);
+ expect(step(p, "cut0").request.params).toMatchObject({ startTime: 0, endTime: 10 });
+ const make = step(p, "make1").request;
+ expect(make).toMatchObject({ modelId: "genjutsu-lite-motion-transfer", op: "motion-transfer", feature: "genjutsu-step", inputs: { images: [ref] }, prompt: "A knight in silver armour." });
+ expect(make.params).toMatchObject({ resolution: "1080p", duration: 10 });
+ expect(p.final).toBe("final");
+ expect(step(p, "final").request).toMatchObject({ op: "mux", feature: "genjutsu", inputs: { audio: clip.url } });
+ expect(step(p, "join").after).toEqual(["make0", "make1"]);
+ // Lite at 1080p: $0.20 a second; Genjutsu rounds up to whole seconds.
+ expect(makerStepUsd("genjutsu-lite-motion-transfer", { duration: 9.2, resolution: "1080p" })).toBeCloseTo(2, 6);
+ expect(makerStepUsd("genjutsu-motion-transfer", { duration: 4, resolution: "480p" })).toBeCloseTo(1.272, 6);
+ expect(makerStepUsd("kling-o3", { duration: 10 })).toBeCloseTo(1.68, 6);
+ expect(makerStepUsd("wan-22-vace-inpaint", { duration: 5 })).toBeNull();
+ });
+
+ it("one call that keeps the sound is the result itself", () => {
+ const p = plan({ maker: maker("genjutsu-motion-transfer") });
+ expect(p.steps.map((s) => s.key)).toEqual(["make0"]);
+ expect(p.final).toBe("make0");
+ expect(step(p, "make0").request).toMatchObject({ feature: "genjutsu", title: "Genjutsu", inputs: { video: clip.url, images: [ref] } });
+ });
+
+ it("Kling Motion Control takes one image and 10 s pieces; Kling O3 swap names the references as @Image", () => {
+ const k = plan({ maker: maker("kling-motion-control"), references: [ref, "/api/files/b.png"] });
+ expect(k.pieces).toBe(2);
+ expect(step(k, "make0").request.inputs?.images).toEqual([ref]);
+ const s = plan({ mode: "swap", maker: maker("kling-o3"), target: "type", subject: "the red car", prompt: "a white horse trotting", references: [ref, "/api/files/b.png"], range: { start: 2, end: 12 } });
+ expect(step(s, "make0").request.prompt).toBe("Replace the red car in @Video1 with @Image1, @Image2. A white horse trotting. Keep everything else the same: the motion, camera, framing and light.");
+ expect(step(s, "cut0").request.params).toMatchObject({ startTime: 2, endTime: 12 });
+ // Kling O3 keeps the sound of its one piece.
+ expect(s.final).toBe("make0");
+ const ins = plan({ mode: "insert", maker: maker("kling-o3"), target: "type", prompt: "on the table next to the cup", range: { start: 0, end: 8 } });
+ expect(step(ins, "make0").request.prompt).toMatch(/^Add @Image1 to @Video1: on the table next to the cup\./);
+ });
+
+ it("hosted VACE swap by paint over several pieces: the paint for the first, SAM 3.1's track for the rest", () => {
+ const p = plan({ mode: "swap", maker: maker("wan-22-vace-inpaint"), target: "paint", mask: "/api/files/mask.png", points: [{ x: 600, y: 300, label: "positive" }], quality: "1080p" });
+ expect(p.tracked).toBe(true);
+ // 20 s at 30 fps = 600 frames → 3 windows of 4n+1 ≤ 241.
+ expect(p.pieces).toBe(3);
+ expect(step(p, "track").request).toMatchObject({ modelId: "sam-3-1-video-mask", params: { points: [{ x: 600, y: 300, label: "positive" }] } });
+ expect(step(p, "make0").request.inputs?.mask).toBe("/api/files/mask.png");
+ expect(step(p, "make1").after).toEqual(["cut1", "mframe1"]);
+ expect(step(p, "make1").chain).toEqual([{ slot: "video" }, { slot: "mask" }]);
+ expect(step(p, "mframe1").request).toMatchObject({ modelId: "extract-frame", op: "frame", params: { extra: { frame_type: "first" } } });
+ expect(step(p, "mframe1").after).toEqual(["mcut1"]);
+ // 1080p isn't one of its sizes: the largest below.
+ expect(step(p, "make0").request.params).toMatchObject({ resolution: "720p", aspectRatio: "auto" });
+ // Billed as frames ÷ 16.
+ const frames = planMakerPieces(maker("wan-22-vace-inpaint"), clip, { start: 0, end: 20 })[0].frames!;
+ expect(step(p, "make0").request.params?.duration).toBeCloseTo(frames / 16, 5);
+ // VACE doesn't keep the sound: put back.
+ expect(p.final).toBe("final");
+ });
+
+ it("hosted VACE insert holds the painted spot in every piece (no tracking)", () => {
+ const p = plan({ mode: "insert", maker: maker("wan-22-vace-inpaint"), target: "paint", mask: "/api/files/spot.png" });
+ expect(p.tracked).toBe(false);
+ expect(p.steps.some((s) => s.key === "track")).toBe(false);
+ for (let i = 0; i < p.pieces; i++) expect(step(p, `make${i}`).request.inputs?.mask).toBe("/api/files/spot.png");
+ });
+
+ it("open VACE swap: windows straight from the upload, SAM 3.1's words, the first reference only", () => {
+ const p = plan({ mode: "swap", maker: maker("oss-vace-swap"), target: "type", subject: "Replace the coffee cup with a red apple", references: [ref, "/api/files/b.png"], quality: "720p" });
+ // 600 frames at 30 fps → 8 windows of ≤81.
+ expect(p.pieces).toBe(8);
+ const w = step(p, "make1").request;
+ expect(w).toMatchObject({ modelId: "oss-vace-swap", op: "video-swap", inputs: { video: clip.url, images: [ref] } });
+ expect(w.params?.extra).toEqual({ maskPrompt: "the coffee cup" });
+ expect(w.params).toMatchObject({ aspectRatio: "auto", resolution: "720p" });
+ expect(w.params?.startTime).toBeGreaterThan(2.5);
+ expect(w.prompt).toBe("A red apple in place of the coffee cup, matching the light, perspective and motion of the shot.");
+ // Joined (4 at a time on ComfyUI) under the clip's own sound.
+ expect(p.steps.filter((s) => s.request.op === "concat").length).toBe(3);
+ expect(step(p, "final").request).toMatchObject({ modelId: "oss-mux", feature: "genjutsu" });
+ });
+
+ it("open VACE insert: the painted spot for every window; Wan Animate 2: one job for the selection", () => {
+ const ins = plan({ mode: "insert", maker: maker("oss-vace-insert"), target: "paint", mask: "/api/files/spot.png", range: { start: 0, end: 5 } });
+ expect(ins.pieces).toBe(2);
+ expect(step(ins, "make0").request.inputs?.mask).toBe("/api/files/spot.png");
+ expect(step(ins, "make1").request.inputs?.mask).toBe("/api/files/spot.png");
+ const anim = plan({ maker: maker("oss-wan22-animate"), range: { start: 4, end: 14 } });
+ expect(anim.steps.map((s) => s.key)).toEqual(["cut0", "make0"]);
+ expect(step(anim, "cut0").request).toMatchObject({ modelId: "oss-trim", params: { startTime: 4, endTime: 14 } });
+ expect(step(anim, "make0").request).toMatchObject({ op: "motion-transfer", feature: "genjutsu", params: { aspectRatio: "auto", resolution: "720p" } });
+ expect(anim.final).toBe("make0");
+ });
+
+ it("Restyle on a Higgsfield look: Genjutsu Restyle with its preset_id and the character references", () => {
+ const p = plan({ mode: "restyle", maker: maker("genjutsu-restyle"), look: { kind: "higgsfield", id: "9b1c", name: "Anime" }, references: [ref] });
+ expect(step(p, "make0").request).toMatchObject({ op: "v2v", params: { extra: { preset_id: "9b1c" }, resolution: "720p" }, inputs: { images: [ref] } });
+ expect(step(p, "make0").request.prompt).toBeTruthy();
+ });
+
+ it("Restyle on a Fuobe look: the Shorts chain in the clip's own shape, under Genjutsu's features", () => {
+ const p = plan({ mode: "restyle", maker: maker("gemini-omni-flash"), look: { kind: "preset", id: "shorts-claymation" }, references: [] });
+ expect(p.pieces).toBe(2);
+ expect(p.steps.every((s) => s.request.feature === (s.key === p.final ? "genjutsu" : "genjutsu-step"))).toBe(true);
+ // No crop to 9:16 / 16:9, no ratio asked of the cloud model.
+ expect(p.steps.some((s) => s.request.op === "reframe")).toBe(false);
+ const look = p.steps.find((s) => s.request.modelId === "gemini-omni-flash")!.request;
+ expect(look.params?.aspectRatio).toBeUndefined();
+ expect(look.prompt).toMatch(/claymation/i);
+ const open = plan({ mode: "restyle", maker: maker("oss-wan22-vace-restyle"), look: { kind: "custom", images: [ref, "/api/files/b.png", "/api/files/c.png"] }, references: [] });
+ const cut = open.steps.find((s) => s.request.modelId === "oss-segment")!.request;
+ expect(cut.params?.aspectRatio).toBe("auto");
+ expect(open.steps.find((s) => s.request.modelId === "oss-qwen-edit")!.request.inputs?.images).toEqual([ref, "/api/files/b.png"]);
+ });
+
+ it("the steps plan as catalog generations (requests the catalog accepts)", () => {
+ const plans = [
+ plan({ maker: maker("genjutsu-lite-motion-transfer") }),
+ plan({ maker: maker("kling-motion-control") }),
+ plan({ mode: "swap", maker: maker("genjutsu-lite-object-swap"), target: "type" }),
+ plan({ mode: "swap", maker: maker("p-video-replace"), target: "type", quality: "480p" }),
+ plan({ mode: "swap", maker: maker("kling-o3"), target: "type", subject: "the cup", range: { start: 0, end: 10 } }),
+ plan({ mode: "insert", maker: maker("wan-22-vace-inpaint"), target: "paint", mask: "/api/files/m.png", range: { start: 0, end: 6 } }),
+ plan({ mode: "swap", maker: maker("oss-vace-swap"), target: "type", subject: "the cup", range: { start: 0, end: 6 } }),
+ plan({ mode: "insert", maker: maker("oss-vace-insert"), target: "paint", mask: "/api/files/m.png", range: { start: 0, end: 6 } }),
+ plan({ mode: "restyle", maker: maker("genjutsu-restyle"), look: { kind: "higgsfield", id: "x" }, references: [] }),
+ ];
+ for (const p of plans) {
+ for (const s of p.steps) {
+ // Chained inputs arrive at run time: stand-ins for what an earlier step makes.
+ const chained = Object.fromEntries((s.chain ?? []).map((c) => [c.slot === "videos" ? "videos" : c.slot, c.slot === "videos" ? ["/api/files/x.mp4", "/api/files/y.mp4"] : "/api/files/x.mp4"]));
+ const req = { ...s.request, inputs: { ...s.request.inputs, ...chained } };
+ expect(() => planGeneration(req, getModel, getPreset), `${s.request.modelId} ${s.key}`).not.toThrow();
+ }
+ }
+ });
+});
+
+describe("Genjutsu: words and qualities", () => {
+ it("swapTarget takes what goes out of a sentence", () => {
+ expect(swapTarget("Replace the red car with a horse")).toBe("the red car");
+ expect(swapTarget("swap the mug for a can of soda")).toBe("the mug");
+ expect(swapTarget("her jacket")).toBe("her jacket");
+ expect(swapParts("Replace the red car with a white horse.")).toEqual({ what: "the red car", into: "a white horse" });
+ // Kling O3 is told both.
+ expect(makerPrompt({ mode: "swap", maker: maker("kling-o3"), subject: "swap the mug for a can of soda", refs: 1 })).toBe(
+ "Replace the mug in @Video1 with @Image1 (a can of soda). Keep everything else the same: the motion, camera, framing and light.",
+ );
+ });
+
+ it("Genjutsu's optional words stay optional", () => {
+ expect(makerPrompt({ mode: "swap", maker: maker("genjutsu-lite-object-swap"), refs: 2 })).toBeUndefined();
+ expect(makerPrompt({ mode: "swap", maker: maker("genjutsu-lite-object-swap"), subject: "the jacket", refs: 2 })).toBe("Replace the jacket with the references.");
+ expect(makerPrompt({ mode: "motion", maker: maker("kling-motion-control"), refs: 1 })).toBeUndefined();
+ });
+
+ it("qualities go to the nearest a model renders", () => {
+ expect(qualityFor(maker("p-video-replace"), "480p")).toBe("720p");
+ expect(qualityFor(maker("oss-vace-swap"), "1080p")).toBe("720p");
+ expect(qualityFor(maker("kling-o3"), "1080p")).toBeUndefined();
+ });
+});
+
+describe("Genjutsu: setup codes", () => {
+ it("round-trips a setup through a short code", () => {
+ const setup = {
+ mode: "swap" as const,
+ engine: "cloud" as const,
+ model: "genjutsu-lite-object-swap",
+ tier: "high" as const,
+ quality: "1080p" as const,
+ target: "type" as const,
+ subject: "the red jacket — ünïcode",
+ prompt: "a yellow raincoat",
+ references: [ref, "/api/files/b.png"],
+ };
+ const code = encodeSetup(setup);
+ expect(code).toMatch(/^gj1\.[A-Za-z0-9_-]+$/);
+ expect(decodeSetup(code)).toEqual(setup);
+ // Pasted as a link, or with spaces around.
+ expect(decodeSetup(` http://localhost:3000/genjutsu?setup=${code} `)).toEqual(setup);
+ });
+
+ it("keeps looks and drops what isn't valid", () => {
+ expect(decodeSetup(encodeSetup({ mode: "restyle", look: { kind: "custom", images: [ref, "https://evil.example/x.png"], words: "neon" } }))).toEqual({ mode: "restyle", look: { kind: "custom", images: [ref], words: "neon" } });
+ expect(decodeSetup(encodeSetup({ mode: "restyle", look: { kind: "preset", id: "shorts-claymation" } }))?.look).toEqual({ kind: "preset", id: "shorts-claymation" });
+ expect(decodeSetup(encodeSetup({ mode: "restyle", look: { kind: "preset", id: "nope" } }))?.look).toBeUndefined();
+ expect(decodeSetup(encodeSetup({ mode: "motion", target: "paint", model: "not-a-model" }))).toEqual({ mode: "motion" });
+ expect(decodeSetup("gj1.!!!")).toBeNull();
+ expect(decodeSetup("hello")).toBeNull();
+ expect(decodeSetup(`gj1.${btoa(JSON.stringify({ m: "fly" }))}`)).toBeNull();
+ });
+});