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.

Originals O5: Genjutsu on the Originals, with MiniMax H3 Character swap on both engines

Claude9c52f8ee5d02
diff --git a/scripts/comfy/build-library.mjs b/scripts/comfy/build-library.mjs
index 6576b571..d74292e9 100644
--- a/scripts/comfy/build-library.mjs
+++ b/scripts/comfy/build-library.mjs
@@ -15,7 +15,7 @@ import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
-import { SPEC, KNOWN_MODELS, CUSTOM_NODE_REPOS } from './library.spec.mjs';
+import { SPEC, KNOWN_MODELS, CUSTOM_NODE_REPOS, PACK_CLASSES } from './library.spec.mjs';
import * as G from './lib/graph.mjs';
import { resolveSource } from './export-templates.mjs';
@@ -122,6 +122,8 @@ export const BINDING_KEYS = new Set([
'every', 'slowdown', 'shortSide', 'colorSpace',
// Fuobe Soul (Originals O2): image to image at Soul's tier
'megapixels',
+ // Genjutsu's Character swap (Originals O5): MiniMax H3 with the h3_character_swap / H3 Relay packs
+ 'quality', 'selection', 'subjectIndex', 'positiveCoords', 'negativeCoords', 'audioGuide', 'useMask', 'windowFrames', 'historyFrames',
]);
const readJson = (p, fallback) => (fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : fallback);
@@ -253,7 +255,9 @@ async function main() {
for (const id of G.outputNodeIds(graph, objectInfo)) if (!outIds.includes(id)) delete graph[id];
G.prune(graph, objectInfo, outIds);
graph = G.sortGraph(graph);
- errs.push(...G.lint(graph, objectInfo));
+ // Classes of a pack this server doesn't have (spec.packs, PACK_CLASSES) are expected: the entry names the pack instead.
+ const packClass = (cls) => (spec.packs || []).some((p) => PACK_CLASSES[p]?.test(cls));
+ errs.push(...G.lint(graph, objectInfo).filter((e) => !/ not installed$/.test(e) || !packClass(e.match(/class (.+) not installed$/)?.[1] ?? '')));
// ---- bindings
const bindings = { ...spec.bindings };
@@ -312,7 +316,8 @@ async function main() {
if (models.has(val)) continue;
const m = metaByName[val];
const known = KNOWN_MODELS[val];
- const url = m?.url || known?.url;
+ // A workflow may pin its own revision of a shared file (spec.modelUrls: the same bytes at a researched commit).
+ const url = spec.modelUrls?.[val] || m?.url || known?.url;
if (m?.directory && m.directory !== folder) errs.push(`model ${val}: template says ${m.directory}, loader reads ${folder}`);
if (!url) errs.push(`model ${val} (${folder}): no download URL known`);
const size = url ? await hfSize(url, sizeCache) : null;
@@ -345,6 +350,8 @@ async function main() {
const m = mod.match(/^custom_nodes\.([^.]+)/);
if (m) custom.add(m[1]);
}
+ // Packs this server doesn't have installed (their classes have no python_module here): declared by the entry.
+ for (const p of spec.packs || []) custom.add(p);
const customNodes = [...custom].sort().map((name) => ({ name, repo: CUSTOM_NODE_REPOS[name] || null }));
for (const c of customNodes) if (!c.repo) errs.push(`custom node pack ${c.name} has no repo URL`);
diff --git a/scripts/comfy/hand-built/video-character-swap-h3-relay.json b/scripts/comfy/hand-built/video-character-swap-h3-relay.json
new file mode 100644
index 00000000..d7f6f289
--- /dev/null
+++ b/scripts/comfy/hand-built/video-character-swap-h3-relay.json
@@ -0,0 +1,788 @@
+{
+ "model": {
+ "class_type": "UNETLoader",
+ "inputs": {
+ "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "_meta": {
+ "title": "UNETLoader"
+ }
+ },
+ "shift": {
+ "class_type": "MiniMaxH3SigmaShift",
+ "inputs": {
+ "model": [
+ "model",
+ 0
+ ],
+ "shift_video": 12.0,
+ "shift_audio": 3.0
+ },
+ "_meta": {
+ "title": "MiniMaxH3SigmaShift"
+ }
+ },
+ "attention": {
+ "class_type": "ModelAttentionBackend",
+ "inputs": {
+ "model": [
+ "shift",
+ 0
+ ],
+ "attention": "comfy kitchen attention"
+ },
+ "_meta": {
+ "title": "ModelAttentionBackend"
+ }
+ },
+ "text": {
+ "class_type": "CLIPLoader",
+ "inputs": {
+ "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "type": "minimax",
+ "device": "default"
+ },
+ "_meta": {
+ "title": "CLIPLoader"
+ }
+ },
+ "text_device": {
+ "class_type": "SelectCLIPDevice",
+ "inputs": {
+ "clip": [
+ "text",
+ 0
+ ],
+ "device": "gpu:0"
+ },
+ "_meta": {
+ "title": "SelectCLIPDevice"
+ }
+ },
+ "text_memory": {
+ "class_type": "H3RelayTextMemory",
+ "inputs": {
+ "clip": [
+ "text_device",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayTextMemory"
+ }
+ },
+ "video_vae": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_video_vae_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "VAELoader"
+ }
+ },
+ "audio_vae": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_audio_vae_fp32.safetensors"
+ },
+ "_meta": {
+ "title": "VAELoader"
+ }
+ },
+ "turbo": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "model": [
+ "attention",
+ 0
+ ],
+ "lora_name": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "strength_model": 1.0
+ },
+ "_meta": {
+ "title": "LoraLoaderModelOnly"
+ }
+ },
+ "adapter": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "model": [
+ "turbo",
+ 0
+ ],
+ "lora_name": "h3_character_swap_v1.5.safetensors",
+ "strength_model": 1.0
+ },
+ "_meta": {
+ "title": "LoraLoaderModelOnly"
+ }
+ },
+ "source": {
+ "class_type": "LoadVideo",
+ "inputs": {
+ "file": "source.mp4"
+ },
+ "_meta": {
+ "title": "LoadVideo"
+ }
+ },
+ "trim": {
+ "class_type": "Video Slice",
+ "inputs": {
+ "video": [
+ "source",
+ 0
+ ],
+ "start_time": 0,
+ "duration": 5.0,
+ "strict_duration": false
+ },
+ "_meta": {
+ "title": "The chosen part"
+ }
+ },
+ "prepare": {
+ "class_type": "H3RelayPrepareSource",
+ "inputs": {
+ "video": [
+ "trim",
+ 0
+ ],
+ "resolution": "768",
+ "duration_seconds": 5.0,
+ "missing_audio": "silence"
+ },
+ "_meta": {
+ "title": "H3RelayPrepareSource"
+ }
+ },
+ "dimensions": {
+ "class_type": "GetImageSize",
+ "inputs": {
+ "image": [
+ "prepare",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "GetImageSize"
+ }
+ },
+ "reference": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "reference.png"
+ },
+ "_meta": {
+ "title": "LoadImage"
+ }
+ },
+ "sam": {
+ "class_type": "CheckpointLoaderSimple",
+ "inputs": {
+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "CheckpointLoaderSimple"
+ }
+ },
+ "subject": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {
+ "clip": [
+ "sam",
+ 1
+ ],
+ "text": "person"
+ },
+ "_meta": {
+ "title": "CLIPTextEncode"
+ }
+ },
+ "first_frame": {
+ "class_type": "ImageFromBatch",
+ "inputs": {
+ "image": [
+ "prepare",
+ 0
+ ],
+ "batch_index": 0,
+ "length": 1
+ },
+ "_meta": {
+ "title": "ImageFromBatch"
+ }
+ },
+ "detect": {
+ "class_type": "SAM3_Detect",
+ "inputs": {
+ "model": [
+ "sam",
+ 0
+ ],
+ "image": [
+ "first_frame",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "threshold": 0.35,
+ "refine_iterations": 2,
+ "individual_masks": true,
+ "positive_coords": "",
+ "negative_coords": ""
+ },
+ "_meta": {
+ "title": "SAM3_Detect"
+ }
+ },
+ "select": {
+ "class_type": "H3RelaySelectMask",
+ "inputs": {
+ "masks": [
+ "detect",
+ 0
+ ],
+ "selection": "largest",
+ "index": 0
+ },
+ "_meta": {
+ "title": "H3RelaySelectMask"
+ }
+ },
+ "track": {
+ "class_type": "SAM3_VideoTrack",
+ "inputs": {
+ "model": [
+ "sam",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "initial_mask": [
+ "select",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "detection_threshold": 0.5,
+ "max_objects": 1,
+ "detect_interval": 1
+ },
+ "_meta": {
+ "title": "SAM3_VideoTrack"
+ }
+ },
+ "mask": {
+ "class_type": "SAM3_TrackToMask",
+ "inputs": {
+ "track_data": [
+ "track",
+ 0
+ ],
+ "object_indices": ""
+ },
+ "_meta": {
+ "title": "SAM3_TrackToMask"
+ }
+ },
+ "recover": {
+ "class_type": "H3RelayRecoverMasks",
+ "inputs": {
+ "masks": [
+ "mask",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "model": [
+ "sam",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "selection": [
+ "select",
+ 1
+ ],
+ "recover_empty_frames": true
+ },
+ "_meta": {
+ "title": "H3RelayRecoverMasks"
+ }
+ },
+ "expand_mask": {
+ "class_type": "H3RelayExpandMask",
+ "inputs": {
+ "masks": [
+ "recover",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "expansion_px": 64
+ },
+ "_meta": {
+ "title": "H3RelayExpandMask"
+ }
+ },
+ "plan": {
+ "class_type": "H3RelayWindowPlan",
+ "inputs": {
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "window_frames": "124",
+ "history_frames": "18",
+ "seed": 904239,
+ "schedule": "adaptive",
+ "seed_mode": "fixed",
+ "seed_overrides": "{}"
+ },
+ "_meta": {
+ "title": "Plan source-aligned windows"
+ }
+ },
+ "start": {
+ "class_type": "StartLoop",
+ "inputs": {
+ "mode": "simple",
+ "mode.num_iterations": [
+ "plan",
+ 2
+ ],
+ "cache_iterations": false
+ },
+ "_meta": {
+ "title": "Native loop · one H3 window"
+ }
+ },
+ "window": {
+ "class_type": "H3RelayWindowInputs",
+ "inputs": {
+ "source": [
+ "prepare",
+ 0
+ ],
+ "window": [
+ "plan",
+ 3
+ ],
+ "iteration_index": [
+ "start",
+ 0
+ ],
+ "previous": [
+ "start",
+ 4
+ ],
+ "reference_history": true,
+ "fps": 24.0,
+ "resize_anchor": true,
+ "history_audio_mode": "source",
+ "source_audio": [
+ "prepare",
+ 1
+ ],
+ "mask": [
+ "expand_mask",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayWindowInputs"
+ }
+ },
+ "reference_conditioning": {
+ "class_type": "MiniMaxH3ReferenceToVideo",
+ "inputs": {
+ "clip": [
+ "text_memory",
+ 0
+ ],
+ "prompt": "Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing.",
+ "width": [
+ "dimensions",
+ 0
+ ],
+ "height": [
+ "dimensions",
+ 1
+ ],
+ "length": [
+ "window",
+ 8
+ ],
+ "ref_image_size": "match",
+ "ref_videos.ref_video_0": [
+ "window",
+ 5
+ ],
+ "ref_images.ref_image_0": [
+ "reference",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ],
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "ref_audios.ref_audio_0": [
+ "window",
+ 6
+ ]
+ },
+ "_meta": {
+ "title": "Native H3 reference conditioning"
+ }
+ },
+ "history": {
+ "class_type": "H3RelayApplyHistory",
+ "inputs": {
+ "positive": [
+ "reference_conditioning",
+ 0
+ ],
+ "latent": [
+ "reference_conditioning",
+ 1
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ],
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "frames": [
+ "window",
+ 3
+ ],
+ "history_frames": [
+ "window",
+ 7
+ ],
+ "first_frame_guide": false,
+ "target_audio_guide": true,
+ "audio": [
+ "window",
+ 4
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayApplyHistory"
+ }
+ },
+ "encode_source": {
+ "class_type": "VAEEncode",
+ "inputs": {
+ "pixels": [
+ "window",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "VAEEncode"
+ }
+ },
+ "edit_mask": {
+ "class_type": "H3RelayApplyEditMask",
+ "inputs": {
+ "latent": [
+ "history",
+ 1
+ ],
+ "source_latent": [
+ "encode_source",
+ 0
+ ],
+ "mask": [
+ "window",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayApplyEditMask"
+ }
+ },
+ "guide": {
+ "class_type": "MiniMaxH3AddGuide",
+ "inputs": {
+ "positive": [
+ "history",
+ 0
+ ],
+ "latent": [
+ "edit_mask",
+ 0
+ ],
+ "frame_idx": 0,
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "audio": [
+ "window",
+ 2
+ ]
+ },
+ "_meta": {
+ "title": "Native target guide"
+ }
+ },
+ "sampling_memory": {
+ "class_type": "H3RelaySamplingMemory",
+ "inputs": {
+ "model": [
+ "adapter",
+ 0
+ ],
+ "latent": [
+ "edit_mask",
+ 0
+ ],
+ "conditioning": [
+ "guide",
+ 0
+ ],
+ "activation_memory_gib": 17.0
+ },
+ "_meta": {
+ "title": "H3RelaySamplingMemory"
+ }
+ },
+ "noise": {
+ "class_type": "RandomNoise",
+ "inputs": {
+ "noise_seed": [
+ "window",
+ 10
+ ]
+ },
+ "_meta": {
+ "title": "RandomNoise"
+ }
+ },
+ "guider": {
+ "class_type": "CFGGuider",
+ "inputs": {
+ "model": [
+ "sampling_memory",
+ 0
+ ],
+ "positive": [
+ "guide",
+ 0
+ ],
+ "negative": [
+ "guide",
+ 0
+ ],
+ "cfg": 1.0
+ },
+ "_meta": {
+ "title": "CFGGuider"
+ }
+ },
+ "sampler": {
+ "class_type": "KSamplerSelect",
+ "inputs": {
+ "sampler_name": "er_sde"
+ },
+ "_meta": {
+ "title": "KSamplerSelect"
+ }
+ },
+ "schedule": {
+ "class_type": "BasicScheduler",
+ "inputs": {
+ "model": [
+ "adapter",
+ 0
+ ],
+ "scheduler": "normal",
+ "steps": 8,
+ "denoise": 1.0
+ },
+ "_meta": {
+ "title": "BasicScheduler"
+ }
+ },
+ "sample": {
+ "class_type": "SamplerCustomAdvanced",
+ "inputs": {
+ "noise": [
+ "noise",
+ 0
+ ],
+ "guider": [
+ "guider",
+ 0
+ ],
+ "sampler": [
+ "sampler",
+ 0
+ ],
+ "sigmas": [
+ "schedule",
+ 0
+ ],
+ "latent_image": [
+ "edit_mask",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "SamplerCustomAdvanced"
+ }
+ },
+ "separate": {
+ "class_type": "LTXVSeparateAVLatent",
+ "inputs": {
+ "av_latent": [
+ "sample",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "LTXVSeparateAVLatent"
+ }
+ },
+ "decode": {
+ "class_type": "VAEDecode",
+ "inputs": {
+ "samples": [
+ "separate",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "VAEDecode"
+ }
+ },
+ "append": {
+ "class_type": "H3RelayAppendWindow",
+ "inputs": {
+ "frames": [
+ "decode",
+ 0
+ ],
+ "window": [
+ "window",
+ 12
+ ],
+ "previous": [
+ "start",
+ 4
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayAppendWindow"
+ }
+ },
+ "end": {
+ "class_type": "EndLoop",
+ "inputs": {
+ "output_value": [
+ "append",
+ 0
+ ],
+ "next_iteration_value": [
+ "append",
+ 0
+ ],
+ "accumulate": false
+ },
+ "_meta": {
+ "title": "EndLoop"
+ }
+ },
+ "finish": {
+ "class_type": "H3RelayFinishWindows",
+ "inputs": {
+ "state": [
+ "end",
+ 0
+ ],
+ "audio_mode": "source",
+ "source_audio": [
+ "prepare",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayFinishWindows"
+ }
+ },
+ "video": {
+ "class_type": "CreateVideo",
+ "inputs": {
+ "images": [
+ "finish",
+ 0
+ ],
+ "fps": [
+ "finish",
+ 2
+ ],
+ "audio": [
+ "finish",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "CreateVideo"
+ }
+ },
+ "save": {
+ "class_type": "SaveVideo",
+ "inputs": {
+ "video": [
+ "video",
+ 0
+ ],
+ "filename_prefix": "fuobe/character-swap-relay",
+ "format": "mp4",
+ "format.codec": "h264",
+ "format.codec.encoding": "re-encode",
+ "format.codec.encoding.crf": 16
+ },
+ "_meta": {
+ "title": "SaveVideo"
+ }
+ }
+}
diff --git a/scripts/comfy/hand-built/video-character-swap-h3.json b/scripts/comfy/hand-built/video-character-swap-h3.json
new file mode 100644
index 00000000..32e231fd
--- /dev/null
+++ b/scripts/comfy/hand-built/video-character-swap-h3.json
@@ -0,0 +1,529 @@
+{
+ "1": {
+ "class_type": "UNETLoader",
+ "inputs": {
+ "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "_meta": {
+ "title": "H3 Ref2VA · INT8"
+ }
+ },
+ "2": {
+ "class_type": "MiniMaxH3SigmaShift",
+ "inputs": {
+ "shift_video": 12,
+ "shift_audio": 3,
+ "model": [
+ "1",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3 sampling shift"
+ }
+ },
+ "3": {
+ "class_type": "ModelAttentionBackend",
+ "inputs": {
+ "attention": "comfy kitchen attention",
+ "model": [
+ "2",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Optimized attention"
+ }
+ },
+ "4": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "lora_name": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "strength_model": 1,
+ "model": [
+ "3",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "FL2V Turbo · 8-step LoRA"
+ }
+ },
+ "850": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "lora_name": "h3_character_swap_v1.5.safetensors",
+ "strength_model": 1,
+ "model": [
+ "4",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Character Swap LoRA (V1.5)"
+ }
+ },
+ "6": {
+ "class_type": "CLIPLoader",
+ "inputs": {
+ "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "type": "minimax",
+ "device": "default"
+ },
+ "_meta": {
+ "title": "Qwen · H3 text encoder"
+ }
+ },
+ "58": {
+ "class_type": "SelectCLIPDevice",
+ "inputs": {
+ "device": "gpu:0",
+ "clip": [
+ "6",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Text encoder device"
+ }
+ },
+ "7": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_video_vae_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "H3 video VAE"
+ }
+ },
+ "8": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_audio_vae_fp32.safetensors"
+ },
+ "_meta": {
+ "title": "H3 audio VAE"
+ }
+ },
+ "9": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "reference.png"
+ },
+ "_meta": {
+ "title": "2 · Character reference"
+ }
+ },
+ "30": {
+ "class_type": "LoadVideo",
+ "inputs": {
+ "file": "source.mp4"
+ },
+ "_meta": {
+ "title": "1 · Source performance video"
+ }
+ },
+ "trim": {
+ "class_type": "Video Slice",
+ "inputs": {
+ "start_time": 0,
+ "duration": 5.0,
+ "strict_duration": false,
+ "video": [
+ "30",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "The chosen part"
+ }
+ },
+ "31": {
+ "class_type": "H3CharacterSwapPrepareVideo",
+ "inputs": {
+ "resolution": "768",
+ "duration_seconds": 5.0,
+ "video": [
+ "trim",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Prepare · 24 fps / pixel budget"
+ }
+ },
+ "100": {
+ "class_type": "CheckpointLoaderSimple",
+ "inputs": {
+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "SAM 3.1 · model"
+ }
+ },
+ "101": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {
+ "text": "person",
+ "clip": [
+ "100",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "4 · Find the subject"
+ }
+ },
+ "102": {
+ "class_type": "ImageFromBatch",
+ "inputs": {
+ "batch_index": 0,
+ "length": 1,
+ "image": [
+ "31",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Detection frame · first frame"
+ }
+ },
+ "103": {
+ "class_type": "SAM3_Detect",
+ "inputs": {
+ "threshold": 0.35,
+ "refine_iterations": 2,
+ "individual_masks": true,
+ "model": [
+ "100",
+ 0
+ ],
+ "image": [
+ "102",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ],
+ "positive_coords": "",
+ "negative_coords": ""
+ },
+ "_meta": {
+ "title": "Detect individual people"
+ }
+ },
+ "104": {
+ "class_type": "H3CharacterSwapSelectSubject",
+ "inputs": {
+ "selection": "largest",
+ "index": 0,
+ "masks": [
+ "103",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Select the person to replace"
+ }
+ },
+ "105": {
+ "class_type": "SAM3_VideoTrack",
+ "inputs": {
+ "detection_threshold": 0.5,
+ "max_objects": 1,
+ "detect_interval": 1,
+ "images": [
+ "31",
+ 0
+ ],
+ "model": [
+ "100",
+ 0
+ ],
+ "initial_mask": [
+ "104",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Track selected person"
+ }
+ },
+ "106": {
+ "class_type": "SAM3_TrackToMask",
+ "inputs": {
+ "object_indices": "",
+ "track_data": [
+ "105",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Selected track → mask"
+ }
+ },
+ "107": {
+ "class_type": "H3CharacterSwapRecoverMasks",
+ "inputs": {
+ "recover_empty_frames": true,
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "masks": [
+ "106",
+ 0
+ ],
+ "images": [
+ "31",
+ 0
+ ],
+ "model": [
+ "100",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ],
+ "selection": [
+ "104",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "Recover empty frames · same as app"
+ }
+ },
+ "110": {
+ "class_type": "H3CharacterSwapExpandMask",
+ "inputs": {
+ "expansion_px": 64,
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "masks": [
+ "107",
+ 0
+ ],
+ "images": [
+ "31",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Expand mask · matches the app"
+ }
+ },
+ "800": {
+ "class_type": "H3CharacterSwapModels",
+ "inputs": {
+ "model": [
+ "850",
+ 0
+ ],
+ "clip": [
+ "58",
+ 0
+ ],
+ "video_vae": [
+ "7",
+ 0
+ ],
+ "audio_vae": [
+ "8",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Shared models"
+ }
+ },
+ "801": {
+ "class_type": "H3CharacterSwapSettings",
+ "inputs": {
+ "prompt": "Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing. Start from the first frame in <Picture 2>.",
+ "seed": 904239,
+ "audio_guide": true,
+ "steps": 8,
+ "cfg": 1,
+ "sampler_name": "er_sde",
+ "scheduler": "normal",
+ "activation_memory_gib": 17
+ },
+ "_meta": {
+ "title": "5 · Prompt & audio guide"
+ }
+ },
+ "anchor_image": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "anchor.png"
+ },
+ "_meta": {
+ "title": "First frame made by the app"
+ }
+ },
+ "anchor_fit": {
+ "class_type": "ImageScale",
+ "inputs": {
+ "upscale_method": "lanczos",
+ "crop": "center",
+ "image": [
+ "anchor_image",
+ 0
+ ],
+ "width": [
+ "31",
+ 2
+ ],
+ "height": [
+ "31",
+ 3
+ ]
+ },
+ "_meta": {
+ "title": "Anchor at the video's exact size"
+ }
+ },
+ "803": {
+ "class_type": "H3CharacterSwapShot",
+ "inputs": {
+ "use_anchor": true,
+ "use_mask": true,
+ "shot_id": "character-swap",
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "fps": [
+ "31",
+ 6
+ ],
+ "source_video": [
+ "trim",
+ 0
+ ],
+ "source": [
+ "31",
+ 0
+ ],
+ "source_audio": [
+ "31",
+ 1
+ ],
+ "reference": [
+ "9",
+ 0
+ ],
+ "anchor": [
+ "anchor_fit",
+ 0
+ ],
+ "body_mask": [
+ "110",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Prepare swap inputs"
+ }
+ },
+ "805": {
+ "class_type": "H3CharacterSwapWindowPlan",
+ "inputs": {
+ "window_frames": "124",
+ "history_frames": "18",
+ "shot": [
+ "803",
+ 0
+ ],
+ "settings": [
+ "801",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Continuation · window / history"
+ }
+ },
+ "806": {
+ "class_type": "H3CharacterSwapController",
+ "inputs": {
+ "models": [
+ "800",
+ 0
+ ],
+ "shot": [
+ "803",
+ 0
+ ],
+ "plan": [
+ "805",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "6 · Generate character swap"
+ }
+ },
+ "807": {
+ "class_type": "H3CharacterSwapAssemble",
+ "inputs": {
+ "filename_prefix": "fuobe-character-swap",
+ "state": [
+ "806",
+ 0
+ ],
+ "shot": [
+ "806",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "7 · Result with source audio"
+ }
+ },
+ "808": {
+ "class_type": "CreateVideo",
+ "inputs": {
+ "fps": 24,
+ "bit_depth": 8,
+ "color_space": "sRGB",
+ "codec": "none",
+ "images": [
+ "807",
+ 0
+ ],
+ "audio": [
+ "807",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "Video for the app"
+ }
+ },
+ "809": {
+ "class_type": "SaveVideo",
+ "inputs": {
+ "filename_prefix": "fuobe/character-swap",
+ "format": "mp4",
+ "format.codec": "h264",
+ "video": [
+ "808",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Save result"
+ }
+ }
+}
diff --git a/scripts/comfy/install-comfyui.sh b/scripts/comfy/install-comfyui.sh
index 874560cf..a586862f 100755
--- a/scripts/comfy/install-comfyui.sh
+++ b/scripts/comfy/install-comfyui.sh
@@ -59,6 +59,33 @@ for name in "${!NODES[@]}"; do
fi
done
+# Genjutsu's Character swap (docs/research/openjutsu-6.md §4): Akatz Labs' h3_character_swap pack (GPL-3.0) lives in a
+# subfolder of their H3 Character Swap tool, pinned at the commit Openjutsu uses (the last one with the pack). It is
+# used unpatched (the workflows send the resolution as "480" / "768") and needs FFmpeg and FFprobe on PATH; its own
+# requirements (numpy, scipy, Pillow, opencv-python-headless) are in the union below. H3_PACK=0 leaves it out.
+H3_TOOL_REF="${H3_TOOL_REF:-0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b}"
+if [ "${H3_PACK:-1}" = "1" ] && [ ! -d "$COMFYUI_DIR/custom_nodes/h3_character_swap" ]; then
+ h3tmp="$(mktemp -d)"
+ git clone -q --filter=blob:none --no-checkout https://github.com/akatz-labs/h3-character-swap-tool "$h3tmp/tool"
+ git -C "$h3tmp/tool" sparse-checkout set --no-cone /worker_nodes/h3_character_swap/
+ git -C "$h3tmp/tool" checkout -q "$H3_TOOL_REF" && cp -r "$h3tmp/tool/worker_nodes/h3_character_swap" "$COMFYUI_DIR/custom_nodes/h3_character_swap" \
+ || echo "warn: could not fetch h3_character_swap at $H3_TOOL_REF"
+ rm -rf "$h3tmp"
+fi
+if [ "${H3_PACK:-1}" = "1" ] && { ! command -v ffmpeg >/dev/null || ! command -v ffprobe >/dev/null; }; then
+ echo "warn: the h3_character_swap pack needs ffmpeg and ffprobe on PATH (Genjutsu's Character swap)"
+fi
+# H3 Relay 2.0 (Akatz Labs' newer nodes for the same swap, GPL-3.0; the video-character-swap-h3-relay workflow) registers
+# HTTP routes and an in-memory H3 layout compatibility layer when it loads, so it is opt-in: H3_RELAY=1 (or install it on
+# the isolated worker, scripts/comfy/install-isolated-worker.sh, the same way).
+H3_RELAY_REF="${H3_RELAY_REF:-e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220}" # 2.0.1, 2026-10-21
+if [ "${H3_RELAY:-0}" = "1" ]; then
+ dest="$COMFYUI_DIR/custom_nodes/h3-relay"
+ [ -d "$dest/.git" ] || git clone -q https://github.com/akatz-ai/h3-relay "$dest"
+ git -C "$dest" fetch -q --depth 1 origin "$H3_RELAY_REF" 2>/dev/null || true
+ git -C "$dest" checkout -q "$H3_RELAY_REF" 2>/dev/null || echo "warn: could not pin h3-relay to $H3_RELAY_REF"
+fi
+
# Union of the packs' requirements, minus GPU-only / unbuildable extras
# (onnxruntime-gpu, cupy, groundingdino-py). triton + decord + pycocotools are needed only so
# ComfyUI-RMBG's SAM3 module imports (otherwise the whole RMBG pack fails to load).
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjs
index 56cb41ab..7520560d 100644
--- a/scripts/comfy/library.spec.mjs
+++ b/scripts/comfy/library.spec.mjs
@@ -91,7 +91,15 @@
// and black-and-white videos: params.matteOutput keeps one)). Entry fields: worker "isolated" (needs its own ComfyUI, see README), expand "captions" (the provider writes one
// segment per caption cue before submitting), "timeline", "videos" / "audios" (one loader per clip in inputs.videos / audios),
// optionalModels (files a model control can pick instead of the graph's own,
-// listed in the manifest with optional: true so missing-model help can name their download).
+// listed in the manifest with optional: true so missing-model help can name their download),
+// packs (node packs the validation server lacks, see PACK_CLASSES; listed in customNodes), modelUrls (a file's
+// download at a pinned revision for this workflow, over KNOWN_MODELS).
+// Keys added with Genjutsu's Character swap (O5, docs/research/openjutsu-6.md). * = the provider fills it:
+// quality* (H3 PrepareVideo resolution "480" | "768": params.resolution 480p / 768p)
+// selection, subjectIndex (who to swap: largest | leftmost | rightmost | index, and the index)
+// positiveCoords*, negativeCoords* (SAM3_Detect clicks: JSON [{"x","y"}] in the prepared first frame's pixels: params.points)
+// audioGuide, useMask (H3 audio guide; masked regeneration off = the whole frame)
+// windowFrames, historyFrames (H3 window plan: "124" / "18", strings of the pack's combos)
import fs from 'node:fs';
@@ -121,6 +129,17 @@ export const CUSTOM_NODE_REPOS = {
// isolated worker only (process-wide side effects / old pins), see scripts/comfy/README.md
'ComfyUI-LatentSyncWrapper': 'https://github.com/ShmuelRonen/ComfyUI-LatentSyncWrapper',
'ComfyUI-ThinkSound_Wrapper': 'https://github.com/ShmuelRonen/ComfyUI-ThinkSound_Wrapper',
+ // Genjutsu's Character swap (docs/research/openjutsu-6.md): Akatz Labs' H3 nodes, GPL-3.0. Not installed on the
+ // validation server (entries list them with `packs`); install-comfyui.sh pins both.
+ h3_character_swap: 'https://github.com/akatz-labs/h3-character-swap-tool/tree/0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b/worker_nodes/h3_character_swap',
+ 'h3-relay': 'https://github.com/akatz-ai/h3-relay',
+};
+
+// Node classes of the packs entries list in `packs` (packs the validation server doesn't have installed): the build
+// expects them instead of reporting "not installed", and the entry's customNodes name the pack.
+export const PACK_CLASSES = {
+ h3_character_swap: /^H3CharacterSwap/,
+ 'h3-relay': /^(H3Relay|LabsH3)/,
};
// Model download locations for files that the source workflow does not annotate
@@ -166,6 +185,14 @@ export const KNOWN_MODELS = {
'lightx2v_T2V_14B_cfg_step_distill_v2_lora_rank64_bf16.safetensors': { folder: 'loras', url: 'https://huggingface.co/Kijai/WanVideo_comfy/resolve/main/Lightx2v/lightx2v_T2V_14B_cfg_step_distill_v2_lora_rank64_bf16.safetensors' },
'Wan21-WanMove_fp8_scaled_e4m3fn_KJ.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Kijai/WanVideo_comfy_fp8_scaled/resolve/main/WanMove/Wan21-WanMove_fp8_scaled_e4m3fn_KJ.safetensors' },
'sam3.1_multiplex_fp16.safetensors': { folder: 'checkpoints', url: 'https://huggingface.co/Comfy-Org/sam3.1/resolve/main/checkpoints/sam3.1_multiplex_fp16.safetensors' },
+ // MiniMax H3 for the Character swap, at the revisions docs/research/openjutsu-6.md §6 read (sizes and SHA-256 there).
+ 'minimax_h3_ref2va_pruned_int8_convrot.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors' },
+ 'qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors': { folder: 'text_encoders', url: 'https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors' },
+ 'minimax_h3_video_vae_fp16.safetensors': { folder: 'vae', url: 'https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_video_vae_fp16.safetensors' },
+ 'minimax_h3_audio_vae_fp32.safetensors': { folder: 'vae', url: 'https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_audio_vae_fp32.safetensors' },
+ 'minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors': { folder: 'loras', url: 'https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors' },
+ 'h3_character_swap_v1.5.safetensors': { folder: 'loras', url: 'https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/d06323b7c8e70e97cdab48b78a1e05f786c8cba9/h3_character_swap_v1.5.safetensors' },
+ 'h3_character_swap_pro4500_1000.safetensors': { folder: 'loras', url: 'https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/a665bb7e3bb9804e487d2925f67744f554c8ad49/h3_character_swap_pro4500_1000.safetensors' },
'depth_anything_3_mono_large.safetensors': { folder: 'geometry_estimation', url: 'https://huggingface.co/Comfy-Org/Depth-Anything-3/resolve/main/geometry_estimation/depth_anything_3_mono_large.safetensors' },
// comfyui-oss-3 additions (docs/research/comfyui-oss-3.json, sizes from the Hugging Face tree API)
'z_image_turbo_bf16.safetensors': { folder: 'diffusion_models', url: 'https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/diffusion_models/z_image_turbo_bf16.safetensors' },
@@ -2769,6 +2796,70 @@ export const SPEC = [
'Window rules (startTime / duration in seconds, at most 81 frames), the work-size budget, paste-back and the kept sound as video-inpaint-wan-vace. Validated by /prompt only (no GPU here).',
},
+ // ---- Genjutsu Character swap (O5, docs/research/openjutsu-6.md): MiniMax H3 + Akatz Labs' Character Swap LoRA ----
+ // Openjutsu's graph (Comfy Org, MIT; derived from Akatz Labs' MIT workflow at 0670e4f) on the UNPATCHED h3_character_swap
+ // pack: the resolution goes as the string "480" / "768". The pack is not installed on the validation server, so these
+ // graphs are checked statically (core nodes against /object_info) and validate only where the pack is installed.
+ {
+ id: 'video-character-swap-h3',
+ title: 'Character swap: SAM 3.1 picks the person, MiniMax H3 + the Character Swap LoRA regenerate only them (h3_character_swap pack)',
+ capability: 'video-character-swap',
+ handBuilt: 'hand-built/video-character-swap-h3.json',
+ packs: ['h3_character_swap'],
+ modelUrls: { 'sam3.1_multiplex_fp16.safetensors': 'https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors' },
+ optionalModels: ['h3_character_swap_pro4500_1000.safetensors'],
+ bindings: {
+ video: [b('30', 'file')], image: [b('9', 'image')], image2: [b('anchor_image', 'image')],
+ startTime: [b('trim', 'start_time')], duration: [b('trim', 'duration'), b('31', 'duration_seconds')], quality: [b('31', 'resolution')],
+ prompt: [b('801', 'prompt')], seed: [b('801', 'seed')], steps: [b('801', 'steps')], cfg: [b('801', 'cfg')], audioGuide: [b('801', 'audio_guide')],
+ maskPrompt: [b('101', 'text')], selection: [b('104', 'selection')], subjectIndex: [b('104', 'index')], maskGrow: [b('110', 'expansion_px')],
+ positiveCoords: [b('103', 'positive_coords')], negativeCoords: [b('103', 'negative_coords')], useMask: [b('803', 'use_mask')],
+ windowFrames: [b('805', 'window_frames')], historyFrames: [b('805', 'history_frames')],
+ lora: [b('850', 'lora_name')], loraStrength: [b('850', 'strength_model')], filenamePrefix: [b('809', 'filename_prefix')],
+ },
+ outputs: [{ node: '809', kind: 'video' }],
+ defaults: { quality: '768', maskPrompt: 'person', selection: 'largest', subjectIndex: 0, maskGrow: 64, audioGuide: true, useMask: true, windowFrames: '124', historyFrames: '18', lora: 'h3_character_swap_v1.5.safetensors' },
+ limits: { maxDurationSec: 30, maxFrames: 3592 },
+ vramGb: 24,
+ license: 'MiniMax H3 Community License (H3 Ref2VA, its video and audio VAEs, the packaged Qwen3-VL text encoder, Akatz Labs\' Character Swap LoRA): territory EXCLUDES the US, the EU, the UK and South Korea; commercial use above US$20M yearly revenue needs MiniMax\'s written authorization; show "MiniMax H3" on the product\'s interface; no outputs used to improve other AI models · Qwen3-VL-32B base Apache-2.0 · SAM 3.1 under Meta\'s SAM License (commercial use allowed under its terms) · FL2V Turbo LoRA Apache-2.0 at the pinned revision · h3_character_swap nodes GPL-3.0 (Akatz Labs; NVIDIA INT8 kernel derivative Apache-2.0)',
+ notes:
+ 'Genjutsu "Character swap" on the open engine (Openjutsu, comfy-openjutsu @ 70ec62d; Akatz Labs h3-character-swap-tool @ 0670e4f). video = the clip, image = the character, image2 = the anchor first frame ' +
+ '(absent: the provider deletes anchor_image and anchor_fit, unlinks 803.anchor and sets 803.use_anchor false); startTime / duration pick the part (trim and 31.duration_seconds both get the length, 5-15 s; up to 30 s plans more windows, beyond H3\'s trained range). ' +
+ 'quality "480" | "768" (strings: the unpatched pack; Openjutsu\'s patched pack takes integers). prompt in H3\'s reference tags (<Video 1> the clip, <Picture 1> the character, <Picture 2> the anchor). ' +
+ 'Who to swap: maskPrompt (SAM words, "person"), selection largest | leftmost | rightmost | index with subjectIndex, or clicks as positiveCoords / negativeCoords (JSON pixel points on the prepared first frame). ' +
+ 'lora V1.5 (h3_character_swap_v1.5) or V1 (h3_character_swap_pro4500_1000); "none" deletes node 850 and feeds 800.model from the Turbo LoRA (node 4). 8 steps, CFG 1, er_sde / normal for the FL2V Turbo LoRA; windows 124 frames with 18 of history (17n+5 / 0, 1, 17n+1). ' +
+ 'The clip\'s own sound is put back by the pack (807) and kept by CreateVideo; the pack also writes its own MP4 under output/H3-Character-Swap. Needs FFmpeg and FFprobe on PATH. ' +
+ 'Tested by its authors on a 96 GB RTX PRO 6000 (Comfy) and a 24 GB RTX 4090 with 128 GB RAM and model offloading (Akatz); NVFP4 text encoding runs natively on compute capability 10+ (Blackwell), slower elsewhere. 46.33 GB of weights. ' +
+ 'Not validated here: the h3_character_swap nodes are not installed on this server (the 22 core nodes were checked against /object_info, docs/research/openjutsu-6.md §3.3).',
+ },
+ {
+ id: 'video-character-swap-h3-relay',
+ title: 'Character swap on H3 Relay 2.0: SAM 3.1 subject, MiniMax H3 + the Character Swap LoRA in native loop windows (h3-relay pack)',
+ capability: 'video-character-swap',
+ handBuilt: 'hand-built/video-character-swap-h3-relay.json',
+ packs: ['h3-relay'],
+ modelUrls: { 'sam3.1_multiplex_fp16.safetensors': 'https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors' },
+ optionalModels: ['h3_character_swap_pro4500_1000.safetensors'],
+ bindings: {
+ video: [b('source', 'file')], image: [b('reference', 'image')],
+ startTime: [b('trim', 'start_time')], duration: [b('trim', 'duration'), b('prepare', 'duration_seconds')], quality: [b('prepare', 'resolution')],
+ prompt: [b('reference_conditioning', 'prompt')], seed: [b('plan', 'seed')], steps: [b('schedule', 'steps')], cfg: [b('guider', 'cfg')], audioGuide: [b('history', 'target_audio_guide')],
+ maskPrompt: [b('subject', 'text')], selection: [b('select', 'selection')], subjectIndex: [b('select', 'index')], maskGrow: [b('expand_mask', 'expansion_px')],
+ positiveCoords: [b('detect', 'positive_coords')], negativeCoords: [b('detect', 'negative_coords')],
+ windowFrames: [b('plan', 'window_frames')], historyFrames: [b('plan', 'history_frames')],
+ lora: [b('adapter', 'lora_name')], loraStrength: [b('adapter', 'strength_model')], filenamePrefix: [b('save', 'filename_prefix')],
+ },
+ outputs: [{ node: 'save', kind: 'video' }],
+ defaults: { quality: '768', maskPrompt: 'person', selection: 'largest', subjectIndex: 0, maskGrow: 64, audioGuide: true, windowFrames: '124', historyFrames: '18', lora: 'h3_character_swap_v1.5.safetensors' },
+ limits: { maxDurationSec: 30, maxFrames: 3592 },
+ vramGb: 24,
+ license: 'MiniMax H3 Community License (H3 Ref2VA, its video and audio VAEs, the packaged Qwen3-VL text encoder, Akatz Labs\' Character Swap LoRA): territory EXCLUDES the US, the EU, the UK and South Korea; commercial use above US$20M yearly revenue needs MiniMax\'s written authorization; show "MiniMax H3" on the product\'s interface; no outputs used to improve other AI models · Qwen3-VL-32B base Apache-2.0 · SAM 3.1 under Meta\'s SAM License (commercial use allowed under its terms) · FL2V Turbo LoRA Apache-2.0 at the pinned revision · H3 Relay nodes GPL-3.0 (Sendy Software LLC and contributors; vendored Context Loop and Spectrum GPL-3.0); the graph is H3 Relay\'s example workflow (GPL-3.0 repository)',
+ notes:
+ 'Akatz Labs\' newer route for the same swap (h3-relay @ e2a7665b, 2.0.1; example_workflows/toolkit/H3-Character-Swap.api.json, which Akatz\'s tool ships at 5f83374). Changed: a Trim Video node picks the part, the mask preview is removed, the adapter loads the V1.5 file by its Hugging Face name. ' +
+ 'Bindings as video-character-swap-h3 without an anchor frame or a masked-generation switch; lora "none" deletes the adapter and feeds its users from the Turbo LoRA. H3 Relay registers HTTP routes and an in-memory H3 layout compatibility layer on import: run it on the isolated worker if you prefer (install-comfyui.sh installs it with H3_RELAY=1). ' +
+ 'Needs FFmpeg and FFprobe on PATH. Not validated here: the pack is not installed on this server.',
+ },
+
// ---- Faceless "Frame by frame": Ken Burns over a still ------------------------------
{
id: 'kenburns-still',
diff --git a/scripts/comfy/validation-state.json b/scripts/comfy/validation-state.json
index c0af1315..89732f4a 100644
--- a/scripts/comfy/validation-state.json
+++ b/scripts/comfy/validation-state.json
@@ -575,6 +575,18 @@
"error": null,
"at": "2026-10-23T16:47:53.446Z"
},
+ "video-character-swap-h3": {
+ "sha256": "37496982555a84ada4ccb22a155639d6ed8817b0cf0a868aa1497bd05c1c9de2",
+ "validated": false,
+ "error": "HTTP 400: missing_node_type: Node 'Prepare · 24 fps / pixel budget' not found. The custom node may not be installed. (Node ID '#31')",
+ "at": "2026-10-27T04:10:39.868Z"
+ },
+ "video-character-swap-h3-relay": {
+ "sha256": "7ff9fd0074152ee5bd15e187b04faec8d876164ea77b0df07224f2c41e677ee6",
+ "validated": false,
+ "error": "HTTP 400: missing_node_type: Node 'H3RelayAppendWindow' not found. The custom node may not be installed. (Node ID '#append')",
+ "at": "2026-10-27T04:10:39.895Z"
+ },
"video-concat-2": {
"sha256": "3d08966f5a3c2da662dc112df537ad4245bcd5dbb90e0451a0beb5c54d8db581",
"validated": true,
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index 7e0477fe..2b6190f7 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -929,6 +929,8 @@ model("scail-2", "SCAIL-2 (hosted)", "SCAIL", "scail", "video",
[("motion-transfer", "fal-ai/scail-2", "fal", {"fixed": {"mode": "animation"}}),
("video-swap", "fal-ai/scail-2", "fal", {"fixed": {"mode": "replacement"}})],
controls=[("subject_type", "Subject"), ("driving_type", "Driven by")], api_defaults={"prompt": _SCAIL_PROMPT},
+ # Words are optional: the API's own prompt (above) goes when none are given.
+ options={"promptOptional": True},
pricing=("second", 0.2, "512p or 704p; output at 16 fps, up to 10 s a call"), defaults={"resolution": "512p"})
model("wan-motion", "Wan Motion (hosted)", "Alibaba Wan", "wan", "video",
"Wan-Animate with pose retargeting: the motion fitted to your character's proportions",
diff --git a/src/lib/catalog/character-swap.ts b/src/lib/catalog/character-swap.ts
new file mode 100644
index 00000000..45c1153c
--- /dev/null
+++ b/src/lib/catalog/character-swap.ts
@@ -0,0 +1,439 @@
+/**
+ * Genjutsu's Character swap (Openjutsu and Akatz Labs' H3 Character Swap tool, docs/research/openjutsu-6.md): the person
+ * in a 5–15 s part of a clip becomes the character in one image, keeping the performance, the scene and the clip's own
+ * sound. On your GPU it is MiniMax H3 with Akatz Labs' Character Swap LoRA on the h3_character_swap node pack (SAM 3.1
+ * finds the person on the part's first frame and H3 regenerates only them, in 124-frame windows with 18 frames of
+ * history); in the cloud it is fal's MiniMax H3 reference-to-video with the same LoRA (no mask: who to swap is said in
+ * words). An optional "anchor" first frame (the part's first frame with the character already in it, made by an image
+ * edit) starts the swap off right; when it can't be made the swap runs without it.
+ *
+ * Pure module: limits, prompts, the H3 window plan, who to swap, the anchor's prompt and models, licences as data.
+ * The prompts follow Openjutsu's (MIT, Comfy Org 2026) and Akatz Labs' anchor brief (MIT, Akatz Labs 2026).
+ */
+import type { Engine, LoraRef, PixelPoint } from "./types";
+
+export const CHARACTER_SWAP = {
+ /** One H3 call: Openjutsu's part picker (Start 0 … duration − 5 s, Length 5 … 15 s). */
+ minSeconds: 5,
+ maxSeconds: 15,
+ /** Longer parts continue window by window (your GPU) or run as 15 s pieces joined with the sound (cloud). */
+ maxContinued: 30,
+ /** "Choose a clip at least 5 seconds long." Genjutsu's own upload limit (Openjutsu's is 100 MB). */
+ maxBytes: 200 * 1024 * 1024,
+ maxDirectionChars: 500,
+ maxDescriptionChars: 500,
+ /** Seeds Openjutsu takes (uint32); blank is random. */
+ maxSeed: 2 ** 32 - 1,
+ qualities: ["480p", "768p"] as const,
+ defaultQuality: "768p" as const,
+ /** H3's frame rate: every part is normalised to 24 fps before it is swapped. */
+ fps: 24,
+ window: 124,
+ history: 18,
+ /** H3's documented range ends near 362 frames (15 s): past it the pack prints "Long clip: beyond … trained range". */
+ trainedFrames: 362,
+ maskGrow: 64,
+ maxPeople: 8,
+ accept: "image/png,image/jpeg,image/webp,.png,.jpg,.jpeg,.webp",
+} as const;
+
+export type CharacterQuality = (typeof CHARACTER_SWAP.qualities)[number];
+
+/** Who to swap when several people are on screen (the pack's SelectSubject). */
+export type SwapWho = "largest" | "leftmost" | "rightmost" | "index";
+/** Akatz Labs' speaker choice for the performance prompt. */
+export type SwapSpeech = "character" | "other" | "offscreen" | "none";
+/** Character Swap LoRA releases: V1.5 (Akatz's recommended release), V1, or none (H3 with the Turbo LoRA only). */
+export type SwapLora = "v1.5" | "v1" | "none";
+
+export const WHO_LABELS: Record<SwapWho, string> = { largest: "Largest", leftmost: "Leftmost", rightmost: "Rightmost", index: "Person #" };
+export const SPEECH_LABELS: Record<SwapSpeech, { label: string; hint: string }> = {
+ character: { label: "My character speaks", hint: "Lips follow the clip's own voice" },
+ other: { label: "Someone else speaks", hint: "The character listens" },
+ offscreen: { label: "Offscreen voice", hint: "The voice isn't anyone on screen" },
+ none: { label: "No dialogue", hint: "Nobody speaks in this part" },
+};
+
+/** The Character Swap LoRA files (Hugging Face akatz-ai/MiniMax-H3-Character-Swap-LoRA at the researched revisions). */
+export const SWAP_LORAS: Record<Exclude<SwapLora, "none">, { label: string; file: string; url: string; bytes: number }> = {
+ "v1.5": {
+ label: "V1.5 (recommended)",
+ file: "h3_character_swap_v1.5.safetensors",
+ url: "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/d06323b7c8e70e97cdab48b78a1e05f786c8cba9/h3_character_swap_v1.5.safetensors",
+ bytes: 155_110_792,
+ },
+ v1: {
+ label: "V1",
+ file: "h3_character_swap_pro4500_1000.safetensors",
+ url: "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/a665bb7e3bb9804e487d2925f67744f554c8ad49/h3_character_swap_pro4500_1000.safetensors",
+ bytes: 155_110_320,
+ },
+};
+
+const H3_LORA_LICENCE = { commercial: true, hostedOk: true, snapshotDate: "2026-10-27", name: "MiniMax H3 Community License" };
+
+/** The swap LoRA a run carries (fal loads it by its pinned Hugging Face URL; ComfyUI gets the file downloaded). */
+export function swapLoraRef(lora: SwapLora | undefined): LoraRef {
+ const l = SWAP_LORAS[lora === "v1" ? "v1" : "v1.5"];
+ return { file: l.file, url: l.url, weightName: l.file, strength: 1, version: l.url.split("/resolve/")[1]?.split("/")[0], licence: H3_LORA_LICENCE };
+}
+
+/** lightx2v's FL2V Turbo 8-step LoRA the open graphs load (Apache-2.0 at this revision). */
+export const TURBO_LORA: LoraRef = {
+ file: "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ url: "https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ version: "3ec17a324ced54151364f24f8b5fb6bf7e26414f",
+ licence: { commercial: true, hostedOk: true, snapshotDate: "2026-10-27", name: "Apache-2.0" },
+};
+
+/** The ComfyUI workflows of the Character swap. */
+export const H3_WORKFLOWS = ["video-character-swap-h3", "video-character-swap-h3-relay"] as const;
+
+/**
+ * The LoRA files a Character swap graph loads itself (not injected: its own loaders name them), so a run can download
+ * the ones ComfyUI lacks before it starts: the Turbo LoRA and the swap LoRA's release (none: only Turbo).
+ */
+export function graphLoras(endpoint: string, extra: Record<string, unknown> | undefined): LoraRef[] {
+ if (!(H3_WORKFLOWS as readonly string[]).includes(endpoint)) return [];
+ const lora = extra?.lora;
+ return lora === "none" ? [TURBO_LORA] : [TURBO_LORA, swapLoraRef(lora === "v1" ? "v1" : "v1.5")];
+}
+
+/** The settings of one swap (the body's `character`, all optional: the defaults are Openjutsu's and Akatz's). */
+export interface CharacterOptions {
+ who?: SwapWho;
+ /** Person #n, from 0 (the pack's index). */
+ index?: number;
+ /** What SAM 3.1 looks for ("person"; "the man in the red jacket" picks among several). */
+ subject?: string;
+ /** Pixels the person's mask grows by (0–256). */
+ maskGrow?: number;
+ /** The anchor first frame (on by default). */
+ anchor?: boolean;
+ /** The image model that makes it (the engine's choice by default, ANCHOR_MODELS). */
+ anchorModel?: string;
+ /** What the character looks like, in words (Akatz found generic prompts weak). */
+ description?: string;
+ speech?: SwapSpeech;
+ /** The part's words (a transcript), for the performance prompt. */
+ dialogue?: string;
+ lora?: SwapLora;
+ /** H3's audio guide: the clip's own sound conditions the performance (the result keeps the sound either way). */
+ audioGuide?: boolean;
+ /** Masked regeneration (off: the whole frame is regenerated). */
+ useMask?: boolean;
+ /** Advanced: H3's window and continuation history (frames). */
+ windowFrames?: number;
+ historyFrames?: number;
+}
+
+// ---------------------------------------------------------------------------
+// Quality, sizes and windows
+
+/** Genjutsu's qualities to H3's two: 480p stays, anything higher is 768p (H3's native top). */
+export function characterQuality(q: string | undefined): CharacterQuality {
+ return q === "480p" ? "480p" : "768p";
+}
+
+/** What the unpatched h3_character_swap pack's PrepareVideo takes: the strings "480" / "768" (the patched one: integers). */
+export const packResolution = (q: string | undefined, patched = false): string | number => {
+ const v = characterQuality(q) === "480p" ? "480" : "768";
+ return patched ? Number(v) : v;
+};
+
+/** fal's H3 resolution enum for a quality. */
+export const falResolution = (q: string | undefined) => (characterQuality(q) === "480p" ? "480P" : "768P");
+
+/** H3's frame grid: the first count of the form 17n + 5 at or above n (ComfyUI's align_frame_count). */
+export function alignFrames(n: number): number {
+ let f = Math.max(5, Math.ceil(n));
+ while (f % 17 !== 5) f++;
+ return f;
+}
+
+/** Frames of a part at H3's 24 fps. */
+export const partFrames = (seconds: number) => Math.max(1, Math.round(seconds * CHARACTER_SWAP.fps));
+
+/**
+ * How many diffusion windows a part takes (the pack plans source-aligned windows over the part padded to H3's grid):
+ * 5 s → 1, 7.5 s and 10 s → 2, 12.5 s and 15 s → 3 (docs/research/openjutsu-6.md §3.4).
+ */
+export function h3Windows(seconds: number, windowFrames: number = CHARACTER_SWAP.window): number {
+ return Math.max(1, Math.ceil(alignFrames(partFrames(seconds)) / Math.max(22, windowFrames)));
+}
+
+/** Window sizes the pack takes (17n + 5, 22 … 362) and continuation history (0, 1 or 17n + 1, 18 … 341). */
+export const WINDOW_CHOICES = Array.from({ length: 21 }, (_, i) => 22 + 17 * i);
+export const HISTORY_CHOICES = [0, 1, ...Array.from({ length: 20 }, (_, i) => 18 + 17 * i)];
+
+const nearest = (xs: number[], v: number) => xs.reduce((a, b) => (Math.abs(b - v) < Math.abs(a - v) ? b : a));
+export const windowFrames = (v: number | undefined) => String(nearest(WINDOW_CHOICES, v ?? CHARACTER_SWAP.window));
+export const historyFrames = (v: number | undefined) => String(nearest(HISTORY_CHOICES, v ?? CHARACTER_SWAP.history));
+
+/**
+ * The size H3 works at for a clip: the short edge at 768 (or 480) px, the area capped at 768 × 1344 (480 × 840), each side
+ * rounded to 32 (ComfyUI's adapt_canvas). Clicks on the first frame are moved into these pixels. For 480p the pack's own
+ * rule isn't published: this scales ComfyUI's 768 rule, so clicks there are an estimate.
+ */
+export function h3Canvas(width: number, height: number, quality: string | undefined): { width: number; height: number } {
+ const short = characterQuality(quality) === "480p" ? 480 : 768;
+ const maxArea = short * Math.round((short * 1344) / 768);
+ const ratio = width / height;
+ let [w, h] = ratio >= 1 ? [short * ratio, short] : [short, short / ratio];
+ if (w * h > maxArea) {
+ const s = Math.sqrt(maxArea / (w * h));
+ w *= s;
+ h *= s;
+ }
+ const r32 = (v: number) => Math.max(32, Math.round(v / 32) * 32);
+ return { width: r32(w), height: r32(h) };
+}
+
+/** Clicks in the clip's pixels → SAM3_Detect's JSON points in H3's canvas: [positive, negative] ("" when none). */
+export function samCoords(points: PixelPoint[] | undefined, clip: { width: number; height: number }, quality: string | undefined): [string, string] {
+ if (!points?.length || !clip.width || !clip.height) return ["", ""];
+ const c = h3Canvas(clip.width, clip.height, quality);
+ const at = (p: PixelPoint) => ({ x: Math.round((p.x / clip.width) * c.width), y: Math.round((p.y / clip.height) * c.height) });
+ const pos = points.filter((p) => p.label !== "negative").map(at);
+ const neg = points.filter((p) => p.label === "negative").map(at);
+ return [pos.length ? JSON.stringify(pos) : "", neg.length ? JSON.stringify(neg) : ""];
+}
+
+// ---------------------------------------------------------------------------
+// Words
+
+const tidy = (s: string | undefined) => (s ?? "").replace(/\s+/g, " ").trim().replace(/[.\s]+$/, "");
+const ORDINALS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth"];
+
+/** Who to swap, in words (the cloud has no mask; the open graph's prompt keeps "the selected person"). */
+export function whoWords(o: Pick<CharacterOptions, "who" | "index" | "subject">): string {
+ const subject = tidy(o.subject);
+ if (subject && subject.toLowerCase() !== "person") return /^(the|a|an)\s/i.test(subject) ? subject : `the ${subject}`;
+ switch (o.who ?? "largest") {
+ case "leftmost":
+ return "the person on the left";
+ case "rightmost":
+ return "the person on the right";
+ case "index":
+ return `the ${ORDINALS[Math.max(0, Math.min(ORDINALS.length - 1, o.index ?? 0))]} person from the left`;
+ default:
+ return "the main person";
+ }
+}
+
+/** One line for who speaks (Akatz Labs' speaker choice), with the part's words when there are some. */
+export function speechLine(speech: SwapSpeech | undefined, dialogue?: string): string {
+ const words = tidy(dialogue).slice(0, 600);
+ const said = words ? ` The words: "${words}".` : "";
+ switch (speech) {
+ case "character":
+ return `The character speaks the clip's lines, lips in sync with its audio.${said}`;
+ case "other":
+ return `Someone else speaks; the character listens and does not talk.${said}`;
+ case "offscreen":
+ return `The voice comes from off screen; the character does not speak.${said}`;
+ case "none":
+ return "Nobody speaks in this part.";
+ default:
+ return "";
+ }
+}
+
+export interface SwapPromptInput extends Pick<CharacterOptions, "who" | "index" | "subject" | "description" | "speech" | "dialogue"> {
+ engine: Engine;
+ /** The anchor first frame goes along (Picture 2 / Image 2). */
+ anchor: boolean;
+ /** Your direction (≤ 500 characters). */
+ direction?: string;
+}
+
+/**
+ * The swap's prompt: Openjutsu's instruction in H3's reference tags, the anchor sentence only with an anchor, then the
+ * character's description, who speaks and your direction. ComfyUI's graph names the inputs <Video 1>, <Picture 1> and
+ * <Picture 2>; fal's H3 names them Video 1, Image 1 and Image 2. Open: the mask says who; cloud: the words do.
+ */
+export function swapPrompt(p: SwapPromptInput): string {
+ const open = p.engine === "open";
+ const video = open ? "<Video 1>" : "Video 1";
+ const picture = (n: number) => (open ? `<Picture ${n}>` : `Image ${n}`);
+ const who = open ? "the selected person" : whoWords(p);
+ const parts = [`Replace ${who} in ${video} with the character in ${picture(1)}. Preserve the source performance, scene and audio timing.`];
+ if (p.anchor) parts.push(`Start from the first frame in ${picture(2)}.`);
+ const description = tidy(p.description).slice(0, CHARACTER_SWAP.maxDescriptionChars);
+ if (description) parts.push(`The character: ${description}.`);
+ const speech = speechLine(p.speech, p.dialogue);
+ if (speech) parts.push(speech);
+ const direction = tidy(p.direction).slice(0, CHARACTER_SWAP.maxDirectionChars);
+ if (direction) parts.push(`${direction[0].toUpperCase()}${direction.slice(1)}.`);
+ return parts.join(" ");
+}
+
+/**
+ * The anchor frame's edit (image 1: the part's first frame, image 2: the character): Openjutsu's instruction, or Akatz
+ * Labs' brief when the character is described (it names who to replace and keeps everyone else).
+ */
+export function anchorPrompt(o: Pick<CharacterOptions, "who" | "index" | "subject" | "description">): string {
+ const description = tidy(o.description).slice(0, CHARACTER_SWAP.maxDescriptionChars);
+ if (!description) {
+ return "Replace the person in image 1 with the character from image 2, including their face, hair, body and complete outfit exactly as shown in image 2. Do not keep any of the original person's clothing. Keep image 1's pose, framing, background and lighting.";
+ }
+ return (
+ `Image 1 is the source frame to edit. Image 2 is character identity only: ${description}. Replace ONLY ${whoWords(o)} with that single character. ` +
+ "Match the exact source pose, face angle, gaze, mouth opening, expression, limb placement, scale and occlusions. Preserve all other people, the entire original scene, camera framing, lighting and aspect ratio. " +
+ "Keep the reference identity and costume; do not copy the reference pose or background. One full-aspect edited source frame."
+ );
+}
+
+/** The image edit that makes the anchor frame, per engine (the first is the default; docs/research/openjutsu-6.md §10). */
+export const ANCHOR_MODELS: Record<Engine, { id: string; label: string; note: string; extra?: Record<string, string>; tokens?: string }[]> = {
+ cloud: [
+ // fal bills Sunburst by tokens, so the catalog has no fixed price for it: the estimate leaves it out and says so.
+ { id: "gpt-image-2-5-sunburst", label: "GPT Image 2.5 Sunburst", note: "Openjutsu's choice, low quality: billed by tokens", extra: { quality: "low" }, tokens: "$8 per million tokens in, $30 per million out" },
+ { id: "nano-banana-pro", label: "Nano Banana Pro", note: "$0.15 an image" },
+ ],
+ open: [{ id: "oss-qwen-edit", label: "Qwen-Image-Edit 2511", note: "Free on your GPU (24 GB)" }],
+};
+
+export const anchorModel = (engine: Engine, id?: string) => ANCHOR_MODELS[engine].find((m) => m.id === id) ?? ANCHOR_MODELS[engine][0];
+
+/** What a run says when the anchor frame couldn't be made (the swap goes ahead without it). */
+export const ANCHOR_FALLBACK = "Couldn't make the first frame — swapped without it";
+
+// ---------------------------------------------------------------------------
+// Checks and notes
+
+/** What stops a part from being swapped, or null. `continued`: longer parts are allowed (up to 30 s). */
+export function partProblem(part: { start: number; end: number }, clipSeconds?: number): string | null {
+ const len = part.end - part.start;
+ if (clipSeconds !== undefined && clipSeconds < CHARACTER_SWAP.minSeconds - 0.05) return `Choose a clip at least ${CHARACTER_SWAP.minSeconds} seconds long`;
+ if (!(len > 0) || part.start < 0) return "Choose where the part starts";
+ if (clipSeconds !== undefined && part.end > clipSeconds + 0.05) return "The part runs past the end of the clip";
+ if (len < CHARACTER_SWAP.minSeconds - 0.05) return `Pick a part of ${CHARACTER_SWAP.minSeconds}–${CHARACTER_SWAP.maxSeconds} seconds (this is ${len.toFixed(1)} s)`;
+ if (len > CHARACTER_SWAP.maxContinued + 0.05) return `A part can run up to ${CHARACTER_SWAP.maxContinued} seconds — 5–15 s swaps best`;
+ return null;
+}
+
+export function seedProblem(seed: number | undefined): string | null {
+ if (seed === undefined) return null;
+ return Number.isInteger(seed) && seed >= 0 && seed <= CHARACTER_SWAP.maxSeed ? null : "Use a whole-number seed, or leave it blank";
+}
+
+/** The hard cuts inside a part (times in the clip), from the browser's cut detection (Katana's detectCuts). */
+export const cutsInPart = (cuts: number[] | undefined, part: { start: number; end: number }) => (cuts ?? []).filter((t) => t > part.start + 0.2 && t < part.end - 0.2);
+
+/** The warning for a part with a hard cut (the swap breaks at a cut). */
+export function cutWarning(cuts: number[]): string | null {
+ if (!cuts.length) return null;
+ const at = cuts.map((t) => `${t.toFixed(1)} s`).join(", ");
+ return `Your part has a cut at ${at} — the swap breaks at a cut. Move the part, or pick one continuous shot`;
+}
+
+/** The limits the page shows before a run (Openjutsu's README and Akatz Labs' validation notes). */
+export const CHARACTER_LIMITS = [
+ "A part of 5–15 seconds (up to 30 s, continued window by window)",
+ "One continuous shot: a hard cut breaks the swap",
+ "The person must be visible in the part's first frame",
+ "With several people, the largest is swapped unless you pick another",
+ "A silent clip gives a silent result",
+] as const;
+
+/** What the open route was tested on (its authors' words), for the GPU line. */
+export const CHARACTER_GPU = {
+ weightsGb: 46.33,
+ tested: "Tested by its authors on a 96 GB RTX PRO 6000, and on a 24 GB RTX 4090 with 128 GB of RAM and model offloading",
+ advice: "24 GB of VRAM with offloading and 64–128 GB of RAM; 48 GB+ for 768p. The NVFP4 text encoder runs at full speed on Blackwell (RTX 50, RTX PRO 6000) and slower on older GPUs",
+ speed: "About two minutes for 5 s at 480p on a warm RTX PRO 6000",
+} as const;
+
+// ---------------------------------------------------------------------------
+// Licences (information for Settings → Models & licences, never a gate: the owner's decision of 2026-10-27)
+
+export type CharacterLicenceClass = "commercial" | "conditions" | "regions" | "non-commercial" | "paid-api";
+
+export interface CharacterLicence {
+ /** What it covers. */
+ item: string;
+ name: string;
+ class: CharacterLicenceClass;
+ url: string;
+ /** Who a restricted-regions licence leaves out. */
+ excludes?: string;
+ /** Notices the app must show. */
+ notices?: string[];
+ note: string;
+}
+
+const H3_LICENCE_URL = "https://huggingface.co/MiniMaxAI/MiniMax-H3/blob/42ed227ee7df40d41602854ae760620d6eb651fe/LICENSE";
+
+export const MINIMAX_H3_LICENCE: CharacterLicence = {
+ item: "MiniMax H3 (diffusion model, VAEs, packaged text encoder) and Akatz Labs' Character Swap LoRA V1 / V1.5",
+ name: "MiniMax H3 Community License",
+ class: "regions",
+ url: H3_LICENCE_URL,
+ excludes: "the US, the EU, the UK and South Korea",
+ notices: ["MiniMax H3"],
+ note:
+ "Granted outside the US, the EU, the UK and South Korea (MiniMax sells licences there, through Comfy); written authorization above US$20M yearly revenue; " +
+ 'show "MiniMax H3" on a commercial product\'s interface; outputs may not be used to improve other AI models; services for others must keep safeguards and a way to report misuse. MiniMax claims no rights over the outputs',
+};
+
+/** Every licence the Character swap touches, as data (the model picker's line and Settings → Models & licences). */
+export const CHARACTER_LICENCES: CharacterLicence[] = [
+ MINIMAX_H3_LICENCE,
+ {
+ item: "SAM 3.1 (finds and follows the person)",
+ name: "Meta SAM License",
+ class: "conditions",
+ url: "https://huggingface.co/Comfy-Org/sam3.1/blob/7bb8374780a725b4353ed31f3a9395c9742b5621/LICENSE",
+ note: "Royalty-free, commercial use allowed; give a copy of the licence when distributing, acknowledge SAM in publications, follow trade controls; no military, nuclear or weapons uses",
+ },
+ {
+ item: "FL2V Turbo 8-step LoRA (lightx2v)",
+ name: "Apache-2.0",
+ class: "commercial",
+ url: "https://huggingface.co/lightx2v/Minimax-h3-Turbo/blob/3ec17a324ced54151364f24f8b5fb6bf7e26414f/README.md",
+ note: "Apache-2.0 at the pinned revision; the current card no longer states a licence",
+ },
+ {
+ item: "h3_character_swap node pack (Akatz Labs)",
+ name: "GPL-3.0",
+ class: "commercial",
+ url: "https://github.com/akatz-labs/h3-character-swap-tool/tree/0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b/worker_nodes/h3_character_swap",
+ note: "GPL-3.0 code, like ComfyUI; a modified NVIDIA INT8 kernel inside is Apache-2.0",
+ },
+ {
+ item: "H3 Relay 2.0 node pack (Akatz Labs)",
+ name: "GPL-3.0",
+ class: "commercial",
+ url: "https://github.com/akatz-ai/h3-relay",
+ note: "GPL-3.0 code (Sendy Software LLC and contributors); vendored Context Loop and Spectrum GPL-3.0",
+ },
+ {
+ item: "Openjutsu's workflow and Akatz Labs' app",
+ name: "MIT",
+ class: "commercial",
+ url: "https://github.com/Comfy-Org/comfy-openjutsu",
+ note: "The graph Fuobe runs is Openjutsu's (Comfy Org, MIT), derived from Akatz Labs' MIT workflow",
+ },
+ {
+ item: "fal's hosted MiniMax H3 and H3 Max Recast",
+ name: "Paid API · fal.ai",
+ class: "paid-api",
+ url: "https://fal.ai/models/minimax/h3/reference-to-video/lora",
+ note: "Pay per second on your fal key, under fal's terms and MiniMax's",
+ },
+];
+
+/** The node packs, in the shape Settings → Models & licences lists packs (src/lib/licences.ts NODE_PACKS on model-access). */
+export const H3_NODE_PACKS = CHARACTER_LICENCES.filter((l) => l.item.includes("node pack")).map((l) => ({
+ name: l.item.startsWith("h3_character_swap") ? "h3_character_swap" : "h3-relay",
+ repo: l.url,
+ licence: { name: l.name, class: l.class, url: l.url, note: l.note },
+}));
+
+/** One line for a model picker: the licence that matters most for the route, as information. */
+export function characterLicenceLine(engine: Engine, modelId: string): string {
+ if (modelId === "h3-max-recast") return "MiniMax's closed H3 Max through fal: pay per second, under fal's and MiniMax's terms";
+ const h3 = `MiniMax H3 Community License — not licensed in ${MINIMAX_H3_LICENCE.excludes}; commercial use over US$20M revenue needs MiniMax's OK; show "MiniMax H3"`;
+ return engine === "open" ? `${h3} · nodes GPL-3.0 · SAM License` : `${h3} · on fal, pay per second`;
+}
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index cda5eb32..582de357 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -14398,7 +14398,8 @@ export const CLOUD_MODELS: ModelDef[] = [
"512p",
"704p"
],
- "maxImages": 1
+ "maxImages": 1,
+ "promptOptional": true
},
"defaults": {
"resolution": "512p"
diff --git a/src/lib/catalog/genjutsu.ts b/src/lib/catalog/genjutsu.ts
index 45157ac0..04c4e9a2 100644
--- a/src/lib/catalog/genjutsu.ts
+++ b/src/lib/catalog/genjutsu.ts
@@ -1,18 +1,38 @@
/**
- * 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).
+ * Fuobe Genjutsu (build plan O5): keep a clip's motion, camera and framing, change what is in it. Five modes: Motion
+ * transfer (your character does what the clip's person does), Character swap (the person in a 5–15 s part becomes your
+ * character, sound and performance kept: Openjutsu / Akatz Labs' H3 Character Swap), Object swap (a thing, a person or
+ * an outfit becomes your reference), Restyle (every frame takes a look) and Insert (your reference is added where you
+ * say). Each mode's default is a Fuobe Original — open weights on your GPU (ComfyUI) and the same open weights hosted on
+ * fal in the cloud: Wan Animate for motion, MiniMax H3 + the Character Swap LoRA for characters, SAM 3.1 + Wan VACE for
+ * swaps, a restyled first frame + Wan Fun VACE for looks. Lite is the cheaper, faster tier of the same Original. Other
+ * hosted open models (SCAIL-2, Wan Motion, Wan 2.2 Animate Replace, hosted Wan 2.2 VACE) and partner models (Kling,
+ * P-Video, H3 Max Recast, Gemini Omni, Happy Horse) stay as labelled alternatives. No Higgsfield model or look.
*
- * 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.
+ * Every model takes a part of the clip (Kling 3–15 s, VACE 81 or 241 frames, H3 5–15 s…), 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/fuobe-originals-recipes-5.md §8 genjutsu and O5, openjutsu-6.md, paid-model-apis-4.md §4,
+ * comfyui-oss-4.md §c.
*/
+import {
+ anchorModel,
+ anchorPrompt,
+ ANCHOR_FALLBACK,
+ CHARACTER_SWAP,
+ characterQuality,
+ cutsInPart,
+ partProblem,
+ seedProblem,
+ swapLoraRef,
+ swapPrompt,
+ whoWords,
+ type CharacterOptions,
+ type SwapLora,
+ type SwapSpeech,
+ type SwapWho,
+} from "./character-swap";
import {
joinWithSound,
MASK_TRACKER,
@@ -29,27 +49,28 @@ import {
type RemoveRange,
type RemoveSource,
} from "./remove-object";
-import { getShortsPreset, lookFromPreset, planShorts, type PlanStep, type ShortsLook } from "./shorts";
+import { firstFramePrompt, getShortsPreset, lookFromPreset, planShorts, segmentPrompt, type PlanStep, type ShortsLook } from "./shorts";
+import { soulLook } from "./soul";
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 GenjutsuMode = "motion" | "character" | "swap" | "restyle" | "insert";
+/** How you say what changes (Object swap and Insert) or who (Character swap): 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 GenjutsuQuality = "480p" | "720p" | "768p" | "1080p";
+/** Lite ("standard", the cheaper, faster tier of the same Original) or the full Original ("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". */
+ /** The source window: "Choose a source video between 4 and 30 seconds" (Higgsfield's limit, kept). */
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. */
+ /** A custom Restyle look: up to 8 images. */
maxLookImages: 8,
maxPoints: 12,
maxPromptChars: 2000,
@@ -60,19 +81,29 @@ export const GENJUTSU = {
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: "character",
+ label: "Character swap",
+ hint: "Your character takes over the person in the clip — same moves, same scene, same sound. Pick 5–15 seconds of one continuous shot with the person in the first frame.",
+ 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: "restyle", label: "Restyle", hint: "Pick a look 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"] };
+/** The ways of saying what changes, per mode (Motion transfer and Restyle change the whole shot; Character swap says who). */
+export const MODE_TARGETS: Record<GenjutsuMode, GenjutsuTarget[]> = { motion: [], restyle: [], character: ["type", "click"], swap: ["type", "click", "paint"], insert: ["type", "paint"] };
export const TARGET_LABELS: Record<GenjutsuMode, Partial<Record<GenjutsuTarget, { label: string; hint: string }>>> = {
motion: {},
restyle: {},
+ character: {
+ type: { label: "Pick who", hint: "The largest, leftmost or rightmost person, or a number" },
+ click: { label: "Click them", hint: "Click the person on the part's first frame" },
+ },
swap: {
type: { label: "Type it", hint: "Name what to swap" },
click: { label: "Click it", hint: "Click it on the first frame" },
@@ -87,19 +118,23 @@ export const TARGET_LABELS: Record<GenjutsuMode, Partial<Record<GenjutsuTarget,
// ---------------------------------------------------------------------------
// Models ("makers")
+/** Where a model comes from: a Fuobe Original, other open weights hosted on fal, or a partner's closed model. */
+export type MakerSource = "original" | "open" | "partner";
+
+export const SOURCE_LABELS: Record<MakerSource, string> = { original: "Fuobe Original", open: "Open weights", partner: "Partner" };
+
export interface Maker {
- /** The catalog model. */
+ /** The catalog model (a Fuobe Original has one entry per engine, under the same id). */
id: string;
engine: Engine;
modes: GenjutsuMode[];
- /** Object swap and Insert: how it is told what changes. */
+ /** Object swap, Insert and Character swap: how it is told what changes (or who). */
targets?: GenjutsuTarget[];
label: string;
- /** One line for the picker: what it's good at and its limits (open: GPU and licence). */
+ /** One line for the picker: what it's good at and its limits (open: GPU). */
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. */
+ source: MakerSource;
+ /** Lite (the cheaper, faster tier) or the full Original, and the other one. */
tier?: GenjutsuTier;
pair?: string;
/** Reference images it takes (extra ones are left out, said in a note). */
@@ -116,112 +151,267 @@ export interface Maker {
qualities?: string[];
/** Without a resolution setting: what it renders, in words ("keeps your clip's size", "renders 4K"). */
renders?: string;
- /** Words aren't needed (Genjutsu and P-Video find what to swap from the references). */
+ /** Words aren't needed (P-Video and Recast find who 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. */
+ /** Restyle: it takes Fuobe's looks (presets, Soul looks, your own images). */
+ looks?: "fuobe";
+ /** Restyle: how many of a look's reference images it reads. */
readsLookImages?: number;
+ /** fal bills frames ÷ this as "video seconds" (Wan Animate and VACE count 16 a second, Wan Motion 24). */
+ billFps?: number;
+ /** params.extra its open route gets (Lite: Wan Animate 2 in 4 steps). */
+ extra?: Record<string, unknown>;
+ /** Character swap on MiniMax H3: who to swap, the anchor first frame and the H3 settings apply. */
+ h3?: { anchor: boolean };
}
-/** fal's hosted Wan 2.2 VACE Fun: 17–241 frames (4n+1, the clip's own count and rate), at most 30 fps. */
+/** fal's hosted Wan VACE (2.1 14B and 2.2 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"];
+const VACE_FUN_CLOUD = "wan-22-vace-inpaint";
+const FAL_RES = ["480p", "580p", "720p"];
+
+export const ORIGINALS = {
+ motion: "fuobe-genjutsu-motion",
+ motionLite: "fuobe-genjutsu-motion-lite",
+ swap: "fuobe-genjutsu-swap",
+ swapLite: "fuobe-genjutsu-swap-lite",
+ restyle: "fuobe-genjutsu-restyle",
+ character: "fuobe-character-swap",
+} as const;
+
+const ORIGINAL_IDS = new Set<string>([...Object.values(ORIGINALS), "fuobe-soul"]);
+/** A model that runs on both engines: its steps say which one (GenerationRequest.engine). */
+export const isOriginal = (id: string) => ORIGINAL_IDS.has(id);
export const MAKERS: Maker[] = [
- // Motion transfer (cloud).
+ // Motion transfer.
{
- id: "genjutsu-lite-motion-transfer",
+ id: ORIGINALS.motionLite,
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,
+ label: "Fuobe Genjutsu",
+ note: "Wan 2.2 Animate on fal at 480p with its turbo pass · one character image · the clip's sound put back",
+ source: "original",
tier: "standard",
- pair: "genjutsu-motion-transfer",
- refs: { min: 1, max: 8 },
- maxSeconds: 15,
- minSeconds: 4,
- keepsSound: true,
- qualities: HIGH_RES,
+ pair: ORIGINALS.motion,
+ refs: { min: 1, max: 1 },
+ maxSeconds: 30,
+ keepsSound: false,
+ qualities: ["480p"],
+ billFps: 16,
+ promptOptional: true,
},
{
- id: "genjutsu-motion-transfer",
+ id: ORIGINALS.motion,
engine: "cloud",
modes: ["motion"],
- label: "Genjutsu",
- note: "Higgsfield's full model · up to 30 s · up to 8 references · sound kept",
- higgsfield: true,
+ label: "Fuobe Genjutsu",
+ note: "Wan 2.2 Animate on fal, up to 720p · one character image · the clip's sound put back",
+ source: "original",
tier: "high",
- pair: "genjutsu-lite-motion-transfer",
- refs: { min: 1, max: 8 },
+ pair: ORIGINALS.motionLite,
+ refs: { min: 1, max: 1 },
maxSeconds: 30,
- minSeconds: 4,
- keepsSound: true,
- qualities: HIGH_RES,
+ keepsSound: false,
+ qualities: FAL_RES,
+ billFps: 16,
+ promptOptional: true,
+ },
+ {
+ id: "scail-2",
+ engine: "cloud",
+ modes: ["motion", "character"],
+ targets: ["type"],
+ label: "SCAIL-2",
+ note: "No skeletons: humans, several people or animals · up to 10 s a call · $0.20/s",
+ source: "open",
+ refs: { min: 1, max: 1 },
+ maxSeconds: 10,
+ minSeconds: 1,
+ keepsSound: false,
+ qualities: ["512p", "704p"],
+ promptOptional: true,
+ },
+ {
+ id: "wan-motion",
+ engine: "cloud",
+ modes: ["motion"],
+ label: "Wan Motion",
+ note: "Wan-Animate with the moves fitted to your character's proportions · 720p",
+ source: "open",
+ refs: { min: 1, max: 1 },
+ maxSeconds: 30,
+ keepsSound: false,
+ renders: "renders 720p",
+ billFps: 24,
+ promptOptional: true,
},
{
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",
+ note: "Kuaishou's closed model · one character image · pieces of up to 10 s",
+ source: "partner",
refs: { min: 1, max: 1 },
maxSeconds: 10,
minSeconds: 3,
keepsSound: false,
renders: "picks its own size",
},
- // Object swap (cloud).
{
- id: "genjutsu-lite-object-swap",
+ id: ORIGINALS.motionLite,
+ engine: "open",
+ modes: ["motion"],
+ label: "Fuobe Genjutsu",
+ note: "Wan Animate 2 at 480p in 4 steps · free on your GPU (24 GB) · Apache-2.0",
+ source: "original",
+ tier: "standard",
+ pair: ORIGINALS.motion,
+ refs: { min: 1, max: 1 },
+ keepsSound: true,
+ qualities: ["480p"],
+ extra: { steps: 4 },
+ promptOptional: true,
+ },
+ {
+ id: ORIGINALS.motion,
+ engine: "open",
+ modes: ["motion"],
+ label: "Fuobe Genjutsu",
+ note: "Wan Animate 2 copies the performance in 81-frame fragments · free on your GPU (24 GB) · Apache-2.0",
+ source: "original",
+ tier: "high",
+ pair: ORIGINALS.motionLite,
+ refs: { min: 1, max: 1 },
+ keepsSound: true,
+ qualities: ["480p", "720p"],
+ promptOptional: true,
+ },
+
+ // Character swap (Openjutsu, Akatz Labs' H3 Character Swap).
+ {
+ id: ORIGINALS.character,
engine: "cloud",
- modes: ["swap"],
+ modes: ["character"],
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,
+ label: "Fuobe Character swap",
+ note: "MiniMax H3 + Akatz Labs' swap LoRA on fal · 5–15 s a call · who to swap in words (no mask) · the clip's sound put back",
+ source: "original",
+ refs: { min: 1, max: 1 },
+ maxSeconds: CHARACTER_SWAP.maxSeconds,
+ minSeconds: CHARACTER_SWAP.minSeconds,
+ keepsSound: false,
+ qualities: ["480p", "768p"],
+ h3: { anchor: true },
+ promptOptional: true,
+ },
+ {
+ id: "h3-max-recast",
+ engine: "cloud",
+ modes: ["character"],
+ targets: ["type"],
+ label: "MiniMax H3 Max Recast",
+ note: "MiniMax's own swap: 1–4 people from photos, across shots, sound kept · 5–30 s · $0.30/s",
+ source: "partner",
+ refs: { min: 1, max: 4 },
+ maxSeconds: 30,
+ minSeconds: 5,
keepsSound: true,
- qualities: HIGH_RES,
+ qualities: ["768p", "1080p"],
promptOptional: true,
+ people: true,
},
{
- id: "genjutsu-object-swap",
+ id: "wan-22-animate-replace",
engine: "cloud",
- modes: ["swap"],
+ modes: ["character"],
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 },
+ label: "Wan 2.2 Animate Replace",
+ note: "Wan 2.2 Animate on fal replaces the person, lighting matched · one image · up to 720p",
+ source: "open",
+ refs: { min: 1, max: 1 },
maxSeconds: 30,
- minSeconds: 4,
+ keepsSound: false,
+ qualities: FAL_RES,
+ billFps: 16,
+ promptOptional: true,
+ people: true,
+ },
+ {
+ id: ORIGINALS.character,
+ engine: "open",
+ modes: ["character"],
+ targets: ["type", "click"],
+ label: "Fuobe Character swap",
+ note: "MiniMax H3 + the swap LoRA on your GPU: SAM 3.1 picks the person, only they are regenerated · free · 48 GB+ advised",
+ source: "original",
+ refs: { min: 1, max: 1 },
+ keepsSound: true,
+ qualities: ["480p", "768p"],
+ h3: { anchor: true },
+ promptOptional: true,
+ },
+ {
+ id: "oss-h3-character-swap-relay",
+ engine: "open",
+ modes: ["character"],
+ targets: ["type", "click"],
+ label: "H3 Character Swap · Relay 2.0",
+ note: "The same swap on Akatz Labs' H3 Relay 2.0 nodes (native loops) · no anchor frame · free on your GPU",
+ source: "open",
+ refs: { min: 1, max: 1 },
keepsSound: true,
- qualities: HIGH_RES,
+ qualities: ["480p", "768p"],
+ h3: { anchor: false },
promptOptional: true,
- minPixels: 409_600,
+ },
+
+ // Object swap.
+ {
+ id: ORIGINALS.swapLite,
+ engine: "cloud",
+ modes: ["swap"],
+ targets: ["type", "click", "paint"],
+ label: "Fuobe Genjutsu",
+ note: "SAM 3.1 follows it, Wan VACE paints your reference in · 480p, fast · up to 4 references",
+ source: "original",
+ tier: "standard",
+ pair: ORIGINALS.swap,
+ refs: { min: 1, max: 4 },
+ window: VACE_CLOUD_WINDOW,
+ maxFps: 30,
+ keepsSound: false,
+ qualities: ["480p"],
+ },
+ {
+ id: ORIGINALS.swap,
+ engine: "cloud",
+ modes: ["swap"],
+ targets: ["type", "click", "paint"],
+ label: "Fuobe Genjutsu",
+ note: "SAM 3.1 follows it, Wan VACE paints your reference in · up to 720p · up to 4 references",
+ source: "original",
+ tier: "high",
+ pair: ORIGINALS.swapLite,
+ refs: { min: 1, max: 4 },
+ window: VACE_CLOUD_WINDOW,
+ maxFps: 30,
+ keepsSound: false,
+ qualities: FAL_RES,
},
{
id: "kling-o3",
engine: "cloud",
- modes: ["swap", "insert"],
+ modes: ["swap", "insert", "character"],
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",
+ note: "Kuaishou's closed model · up to 4 references as @Image · 3–15 s a piece · keeps the clip's size",
+ source: "partner",
refs: { min: 1, max: 4 },
maxSeconds: 15,
minSeconds: 3,
@@ -232,10 +422,11 @@ export const MAKERS: Maker[] = [
{
id: "p-video-replace",
engine: "cloud",
- modes: ["swap"],
+ modes: ["swap", "character"],
targets: ["type"],
label: "P-Video Replace",
- note: "Swaps the person on camera for 1–3 photos of someone · motion, timing and scene kept",
+ note: "Pruna's closed model: the person on camera becomes the one in 1–3 photos · motion, timing and scene kept",
+ source: "partner",
refs: { min: 1, max: 3 },
keepsSound: true,
qualities: ["720p", "1080p"],
@@ -243,39 +434,73 @@ export const MAKERS: Maker[] = [
people: true,
},
{
- id: VACE_CLOUD,
+ id: VACE_FUN_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",
+ note: "Open weights on fal: changes exactly the area you mark on the first frame · up to 4 references · 241 frames a piece",
+ source: "open",
refs: { min: 1, max: 4 },
window: VACE_CLOUD_WINDOW,
maxFps: 30,
keepsSound: false,
- qualities: ["480p", "580p", "720p"],
+ qualities: FAL_RES,
+ },
+ {
+ id: ORIGINALS.swapLite,
+ engine: "open",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "Fuobe Genjutsu",
+ note: "SAM 3.1 follows what you name, Wan 2.1 VACE paints your first reference in · 480p · free on your GPU (24 GB)",
+ source: "original",
+ tier: "standard",
+ pair: ORIGINALS.swap,
+ refs: { min: 1, max: 1 },
+ window: VACE_WINDOW,
+ keepsSound: true,
+ qualities: ["480p"],
+ },
+ {
+ id: ORIGINALS.swap,
+ engine: "open",
+ modes: ["swap"],
+ targets: ["type"],
+ label: "Fuobe Genjutsu",
+ note: "SAM 3.1 follows what you name, Wan 2.1 VACE paints your first reference in · free on your GPU (24 GB) · Apache-2.0",
+ source: "original",
+ tier: "high",
+ pair: ORIGINALS.swapLite,
+ refs: { min: 1, max: 1 },
+ window: VACE_WINDOW,
+ keepsSound: true,
+ qualities: ["480p", "720p"],
},
- // Restyle (cloud).
+
+ // Restyle.
{
- id: "genjutsu-restyle",
+ id: ORIGINALS.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",
+ label: "Fuobe Genjutsu",
+ note: "The first frame takes the look, then Wan 2.2 Fun VACE carries it through every frame by depth · 241 frames a piece",
+ source: "original",
+ refs: { min: 0, max: 0 },
+ window: VACE_CLOUD_WINDOW,
+ maxFps: 30,
+ keepsSound: false,
+ qualities: FAL_RES,
+ looks: "fuobe",
+ readsLookImages: 2,
},
{
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",
+ note: "Google's closed model · restyles from the look's words · pieces of up to 10 s",
+ source: "partner",
refs: { min: 0, max: 0 },
keepsSound: false,
qualities: ["720p", "1080p"],
@@ -286,7 +511,8 @@ export const MAKERS: Maker[] = [
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",
+ note: "Kuaishou's closed model · reads up to 4 of the look's images · 4K · pieces of up to 10 s",
+ source: "partner",
refs: { min: 0, max: 0 },
keepsSound: false,
renders: "renders 4K",
@@ -298,72 +524,69 @@ export const MAKERS: Maker[] = [
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",
+ note: "Closed model · reads up to 4 of the look's images · billed on the clip's seconds too",
+ source: "partner",
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",
+ id: ORIGINALS.restyle,
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"],
+ modes: ["restyle"],
+ label: "Fuobe Genjutsu",
+ note: "The first frame takes the look (Qwen-Image-Edit, or Z-Image with a Soul look's LoRAs), then Wan 2.2 Fun VACE by depth · 5 s segments at 16 fps, 480p",
+ source: "original",
+ refs: { min: 0, max: 0 },
+ keepsSound: false,
+ renders: "renders 480p at 16 fps",
+ looks: "fuobe",
+ readsLookImages: 2,
},
+
+ // Insert (no Original yet: VACE inserts in a painted spot on both engines).
{
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",
+ note: "Your first reference in the painted spot, held for the whole shot (a still or slow camera) · free on your GPU (24 GB) · Apache-2.0",
+ source: "open",
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,
- renders: "renders 480p at 16 fps",
- looks: "fuobe",
- readsLookImages: 2,
- },
];
-export const getMaker = (id: string | undefined) => MAKERS.find((m) => m.id === id);
+/** The maker for a model id (on an engine: an Original has one per engine; the first otherwise). */
+export const getMaker = (id: string | undefined, engine?: Engine) => MAKERS.find((m) => m.id === id && (!engine || m.engine === engine));
-/** 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[] {
+/**
+ * Setups and links made before the Originals name Higgsfield's Genjutsu or the round-4 open models: the Original that
+ * replaced each (the look and tier are kept where they still mean something).
+ */
+export const LEGACY_MAKERS: Record<string, string> = {
+ "genjutsu-motion-transfer": ORIGINALS.motion,
+ "genjutsu-lite-motion-transfer": ORIGINALS.motionLite,
+ "genjutsu-object-swap": ORIGINALS.swap,
+ "genjutsu-lite-object-swap": ORIGINALS.swapLite,
+ "genjutsu-restyle": ORIGINALS.restyle,
+ "oss-wan22-animate": ORIGINALS.motion,
+ "oss-vace-swap": ORIGINALS.swap,
+ "oss-wan22-vace-restyle": ORIGINALS.restyle,
+};
+
+/** The models you can pick for this engine, mode and way of pointing. */
+export function makersFor(engine: Engine, mode: GenjutsuMode, target?: GenjutsuTarget): 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).
+ // Lite and the full Original 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;
});
}
@@ -373,40 +596,34 @@ export const OPEN_TARGET_PROBLEM: Partial<Record<GenjutsuMode, string>> = {
insert: "On your ComfyUI, paint where it goes — saying it in words is on the cloud engine",
};
-/** Restyle on the open engine with one of Higgsfield's looks (they run on Higgsfield's Genjutsu Restyle only). */
-export const OPEN_LOOK_PROBLEM = "Higgsfield's looks run on the cloud engine — pick one of the 44 looks or Your own";
+/** Clicking who to swap needs SAM 3.1's mask, which only the open graph has. */
+export const CLOUD_CLICK_PROBLEM = "Clicking the person works on your GPU (SAM 3.1 marks them) — on the cloud, pick who in words";
+
+const SOURCE_RANK: Record<MakerSource, number> = { original: 0, open: 1, partner: 2 };
/**
- * 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.
+ * The model a request runs on, or why there is none. Without a modelId: the mode's Fuobe Original (Lite unless the
+ * tier is High), then other open weights, then partners.
*/
-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 } {
+export function chooseMaker(o: { engine: Engine; mode: GenjutsuMode; target?: GenjutsuTarget; tier?: GenjutsuTier; look?: GenjutsuLook; modelId?: string }): { 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 (target && !MODE_TARGETS[o.mode].includes(target)) return { problem: `${getMode(o.mode).label} doesn't take ${target === "click" ? "clicks" : target === "paint" ? "paint" : "that"} — pick another way` };
+ const options = makersFor(o.engine, o.mode, target);
if (!options.length) {
- if (o.engine === "open" && o.mode === "restyle" && o.look?.kind === "higgsfield") return { problem: OPEN_LOOK_PROBLEM };
+ if (o.engine === "cloud" && o.mode === "character" && target === "click") return { problem: CLOUD_CLICK_PROBLEM };
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);
+ const withTier = (m: Maker) => (m.pair && o.tier && m.tier !== o.tier ? (getMaker(m.pair, m.engine) ?? m) : m);
+ const id = o.modelId && (LEGACY_MAKERS[o.modelId] ?? o.modelId);
+ const picked = getMaker(id, o.engine);
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) };
+ // The picker lists Lite; a High pick (or a setup naming the full Original) is the same choice.
+ const lite = picked.tier === "high" && picked.pair ? getMaker(picked.pair, picked.engine)! : picked;
+ if (options.includes(lite)) return { maker: o.tier ? withTier(lite) : picked };
}
- 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 };
+ const first = [...options].sort((a, b) => SOURCE_RANK[a.source] - SOURCE_RANK[b.source])[0];
+ // Restyle with your own look's images on a partner list: a model that reads them.
+ if (o.mode === "restyle" && o.look?.kind === "custom" && first.source === "partner") return { maker: options.find((m) => m.readsLookImages) ?? first };
return { maker: withTier(first) };
}
@@ -414,20 +631,23 @@ export function chooseMaker(o: {
// Looks (Restyle)
export type GenjutsuLook =
- /** One of the 44 Shorts presets (Fuobe's words). */
+ /** One of the 44 Shorts looks (Fuobe's words). */
| { kind: "preset"; id: string }
- /** One of Higgsfield's live Genjutsu looks (its preset_id). */
- | { kind: "higgsfield"; id: string; name?: string }
+ /** One of Fuobe Soul's 139 looks: its LoRAs and words on the first frame. */
+ | { kind: "soul"; id: 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). */
+/** The Shorts look a Fuobe look restyles with (null: 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;
+ if (look.kind === "soul") {
+ const s = soulLook(look.id);
+ return s ? { presetId: s.id, name: s.name, look: s.look } : null;
+ }
const words = look.words?.trim().replace(/[.\s]+$/, "");
return {
presetId: "genjutsu-custom",
@@ -442,7 +662,7 @@ export function shortsLook(look: GenjutsuLook): ShortsLook | null {
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";
+ if (look.kind === "soul") return soulLook(look.id)?.name ?? "a Soul look";
return "your look";
}
@@ -450,16 +670,10 @@ export function lookName(look: GenjutsuLook | undefined): string {
// 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,
+ * Per-second list prices the catalog doesn't carry per resolution: 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 },
};
@@ -468,9 +682,7 @@ export function makerStepUsd(modelId: string, params: { duration?: number; resol
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);
+ return usd * (params?.duration ?? 0);
}
const px = (q: string) => parseInt(q, 10) || 0;
@@ -478,6 +690,7 @@ const px = (q: string) => parseInt(q, 10) || 0;
/** 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.h3) return characterQuality(quality);
if (m.qualities.includes(quality)) return quality;
const below = m.qualities.filter((q) => px(q) <= px(quality)).sort((a, b) => px(b) - px(a));
return below[0] ?? [...m.qualities].sort((a, b) => px(a) - px(b))[0];
@@ -510,21 +723,26 @@ export function swapParts(text: string): { what: string; into?: string } {
}
/**
- * 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).
+ * What a sentence says to swap, for SAM 3.1 to track: "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);
}
+const isVace = (id: string) => id === VACE_FUN_CLOUD || id === ORIGINALS.swap || id === ORIGINALS.swapLite || id === "oss-vace-insert";
+
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). */
+ /** Guidance: the result (swap), where it goes (insert), the character (motion), extra words (restyle), direction (character). */
prompt?: string;
refs: number;
+ /** Character swap's settings, and whether the anchor first frame goes along. */
+ character?: CharacterOptions;
+ anchor?: boolean;
}
/** Each model's words for the request (undefined: none needed). */
@@ -533,12 +751,23 @@ export function makerPrompt(p: PromptInput): string | undefined {
const words = tidy(p.prompt);
const { what, into } = swapParts(p.subject ?? "");
const also = into ? ` (${into})` : "";
+ if (p.mode === "character") {
+ const c = p.character ?? {};
+ if (m.h3) return swapPrompt({ ...c, engine: m.engine, anchor: !!p.anchor, direction: p.prompt });
+ const who = whoWords(c);
+ const described = tidy(c.description);
+ const look = described ? `, ${described}` : "";
+ if (m.id === "kling-o3") return `Replace ${who} in @Video1 with ${imageTags(1)}${look}${words ? `. ${cap(words)}` : ""}. Keep everything else the same: the performance, camera, framing, light and timing.`;
+ if (m.id === "h3-max-recast") return `${cap(who)} becomes the person in the photo${look}.${words ? ` ${cap(words)}.` : ""}`;
+ const out = [described ? `The character: ${described}.` : "", words ? `${cap(words)}.` : ""].filter(Boolean).join(" ");
+ return out || undefined;
+ }
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") {
+ if (isVace(m.id)) {
// 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.";
@@ -550,7 +779,6 @@ export function makerPrompt(p: PromptInput): string | undefined {
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;
}
@@ -577,10 +805,12 @@ export interface GenjutsuCheck {
points?: number;
mask?: boolean;
look?: GenjutsuLook;
+ seed?: number;
}
/** What's wrong with the selection whatever the model, or null. */
-export function rangeProblem(source: Pick<RemoveSource, "duration">, range: RemoveRange): string | null {
+export function rangeProblem(source: Pick<RemoveSource, "duration">, range: RemoveRange, mode?: GenjutsuMode): string | null {
+ if (mode === "character") return partProblem(range, source.duration);
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";
@@ -591,6 +821,7 @@ export function rangeProblem(source: Pick<RemoveSource, "duration">, range: Remo
const REFS_MISSING: Record<GenjutsuMode, string> = {
motion: "Add a picture of your character",
+ character: "Add a picture of your character",
swap: "Add a picture of what goes in",
insert: "Add a picture of what to add",
restyle: "",
@@ -598,7 +829,7 @@ const REFS_MISSING: Record<GenjutsuMode, string> = {
/** 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);
+ const general = rangeProblem(c.source, c.range, c.mode);
if (general) return general;
const m = c.maker;
const len = c.range.end - c.range.start;
@@ -609,10 +840,8 @@ export function genjutsuProblem(c: GenjutsuCheck): string | null {
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}) — pick another model`;
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) {
- // The hosted VACE is the only model for clicks and paint: the way out is words (or a slower copy of the clip).
const others = makersFor(m.engine, c.mode, target).filter((x) => x.id !== m.id);
const words = TARGET_LABELS[c.mode].type?.label;
const way = others.length ? "pick another model" : words && target !== "type" ? `switch to “${words}”, or save the clip at ${m.maxFps} fps and add it again` : `save the clip at ${m.maxFps} fps and add it again`;
@@ -622,10 +851,14 @@ export function genjutsuProblem(c: GenjutsuCheck): string | null {
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`;
}
+ if (c.mode === "character") {
+ const seed = seedProblem(c.seed);
+ if (seed) return seed;
+ if (target === "click" && !c.points) return "Click the person to swap on the first frame";
+ return null;
+ }
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”";
@@ -648,6 +881,14 @@ export function planMakerPieces(m: Maker, source: RemoveSource, range: RemoveRan
return [{ index: 0, start: range.start, end: range.end }];
}
+/** The seconds a step is billed for: fal's "video seconds" are frames ÷ 16 (or 24), the clip keeping its own rate. */
+export function billedSeconds(m: Maker, piece: Piece, fps: number | undefined): number {
+ if (piece.frames && m.window) return r6(piece.frames / (m.billFps ?? 16));
+ const secs = piece.end - piece.start;
+ if (m.billFps && fps) return r6((secs * fps) / m.billFps);
+ return r3(secs);
+}
+
// ---------------------------------------------------------------------------
// The pipeline
@@ -670,36 +911,55 @@ export interface GenjutsuPlanInput {
mask?: string;
look?: GenjutsuLook;
seed?: number;
+ /** Character swap's settings. */
+ character?: CharacterOptions;
}
export interface GenjutsuPlan {
steps: PlanStep[];
/** The finished video's step. */
final: string;
- /** Pieces (cloud), windows (open) or segments (Restyle on Fuobe looks). */
+ /** Pieces (cloud), windows (open) or segments (Restyle). */
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. */
+ /** Cloud swaps: SAM 3.1 follows the object (or the person) through the selection first. */
tracked: boolean;
+ /** Character swap: the anchor first frame is made (and the swap goes on without it if it can't be). */
+ anchors?: number;
}
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" };
+const OP: Record<GenjutsuMode, GenerationRequest["op"]> = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v" };
+
+/** Steps on a model that runs on both engines say which one (Originals, the Soul look's first frame). */
+function pinEngines(steps: PlanStep[], engine: Engine): PlanStep[] {
+ return steps.map((s) => (isOriginal(s.request.modelId) ? { ...s, request: { ...s.request, engine } } : s));
+}
/**
* 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);
+ * - Character swap on MiniMax H3: the anchor first frame (the part's first frame with the character in it), then the
+ * swap with the anchor as Picture 2 — or without it when it couldn't be made; the cloud cuts 15 s pieces;
+ * - Restyle: a restyled first frame and Wan Fun VACE per segment (the Original), or the Shorts chain (partners);
+ * - open VACE swap / insert: one window per job straight from the upload (the graph reads its own 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; Fuobe Genjutsu's swap follows the object
+ * with SAM 3.1 (words, clicks or the paint's points) and paints into its mask video; the hosted Wan 2.2 VACE reads a
+ * still mask of each piece's first frame;
* - then the pieces joined and the clip's own sound put back.
*/
export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
+ const plan = planSteps(input);
+ return { ...plan, steps: pinEngines(plan.steps, input.maker.engine) };
+}
+
+function planSteps(input: GenjutsuPlanInput): GenjutsuPlan {
+ if (input.mode === "character" && input.maker.h3) return planCharacterSwap(input);
+ if (input.mode === "restyle" && input.maker.id === ORIGINALS.restyle && input.maker.engine === "cloud") return planCloudRestyle(input);
if (input.mode === "restyle" && input.maker.looks === "fuobe") return planFuobeRestyle(input);
const m = input.maker;
const t = REMOVE_TOOLS[m.engine];
@@ -717,11 +977,11 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
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 prompt = makerPrompt({ mode: input.mode, maker: m, subject: input.subject, prompt: input.prompt, refs: refs.length, character: input.character });
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}`);
+ const extra = m.extra ? { extra: { ...m.extra } } : {};
if (m.engine === "open" && m.window) {
// VACE windows: the graph reads [startTime, endTime) of the upload itself.
@@ -740,7 +1000,7 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
aspectRatio: "auto",
...(resolution ? { resolution } : {}),
...seed,
- ...(input.mode === "swap" && input.subject?.trim() ? { extra: { maskPrompt: swapTarget(input.subject) } } : {}),
+ ...(input.mode === "swap" && input.subject?.trim() ? { extra: { ...m.extra, maskPrompt: swapTarget(input.subject) } } : extra),
},
step: pieceLabel(p, n, input.mode === "insert" ? "add it" : "swap it"),
},
@@ -758,29 +1018,33 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
op,
...words,
inputs: { ...(cut ? {} : { video: input.source.url }), ...images },
- params: { aspectRatio: "auto", ...(resolution ? { resolution } : {}), ...seed },
+ params: { aspectRatio: "auto", ...(resolution ? { resolution } : {}), ...seed, ...extra },
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);
+ // Cloud. Fuobe Genjutsu's swap reads a mask video: SAM 3.1's track of what you named, clicked or painted, cut like
+ // the clip. The hosted Wan 2.2 VACE reads a still mask of its piece's first frame: the paint for one piece, else the
+ // first frame of the track.
+ const original = m.id === ORIGINALS.swap || m.id === ORIGINALS.swapLite;
+ const tracked = input.mode === "swap" && (original || (m.id === VACE_FUN_CLOUD && (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) {
+ const named = target === "type" && input.subject?.trim() ? swapTarget(input.subject) : undefined;
steps.push({
key: "track",
request: {
...helper,
modelId: MASK_TRACKER,
op: "bg-remove-video",
+ ...(named ? { prompt: named } : {}),
...(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 },
+ params: { ...(named ? {} : { points: input.points }), duration: r3(input.range.end - input.range.start) },
+ step: { label: named ? `Follow ${named} (SAM 3.1)` : "Follow what you marked (SAM 3.1)", index: 0, of: 1 },
},
...(cutRange ? { after: ["range"], chain: [{ slot: "video" as const }] } : {}),
});
@@ -799,24 +1063,26 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
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;
+ if (tracked) {
+ // The track covers the selection: each piece takes its own part of it.
+ 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}`;
+ }
+ if (original) {
+ after.push(from);
+ chain.push({ slot: "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);
+ } else if (m.id === VACE_FUN_CLOUD && input.mask) mask = input.mask;
+ // What per-second prices count: the piece's seconds, or fal's video seconds (frames ÷ 16).
+ const secs = billedSeconds(m, p, input.source.fps);
steps.push({
key: keys[i],
request: {
@@ -825,8 +1091,8 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
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"),
+ params: { duration: secs, sourceDuration: r3(p.end - p.start), ...(resolution ? { resolution } : {}), ...(m.window ? { aspectRatio: "auto" } : {}), ...(input.source.fps ? { fps: input.source.fps } : {}), ...seed },
+ step: pieceLabel(p, n, input.mode === "motion" ? "transfer the motion" : input.mode === "insert" ? "add it" : "swap it"),
},
...(after.length ? { after, chain } : {}),
});
@@ -839,7 +1105,160 @@ export function planGenjutsu(input: GenjutsuPlanInput): GenjutsuPlan {
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. */
+// ---------------------------------------------------------------------------
+// Character swap
+
+/** The open graph's H3 settings (params.extra): who to swap, the mask, the LoRA, the windows. */
+export function h3Extra(c: CharacterOptions | undefined): Record<string, unknown> {
+ const o = c ?? {};
+ const who: SwapWho = o.who ?? "largest";
+ const subject = (o.subject ?? "").trim();
+ return {
+ selection: who,
+ subjectIndex: who === "index" ? Math.max(0, Math.min(CHARACTER_SWAP.maxPeople - 1, Math.round(o.index ?? 0))) : 0,
+ ...(subject ? { maskPrompt: subject.slice(0, 120) } : {}),
+ ...(o.maskGrow !== undefined ? { maskGrow: Math.max(0, Math.min(256, Math.round(o.maskGrow))) } : {}),
+ ...(o.audioGuide === false ? { audioGuide: false } : {}),
+ ...(o.useMask === false ? { useMask: false } : {}),
+ ...(o.windowFrames !== undefined ? { windowFrames: o.windowFrames } : {}),
+ ...(o.historyFrames !== undefined ? { historyFrames: o.historyFrames } : {}),
+ ...(o.lora && o.lora !== "v1.5" ? { lora: o.lora } : {}),
+ };
+}
+
+/**
+ * Character swap on MiniMax H3. Open: one job on the upload (the graph trims the part, finds the person with SAM 3.1,
+ * continues window after window up to 30 s and keeps the clip's sound). Cloud: 15 s pieces (5–15 s each), each with
+ * its anchor, joined, and the clip's sound put back. The anchor (the part's first frame with the character in it) is
+ * an optional input of the swap: if it fails, the swap runs without it and says so.
+ */
+function planCharacterSwap(input: GenjutsuPlanInput): GenjutsuPlan {
+ const m = input.maker;
+ const c = input.character ?? {};
+ const base = { feature: GENJUTSU.feature, batchTitle: input.title };
+ const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };
+ const character = input.references.slice(0, 1);
+ if (!character.length) throw new Error(REFS_MISSING.character);
+ const quality = characterQuality(input.quality);
+ const seed = input.seed !== undefined ? { seed: input.seed } : {};
+ const anchorOn = !!m.h3?.anchor && c.anchor !== false;
+ const am = anchorModel(m.engine, c.anchorModel);
+ const steps: PlanStep[] = [];
+ const promptWith = (anchor: boolean) => makerPrompt({ mode: "character", maker: m, prompt: input.prompt, refs: 1, character: c, anchor })!;
+ const anchorStep = (key: string, frameKey: string, label: { label: string; index: number; of: number }): PlanStep => ({
+ key,
+ request: {
+ ...helper,
+ modelId: am.id,
+ op: "edit",
+ prompt: anchorPrompt(c),
+ inputs: { images: character },
+ params: { ...(am.extra ? { extra: { ...am.extra } } : {}), ...seed },
+ step: label,
+ },
+ after: [frameKey],
+ chain: [{ slot: "images", position: "first" }],
+ });
+ /** The anchor goes in last among the swap's images (Picture 2); when it fails the swap goes on with this prompt. */
+ const anchorSlot = (): ChainSlot => ({ slot: "images", position: "last", optional: { prompt: promptWith(false), notice: ANCHOR_FALLBACK } });
+
+ if (m.engine === "open") {
+ const start = input.range.start;
+ if (anchorOn) {
+ steps.push({
+ key: "frame",
+ request: { ...helper, modelId: "oss-extract-frame", op: "frame", inputs: { video: input.source.url }, params: { startTime: start, endTime: start + 0.5, extra: { frameIndex: 0 } }, step: { label: "The part's first frame", index: 0, of: 1 } },
+ });
+ steps.push(anchorStep("anchor", "frame", { label: `Put your character in it (${am.label})`, index: 0, of: 1 }));
+ }
+ steps.push({
+ key: "swap",
+ request: {
+ ...base,
+ title: input.title,
+ modelId: m.id,
+ op: "video-swap",
+ prompt: promptWith(anchorOn),
+ inputs: { video: input.source.url, images: character },
+ params: {
+ startTime: r3(input.range.start),
+ endTime: r3(input.range.end),
+ resolution: quality,
+ ...(input.points?.length ? { points: input.points } : {}),
+ ...seed,
+ extra: h3Extra(c),
+ },
+ step: { label: "Swap the character (MiniMax H3)", index: 0, of: 1 },
+ },
+ ...(anchorOn ? { after: ["anchor"], chain: [anchorSlot()] } : {}),
+ });
+ return { steps, final: "swap", pieces: 1, sound: false, tracked: false, anchors: anchorOn ? 1 : 0 };
+ }
+
+ // Cloud: fal's H3 takes 5–15 s of reference video and whole seconds of output.
+ const pieces = planCloudPieces(input.range, CHARACTER_SWAP.maxSeconds, input.source.fps);
+ const n = pieces.length;
+ const sound = !!input.source.hasAudio;
+ const keys: string[] = [];
+ const lora = swapLoraRef(c.lora);
+ pieces.forEach((p, i) => {
+ const label = (what: string) => pieceLabel(p, n, what);
+ const secs = r3(p.end - p.start);
+ const callSecs = Math.min(CHARACTER_SWAP.maxSeconds, Math.max(CHARACTER_SWAP.minSeconds, Math.ceil(secs - 1e-6)));
+ steps.push({ key: `cut${i}`, request: { ...helper, modelId: REMOVE_TOOLS.cloud.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: p.start, endTime: p.end }, step: label("cut") } });
+ const after = [`cut${i}`];
+ const chain: ChainSlot[] = [{ slot: "video" }];
+ if (anchorOn) {
+ steps.push({ key: `frame${i}`, request: { ...helper, modelId: "extract-frame", op: "frame", params: { extra: { frame_type: "first" } }, step: label("first frame") }, after: [`cut${i}`], chain: [{ slot: "video" }] });
+ steps.push(anchorStep(`anchor${i}`, `frame${i}`, label(`put your character in it (${am.label})`)));
+ after.push(`anchor${i}`);
+ chain.push(anchorSlot());
+ }
+ const fit = callSecs - secs > 0.05;
+ const own = n === 1 && !sound && !fit;
+ steps.push({
+ key: `swap${i}`,
+ request: {
+ ...(own ? { ...base, title: input.title } : helper),
+ modelId: m.id,
+ op: "video-swap",
+ prompt: promptWith(anchorOn),
+ inputs: { images: character },
+ loras: [lora],
+ params: { duration: callSecs, sourceDuration: secs, resolution: quality, ...seed },
+ step: label("swap the character"),
+ },
+ after,
+ chain,
+ });
+ if (fit) {
+ // H3 makes whole seconds: the extra is cut off, so the pieces stay on the clip's sound.
+ steps.push({ key: `fit${i}`, request: { ...(n === 1 && !sound ? { ...base, title: input.title } : helper), modelId: REMOVE_TOOLS.cloud.cut, op: "trim", params: { startTime: 0, endTime: secs }, step: label("trim to the part") }, after: [`swap${i}`], chain: [{ slot: "video" }] });
+ keys.push(`fit${i}`);
+ } else keys.push(`swap${i}`);
+ });
+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: "cloud", title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound });
+ return { steps, final, pieces: n, sound, tracked: false, anchors: anchorOn ? n : 0 };
+}
+
+// ---------------------------------------------------------------------------
+// Restyle
+
+/** The first frame's restyle: a Soul look's LoRAs on Z-Image (Fuobe Soul's edit), else Qwen-Image-Edit with the look's images. */
+function lookFrameRequest(engine: Engine, look: GenjutsuLook, sl: ShortsLook, refs: string[], seed: object): Pick<GenerationRequest, "modelId" | "op" | "prompt" | "presetId" | "inputs" | "params"> {
+ if (look.kind === "soul") {
+ return { modelId: "fuobe-soul", op: "edit", presetId: look.id, prompt: "The same frame: every person, face, pose and object in place", params: { ...seed } };
+ }
+ return {
+ modelId: engine === "open" ? "oss-qwen-edit" : "qwen-image-edit-2511-cloud",
+ op: "edit",
+ prompt: firstFramePrompt(sl, "auto", refs.length),
+ ...(refs.length ? { inputs: { images: refs } } : {}),
+ params: { ...seed },
+ };
+}
+
+/** Restyle on a Fuobe look through the Shorts chain in the clip's own shape (the open Original, and partners). */
function planFuobeRestyle(input: GenjutsuPlanInput): GenjutsuPlan {
const look = input.look && shortsLook(input.look);
if (!look) throw new Error("Pick a look");
@@ -860,13 +1279,61 @@ function planFuobeRestyle(input: GenjutsuPlanInput): GenjutsuPlan {
});
// 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 },
- }));
+ const seed = input.seed !== undefined ? { seed: input.seed } : {};
+ const steps = plan.steps.map((s) => {
+ let request: GenerationRequest = s.key === final ? { ...s.request, feature: GENJUTSU.feature, title: input.title } : { ...s.request, feature: GENJUTSU.stepFeature };
+ // A Soul look restyles the first frame with its own LoRAs (Fuobe Soul's edit) instead of the Qwen edit.
+ if (input.look?.kind === "soul" && /^frame\d/.test(s.key)) request = { ...request, ...lookFrameRequest(m.engine, input.look, look, [], seed), inputs: undefined };
+ return { ...s, request };
+ });
return { steps, final, pieces: plan.segments.length, sound: !!input.source.hasAudio, tracked: false };
}
+/**
+ * The cloud Original's restyle: per piece of up to 241 frames, cut it, restyle its first frame (a Soul look's LoRAs on
+ * Z-Image, or Qwen-Image-Edit with the look's words and images), then Wan 2.2 Fun VACE carries the look through every
+ * frame by depth (fal's first_frame_url); the pieces are joined and the clip's sound put back.
+ */
+function planCloudRestyle(input: GenjutsuPlanInput): GenjutsuPlan {
+ const look = input.look && shortsLook(input.look);
+ if (!look) throw new Error("Pick a look");
+ const m = input.maker;
+ const pieces = planMakerPieces(m, input.source, input.range);
+ if (!pieces.length) throw new Error("Couldn't read this clip's frame rate — save it as an MP4 (H.264) and try again");
+ const n = pieces.length;
+ const base = { feature: GENJUTSU.feature, batchTitle: input.title };
+ const helper = { feature: GENJUTSU.stepFeature, batchTitle: input.title };
+ const sound = !!input.source.hasAudio;
+ const seed = input.seed !== undefined ? { seed: input.seed } : {};
+ const refs = (look.references ?? []).slice(0, m.readsLookImages ?? 2);
+ const resolution = qualityFor(m, input.quality);
+ const steps: PlanStep[] = [];
+ const keys: string[] = [];
+ pieces.forEach((p, i) => {
+ const label = (what: string) => pieceLabel(p, n, what);
+ steps.push({ key: `cut${i}`, request: { ...helper, modelId: REMOVE_TOOLS.cloud.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: p.start, endTime: p.end }, step: label("cut") } });
+ steps.push({ key: `frame${i}`, request: { ...helper, modelId: "extract-frame", op: "frame", params: { extra: { frame_type: "first" } }, step: label("first frame") }, after: [`cut${i}`], chain: [{ slot: "video" }] });
+ steps.push({ key: `look${i}`, request: { ...helper, ...lookFrameRequest("cloud", input.look!, look, refs, seed), step: label(`first frame as ${look.name}`) }, after: [`frame${i}`], chain: [{ slot: "images", position: "first" }] });
+ const own = n === 1 && !sound;
+ steps.push({
+ key: `restyle${i}`,
+ request: {
+ ...(own ? { ...base, title: input.title } : helper),
+ modelId: m.id,
+ op: "v2v",
+ prompt: segmentPrompt(look),
+ params: { duration: billedSeconds(m, p, input.source.fps), sourceDuration: r3(p.end - p.start), aspectRatio: "auto", ...(resolution ? { resolution } : {}), ...(input.source.fps ? { fps: input.source.fps } : {}), ...seed },
+ step: label("restyle"),
+ },
+ after: [`cut${i}`, `look${i}`],
+ chain: [{ slot: "video" }, { slot: "images", position: "first" }],
+ });
+ keys.push(`restyle${i}`);
+ });
+ const final = n === 1 && !sound ? keys[0] : joinWithSound(steps, { engine: "cloud", title: input.title, base, helper, source: input.source, range: input.range, pieces: keys, sound, end: pieces[n - 1].end });
+ return { steps, final, pieces: n, sound, tracked: false };
+}
+
// ---------------------------------------------------------------------------
// Setup codes ("share by code", done locally: the settings as base64url JSON)
@@ -882,12 +1349,17 @@ export interface GenjutsuSetup {
look?: GenjutsuLook;
/** Reference images (files in this install's library). */
references?: string[];
+ /** Character swap's settings (not the part's words: they belong to the clip). */
+ character?: Omit<CharacterOptions, "dialogue">;
}
const MODES = new Set<string>(GENJUTSU_MODES.map((m) => m.id));
+const QUALITIES = new Set<string>(["480p", "720p", "768p", "1080p"]);
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) : []);
+const num = (v: unknown, min: number, max: number) => (typeof v === "number" && Number.isFinite(v) ? Math.max(min, Math.min(max, Math.round(v))) : undefined);
+const oneOf = <T extends string>(v: unknown, xs: readonly T[]): T | undefined => (typeof v === "string" && (xs as readonly string[]).includes(v) ? (v as T) : undefined);
function toBase64Url(text: string): string {
const bytes = new TextEncoder().encode(text);
@@ -902,10 +1374,55 @@ function fromBase64Url(code: string): string {
return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
}
+/** Character swap's settings as they travel in a code: known values only, defaults left out. */
+export function cleanCharacter(v: unknown): Omit<CharacterOptions, "dialogue"> | undefined {
+ if (!v || typeof v !== "object") return undefined;
+ const o = v as Record<string, unknown>;
+ const out: Omit<CharacterOptions, "dialogue"> = {};
+ const who = oneOf(o.who, ["largest", "leftmost", "rightmost", "index"] as const);
+ if (who) out.who = who;
+ const index = num(o.index, 0, CHARACTER_SWAP.maxPeople - 1);
+ if (index !== undefined && who === "index") out.index = index;
+ const subject = str(o.subject, 120);
+ if (subject) out.subject = subject;
+ const grow = num(o.maskGrow, 0, 256);
+ if (grow !== undefined) out.maskGrow = grow;
+ if (o.anchor === false) out.anchor = false;
+ const am = str(o.anchorModel, 60);
+ if (am && [...ANCHOR_IDS].includes(am)) out.anchorModel = am;
+ const description = str(o.description, CHARACTER_SWAP.maxDescriptionChars);
+ if (description) out.description = description;
+ const speech = oneOf<SwapSpeech>(o.speech, ["character", "other", "offscreen", "none"] as const);
+ if (speech) out.speech = speech;
+ const lora = oneOf<SwapLora>(o.lora, ["v1.5", "v1", "none"] as const);
+ if (lora) out.lora = lora;
+ if (o.audioGuide === false) out.audioGuide = false;
+ if (o.useMask === false) out.useMask = false;
+ const wf = num(o.windowFrames, 22, 362);
+ if (wf !== undefined) out.windowFrames = wf;
+ const hf = num(o.historyFrames, 0, 341);
+ if (hf !== undefined) out.historyFrames = hf;
+ return Object.keys(out).length ? out : undefined;
+}
+
+const ANCHOR_IDS = new Set(["gpt-image-2-5-sunburst", "nano-banana-pro", "oss-qwen-edit"]);
+
/** 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 };
+ 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" : "s", id: s.look.id });
+ 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,
+ c: s.character && cleanCharacter(s.character),
+ };
return `gj1.${toBase64Url(JSON.stringify(o))}`;
}
@@ -927,9 +1444,11 @@ export function decodeSetup(input: string): GenjutsuSetup | null {
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;
+ // Codes from before the Originals name Higgsfield's Genjutsu or the round-4 open models: the Original that replaced it.
+ const current = model && (LEGACY_MAKERS[model] ?? model);
+ if (current && getMaker(current)) out.model = current;
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.q === "string" && QUALITIES.has(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;
@@ -938,13 +1457,19 @@ export function decodeSetup(input: string): GenjutsuSetup | null {
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 === "s" && typeof l.id === "string" && soulLook(l.id)) out.look = { kind: "soul", id: soulLook(l.id)!.id };
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) } : {}) };
}
+ // Higgsfield's looks ("h") are gone: the code opens without a look.
}
const refs = files(o.r, GENJUTSU.maxReferences);
if (refs.length) out.references = refs;
+ const character = mode === "character" ? cleanCharacter(o.c) : undefined;
+ if (character) out.character = character;
return out;
}
+
+/** Hard cuts in the part, as the server and the page both say them (re-exported for the server's notes). */
+export { cutsInPart, swapLoraRef };
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index 0c7e6532..be5ac7ab 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -682,6 +682,19 @@ const open: ModelDef[] = [
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" } },
}),
+ // H3 Relay 2.0 (akatz-ai/h3-relay): Akatz Labs' newer node pack for the same Character swap, native loops instead of the
+ // pack's controller (Genjutsu's Character swap lists it as an alternative). It needs the pack installed (H3_RELAY=1).
+ o({
+ id: "oss-h3-character-swap-relay",
+ name: "H3 Character Swap · Relay 2.0",
+ vendor: "MiniMax × Akatz Labs",
+ family: "minimax-h3",
+ kind: "video",
+ tagline: "The same H3 swap on Akatz Labs' H3 Relay 2.0 nodes (native loops, no anchor frame) · 24 GB GPU with offloading, 48 GB+ advised",
+ badges: ["new"],
+ routes: [comfy("video-swap", "video-character-swap-h3-relay", "H3 Relay toolkit: SAM 3.1 subject, 124-frame windows with 18 frames of history, the clip's sound kept")],
+ options: { seed: true, resolutions: ["480p", "768p"], maxImages: 1 },
+ }),
o({
id: "oss-qwen-relight",
name: "Qwen-Image-Edit Relight",
@@ -1617,6 +1630,53 @@ const originals: ModelDef[] = [
// Wan 2.2 Lightning: 3 or 5 s, three shapes, 480p or 720p, no sound; several shots render one clip each, then join.
engineOptions: { open: { durations: [3, 5], aspectRatios: VID_AR, resolutions: ["480p", "720p"], audio: false, multiShot: CONCAT_SHOTS } },
},
+ // Fuobe Genjutsu (O5): Higgsfield's Genjutsu rebuilt on open weights, one model per mode on both engines, and Lite as the
+ // cheaper, faster tier of the same Original (src/lib/catalog/genjutsu.ts plans the pieces, masks, looks and sound).
+ original({
+ id: "fuobe-genjutsu-motion",
+ open: [comfy("motion-transfer", "wan-animate2", "Wan Animate 2: the whole selection in 81-frame fragments, the clip's fps and sound kept")],
+ tagline: "Your character performs the clip's moves · Wan Animate 2 free on your GPU (24 GB), Wan 2.2 Animate on fal",
+ options: { seed: true, resolutions: ["480p", "720p"], maxImages: 1, promptOptional: true },
+ }),
+ original({
+ id: "fuobe-genjutsu-motion-lite",
+ open: [comfy("motion-transfer", "wan-animate2", "Wan Animate 2 at 480p with 4 distilled steps")],
+ tagline: "The quick tier: 480p · Wan Animate 2 in 4 steps on your GPU, Wan 2.2 Animate turbo on fal",
+ options: { seed: true, resolutions: ["480p"], maxImages: 1, promptOptional: true },
+ }),
+ {
+ ...original({
+ id: "fuobe-genjutsu-swap",
+ open: [comfy("video-swap", "video-swap-wan-vace", "SAM 3.1 follows what you name, Wan 2.1 VACE 14B paints your first reference in; 81 frames per window")],
+ tagline: "Swap a thing, a person or an outfit for your reference · Wan VACE + SAM 3.1 free on your GPU (24 GB), or hosted on fal",
+ options: { seed: true, negativePrompt: true, resolutions: ["480p", "720p"], maxImages: 4 },
+ }),
+ engineOptions: { open: { maxImages: 1 } },
+ },
+ {
+ ...original({
+ id: "fuobe-genjutsu-swap-lite",
+ open: [comfy("video-swap", "video-swap-wan-vace", "SAM 3.1 + Wan 2.1 VACE 14B at 480p")],
+ tagline: "The quick tier: 480p · Wan VACE + SAM 3.1 on your GPU, accelerated Wan VACE on fal",
+ options: { seed: true, negativePrompt: true, resolutions: ["480p"], maxImages: 4 },
+ }),
+ engineOptions: { open: { maxImages: 1 } },
+ },
+ original({
+ id: "fuobe-genjutsu-restyle",
+ open: [comfy("v2v", "video-restyle-wan22-fun-vace", "the restyled first frame, then every frame with depth; 5 s segments at 16 fps")],
+ tagline: "Every frame takes a Fuobe look, motion and framing kept · Wan 2.2 Fun VACE free on your GPU (24 GB), or hosted on fal",
+ options: { seed: true, negativePrompt: true, resolutions: ["480p", "720p"], maxImages: 4 },
+ }),
+ // Character swap (Openjutsu, Akatz Labs' H3 Character Swap): MiniMax H3 with the Character Swap LoRA. On your GPU the
+ // h3_character_swap graph finds the person with SAM 3.1 and regenerates only them in 124-frame windows, keeping the
+ // clip's own sound; on fal, H3 reference-to-video with the same LoRA (no mask), the clip's sound put back.
+ original({
+ id: "fuobe-character-swap",
+ open: [comfy("video-swap", "video-character-swap-h3", "SAM 3.1 picks the person on the part's first frame; H3 regenerates them in 124-frame windows, 18 frames of history")],
+ tagline: "The person in your clip becomes your character · MiniMax H3 free on your GPU (48 GB+ advised), or hosted on fal",
+ options: { seed: true, resolutions: ["480p", "768p"], maxImages: 2 },
+ }),
];
/** Tools that run entirely in the browser; recorded in the library like any other result. */
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index 738cb5c5..3e95b3d9 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -835,6 +835,13 @@ export interface GenerationRequest {
chain?: ChainSlot[];
/** Server-set when the runner filled the chain slots from the earlier steps' outputs (a retry takes them out again: unfilledRequest). */
chainFilled?: boolean;
+ /**
+ * Server-set when the runner left out optional chain slots whose steps failed (ChainSlot.optional): their indexes, and
+ * the prompt the request had before the fallback replaced it (a retry puts it back).
+ */
+ chainSkipped?: { slots: number[]; prompt?: string };
+ /** Server-set: what changed while the job ran (an optional input left out), said on the result and carried down the chain. */
+ notice?: string;
/**
* A step only worth making for the steps after it (a per-frame render's frame edits and clips): while it still
* waits for its inputs (nothing spent yet), the runner cancels it once every step that would use it has failed
@@ -891,6 +898,12 @@ export interface ChainSlot {
* frames is not).
*/
of?: number;
+ /**
+ * An input the step can do without (Genjutsu's anchor first frame): when the step it comes from fails or is canceled,
+ * this step runs without it instead of failing. `prompt` then replaces the request's prompt (the words that named the
+ * missing input go), and `notice` is said on the result and on the steps after it.
+ */
+ optional?: { prompt?: string; notice: string };
}
/** How many outputs a planned list (ChainSlot.of) may be short of before the steps reading it fail. */
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 593fcef3..dd222159 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -43,6 +43,7 @@ import { enhancePrompt, enhanceSoulWords } from "./enhance";
import { setResolver, watchGenerations, type LiveEvent } from "./live";
import { provider } from "./providers";
import { comfyLoraFiles, probeComfy } from "./providers/comfyui";
+import { graphLoras } from "@/lib/catalog/character-swap";
import { ensureLorasOnComfy, prepareCloudLoras, withoutUnreachableCivitai } from "./loras";
import { llmBackends, llmMissing, llmUsesClaude, probeOllama } from "./providers/llm";
import type { PollContext, PollResult, RemoteOutput } from "./providers/types";
@@ -756,9 +757,13 @@ export function withChainInputs(req: GenerationRequest, urls: string[]): Generat
* "prompt" slot can't be told from the prompt, so it stays.
*/
export function unfilledRequest(req: GenerationRequest, deps: number): GenerationRequest {
- const { chainFilled, ...rest } = req;
- if (!chainFilled) return rest;
- const slots = slotsFor(rest, deps);
+ const { chainFilled, chainSkipped, ...rest } = req;
+ // A fallback's notice belongs to the run that fell back, not to a retry.
+ delete rest.notice;
+ if (!chainFilled) return chainSkipped ? { ...rest, ...(chainSkipped.prompt !== undefined ? { prompt: chainSkipped.prompt } : {}) } : rest;
+ // Optional slots left out filled nothing; the fallback's prompt goes back to the one planned.
+ if (chainSkipped?.prompt !== undefined) rest.prompt = chainSkipped.prompt;
+ const slots = filledSlots({ ...rest, chainSkipped }, deps);
const inputs = { ...rest.inputs };
for (const k of ["images", "videos", "audios"] as const) {
const count = (pos: "first" | "last") => slots.filter((s) => s.slot === k && (s.position ?? "last") === pos).length;
@@ -849,26 +854,57 @@ function dropUnused(ids: string[]): void {
}
}
+/**
+ * A step with optional inputs whose steps failed (ChainSlot.optional): its chain without those slots, the fallback's
+ * prompt and notice, and what was left out (so a retry can put the request back as it was: unfilledRequest).
+ */
+export function withoutSkipped(req: GenerationRequest, slots: ChainSlot[], skipped: number[]): GenerationRequest {
+ const left = skipped.map((i) => slots[i]);
+ const prompt = left.map((s) => s.optional?.prompt).find((p) => p !== undefined);
+ const notice = [req.notice, ...left.map((s) => s.optional?.notice)].filter(Boolean).join(" · ");
+ return {
+ ...req,
+ chainSkipped: { slots: skipped, ...(prompt !== undefined && req.prompt !== undefined ? { prompt: req.prompt } : {}) },
+ ...(prompt !== undefined ? { prompt } : {}),
+ ...(notice ? { notice } : {}),
+ };
+}
+
+/** The chain slots a step fills: its own, less the optional ones left out (chainSkipped). */
+const filledSlots = (req: GenerationRequest, n: number): ChainSlot[] => slotsFor(req, n).filter((_, i) => !req.chainSkipped?.slots.includes(i));
+
/** Launch dependent jobs whose inputs finished; fail the ones whose inputs failed. Never waits for an upload. */
async function advanceDependents(): Promise<void> {
const rows = db().prepare(READY_DEPENDENTS).all(50 + submitting().size) as Row[];
for (const r of rows) {
if (submitting().has(r.id)) continue;
- const request = JSON.parse(r.request_json) as GenerationRequest;
- const ids = depIds(r.depends_on);
- const slots = slotsFor(request, ids.length);
- const deps = ids.map((id) => db().prepare("SELECT status, provider, outputs_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json"> | undefined);
- const earlier = request.frame ? "The previous frame" : "An earlier step";
+ const stored = JSON.parse(r.request_json) as GenerationRequest;
+ const allIds = depIds(r.depends_on);
+ const allSlots = slotsFor(stored, allIds.length);
+ const allDeps = allIds.map(
+ (id) => db().prepare("SELECT status, provider, outputs_json, request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json" | "request_json"> | undefined,
+ );
+ const earlier = stored.frame ? "The previous frame" : "An earlier step";
const fail = (error: string) => {
update(r.id, { status: "failed", error, message: null, completed_at: Date.now() });
// Steps waiting only to feed this one (the other lanes of a per-frame render) are dropped before they are paid for.
- dropUnused(ids);
+ dropUnused(allIds);
};
- if (deps.some((d) => !d || d.status === "failed" || d.status === "canceled")) {
- fail(waitedOnFailure(!!request.frame));
+ const broken = (d: (typeof allDeps)[number]) => !d || d.status === "failed" || d.status === "canceled";
+ // An optional input whose step failed is left out (Genjutsu's anchor frame): the step runs without it.
+ const skipped = allSlots.flatMap((s, i) => (s.optional && broken(allDeps[i]) ? [i] : []));
+ if (allDeps.some((d, i) => broken(d) && !skipped.includes(i))) {
+ fail(waitedOnFailure(!!stored.frame));
continue;
}
+ const keep = (_: unknown, i: number) => !skipped.includes(i);
+ const deps = allDeps.filter(keep);
+ const slots = allSlots.filter(keep);
if (deps.some((d) => d!.status !== "succeeded")) continue;
+ const request = skipped.length ? withoutSkipped(stored, allSlots, skipped) : stored;
+ // What changed upstream (an earlier fallback) is said on this step too, down to the finished result.
+ const notices = [request.notice, ...deps.map((d) => (JSON.parse(d!.request_json) as GenerationRequest).notice)].filter((x): x is string => !!x);
+ if (notices.length) request.notice = [...new Set(notices)].join(" · ");
const outputs = deps.map((d) => JSON.parse(d!.outputs_json) as OutputFile[]);
const short = slots.map((s, i) => listShortfall(outputs[i], s)).find(Boolean);
if (short) {
@@ -889,7 +925,9 @@ async function advanceDependents(): Promise<void> {
const model = getModel(request.modelId);
if (model?.routes.some((x) => x.provider === "comfyui")) await probeComfy();
if (model?.routes.some((x) => x.provider === "llm")) await probeOllama();
- const original: GenerationRequest = { ...withChainInputs(request, values as string[]), chainFilled: true };
+ // Filled with the slots that have an input; stored with its whole chain (and what was skipped) for a retry.
+ const filled = withChainInputs({ ...request, chain: slots }, values as string[]);
+ const original: GenerationRequest = { ...filled, chain: request.chain, chainFilled: true };
const prepared = prepare(original);
const mode = chainMode(prepared, deps as Pick<Row, "provider">[]);
if (mode.error) throw new Error(mode.error);
@@ -1006,8 +1044,9 @@ async function submit(
// file mirrored once to the provider's storage (the civitai key never leaves this server).
if (input.loras?.length && (providerId === "fal" || providerId === "replicate")) {
input.loras = await prepareCloudLoras(input.loras, providerId, (data, name) => adapter.prepareFile(data, "application/octet-stream", name, route), (message) => update(id, { message }));
- } else if (input.loras?.length && providerId === "comfyui") {
- await ensureLorasOnComfy(input.loras, await comfyLoraFiles(route), (message) => update(id, { message }));
+ } else if (providerId === "comfyui" && (input.loras?.length || graphLoras(route.endpoint, input.extra).length)) {
+ // A graph that loads its own LoRAs (Genjutsu's Character swap: the Turbo and swap LoRAs) gets them downloaded too.
+ await ensureLorasOnComfy([...(input.loras ?? []), ...graphLoras(route.endpoint, input.extra)], await comfyLoraFiles(route), (message) => update(id, { message }));
}
const res = await adapter.submit({ generationId: id, model: plan.model, route, input });
const now = Date.now();
diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.ts
index cf6e4f2c..389b2e35 100644
--- a/src/server/genjutsu.ts
+++ b/src/server/genjutsu.ts
@@ -1,12 +1,14 @@
import "server-only";
import { z } from "zod";
import { getModel } from "@/lib/catalog";
+import { onEngine } from "@/lib/catalog/engines";
+import { ANCHOR_MODELS, anchorModel, CHARACTER_GPU, CHARACTER_LIMITS, CHARACTER_SWAP, characterLicenceLine, cutWarning, h3Windows, type CharacterOptions } from "@/lib/catalog/character-swap";
import {
chooseMaker,
+ cutsInPart,
GENJUTSU,
genjutsuProblem,
genjutsuTitle,
- getMaker,
makersFor,
MODE_TARGETS,
planGenjutsu,
@@ -14,12 +16,14 @@ import {
qualityFor,
makerStepUsd,
resolutionWords,
+ SOURCE_LABELS,
type GenjutsuLook,
type GenjutsuMode,
type GenjutsuPlanInput,
type GenjutsuTarget,
type GenjutsuTier,
type Maker,
+ type MakerSource,
} from "@/lib/catalog/genjutsu";
import { MASK_TRACKER, REMOVE_TOOLS, scalePoints, wholeClip, type RemoveRange, type RemoveSource } from "@/lib/catalog/remove-object";
import { planSegments, type PlanStep } from "@/lib/catalog/shorts";
@@ -32,10 +36,10 @@ import { engineMode } from "./settings";
import { probeSource, ShortsError } from "./shorts";
/**
- * Genjutsu (/genjutsu): plans, prices and starts a Motion transfer, Object swap, Restyle or Insert
+ * Fuobe Genjutsu (/genjutsu): plans, prices and starts a Motion transfer, Character swap, Object swap, Restyle or Insert
* (src/lib/catalog/genjutsu.ts) as one pipeline of ordinary generations: feature "genjutsu" for the finished video,
- * "genjutsu-step" for the cuts, tracks, pieces and joins. No table of its own: the page's history is a feed, and a
- * setup travels as a code (encodeSetup), not a row.
+ * "genjutsu-step" for the cuts, tracks, anchor frames, pieces and joins. No table of its own: the page's history is a
+ * feed, and a setup travels as a code (encodeSetup), not a row. No Higgsfield model runs here.
*/
export { ShortsError as GenjutsuError };
@@ -43,14 +47,15 @@ export { ShortsError as GenjutsuError };
export interface GenjutsuBody {
engine: Engine;
mode: GenjutsuMode;
- /** The model picked (defaults per engine, mode and key). */
+ /** The model picked (defaults per engine and mode: the Fuobe Original). */
modelId?: string;
- /** Genjutsu Lite ("standard") or the full model ("high"). */
+ /** Lite ("standard") or the full Original ("high"). */
tier?: GenjutsuTier;
quality?: string;
target?: GenjutsuTarget;
/** Object swap: what goes. */
subject?: string;
+ /** Guidance (Character swap: your direction). */
prompt?: string;
points?: PixelPoint[];
/** The picture the points or the paint were made on (the first frame the browser showed). */
@@ -61,6 +66,10 @@ export interface GenjutsuBody {
source: { url: string; name?: string; duration?: number; fps?: number; width?: number; height?: number; hasAudio?: boolean };
range?: RemoveRange;
seed?: number;
+ /** Character swap's settings. */
+ character?: CharacterOptions;
+ /** Hard cuts the browser found in the clip (seconds), for the "one continuous shot" warning. */
+ cuts?: number[];
}
const fileUrl = z.string().startsWith("/api/files/").max(500);
@@ -68,17 +77,33 @@ const seconds = z.number().finite().min(0).max(3600);
const point = z.object({ x: z.number().finite().min(0).max(20000), y: z.number().finite().min(0).max(20000), label: z.enum(["positive", "negative"]).optional() });
const look = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("preset"), id: z.string().max(80) }),
- z.object({ kind: z.literal("higgsfield"), id: z.string().max(80), name: z.string().max(120).optional() }),
+ z.object({ kind: z.literal("soul"), id: z.string().max(80) }),
z.object({ kind: z.literal("custom"), images: z.array(fileUrl).max(GENJUTSU.maxLookImages), words: z.string().max(300).optional() }),
]);
+const character = z.object({
+ who: z.enum(["largest", "leftmost", "rightmost", "index"]).optional(),
+ index: z.number().int().min(0).max(CHARACTER_SWAP.maxPeople - 1).optional(),
+ subject: z.string().max(120).optional(),
+ maskGrow: z.number().int().min(0).max(256).optional(),
+ anchor: z.boolean().optional(),
+ anchorModel: z.enum(["gpt-image-2-5-sunburst", "nano-banana-pro", "oss-qwen-edit"]).optional(),
+ description: z.string().max(CHARACTER_SWAP.maxDescriptionChars).optional(),
+ speech: z.enum(["character", "other", "offscreen", "none"]).optional(),
+ dialogue: z.string().max(2000).optional(),
+ lora: z.enum(["v1.5", "v1", "none"]).optional(),
+ audioGuide: z.boolean().optional(),
+ useMask: z.boolean().optional(),
+ windowFrames: z.number().int().min(22).max(362).optional(),
+ historyFrames: z.number().int().min(0).max(341).optional(),
+});
/** The body of /api/genjutsu (and /estimate). */
export const GenjutsuBodySchema = z.object({
engine: z.enum(["cloud", "open"]),
- mode: z.enum(["motion", "swap", "restyle", "insert"]),
+ mode: z.enum(["motion", "character", "swap", "restyle", "insert"]),
modelId: z.string().max(80).optional(),
tier: z.enum(["standard", "high"]).optional(),
- quality: z.enum(["480p", "720p", "1080p"]).optional(),
+ quality: z.enum(["480p", "720p", "768p", "1080p"]).optional(),
target: z.enum(["type", "click", "paint"]).optional(),
subject: z.string().max(300).optional(),
prompt: z.string().max(GENJUTSU.maxPromptChars).optional(),
@@ -98,6 +123,8 @@ export const GenjutsuBodySchema = z.object({
}),
range: z.object({ start: seconds, end: seconds }).optional(),
seed: z.number().int().min(0).max(2 ** 48).optional(),
+ character: character.optional(),
+ cuts: z.array(seconds).max(200).optional(),
/** A client nonce for one submit: a repeat gets the first answer (see once()). */
requestId: z.string().trim().min(8).max(64).optional(),
});
@@ -116,9 +143,6 @@ const mustMatchMode = (engine: Engine) => {
}
};
-/** A Higgsfield key is set (Genjutsu and Genjutsu Lite run on it). */
-export const higgsfieldReady = () => provider("higgsfield").isConfigured();
-
interface Planned {
input: GenjutsuPlanInput;
maker: Maker;
@@ -127,7 +151,7 @@ interface Planned {
async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<Planned> {
mustMatchMode(body.engine);
- const picked = chooseMaker({ engine: body.engine, mode: body.mode, target: body.target, tier: body.tier, look: body.look, modelId: body.modelId, higgsfield: higgsfieldReady() });
+ const picked = chooseMaker({ engine: body.engine, mode: body.mode, target: body.target, tier: body.tier, look: body.look, modelId: body.modelId });
if ("problem" in picked) throw new ShortsError(picked.problem, 422);
const maker = picked.maker;
// The header's facts win over what the browser read (the estimate runs before the upload is read).
@@ -141,24 +165,26 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<
// Sound we couldn't read counts as none (putting it back would fail after the work was paid for).
hasAudio: opts.probe ? (info.hasAudio ?? false) : (body.source.hasAudio ?? false),
};
- const range = body.range ?? (source.duration ? { start: 0, end: Math.min(source.duration, GENJUTSU.maxSeconds) } : null);
+ // Character swap's part defaults to the first 15 s (Openjutsu's Length); the other modes take up to 30 s.
+ const longest = body.mode === "character" ? CHARACTER_SWAP.maxSeconds : GENJUTSU.maxSeconds;
+ const range = body.range ?? (source.duration ? { start: 0, end: Math.min(source.duration, longest) } : null);
if (!range) throw new ShortsError("Reading the clip… try again in a moment");
const target = MODE_TARGETS[body.mode].length ? (body.target ?? MODE_TARGETS[body.mode][0]) : undefined;
const references = body.references ?? [];
const clicks = (body.points ?? []).filter((p) => p.label !== "negative").length;
- const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look });
+ const problem = genjutsuProblem({ mode: body.mode, maker, source, range, references: references.length, target, subject: body.subject, prompt: body.prompt, points: clicks, mask: !!body.mask, look: body.look, seed: body.seed });
if (problem) throw new ShortsError(problem, 422);
- // Clicks on the first frame, in the clip's pixels; paint over several hosted VACE pieces is followed from its deepest points.
+ // Clicks on the first frame, in the clip's pixels; paint is followed from its deepest points (SAM 3.1 on fal).
let points: PixelPoint[] | undefined;
const size = source.width && source.height ? { width: source.width, height: source.height } : null;
if (target === "click") points = body.frame && size ? scalePoints(body.points!.slice(0, GENJUTSU.maxPoints), body.frame, size) : body.points;
const pieces = planMakerPieces(maker, source, range);
- // Restyle on Fuobe's looks runs in the Shorts chain's segments.
- const n = (body.mode === "restyle" && maker.looks === "fuobe" ? planSegments(range, maker.engine).length : pieces.length) || 1;
- if (target === "paint" && maker.engine === "cloud" && body.mode === "swap" && n > 1) {
- points = opts.probe ? await pointsFromPaint(body.mask!, source, "Paint over what to swap first") : [{ x: 1, y: 1, label: "positive" }];
- }
+ // Restyle on Fuobe's looks runs in the Shorts chain's segments (the open Original and partners).
+ const shortsChain = body.mode === "restyle" && maker.looks === "fuobe" && !(maker.engine === "cloud" && maker.source === "original");
+ const n = (shortsChain ? planSegments(range, maker.engine).length : pieces.length) || 1;
+ const tracksPaint = maker.engine === "cloud" && body.mode === "swap" && target === "paint" && (maker.source === "original" || n > 1);
+ if (tracksPaint) points = opts.probe ? await pointsFromPaint(body.mask!, source, "Paint over what to swap first") : [{ x: 1, y: 1, label: "positive" }];
const notes = notesFor(body, maker, source, range, n, references.length);
const name = (body.source.name ?? "").replace(/\.[a-z0-9]{2,4}$/i, "").trim().slice(0, 40);
@@ -173,7 +199,7 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<
title: name ? `${title} · ${name}` : title,
source,
range,
- quality: body.quality ?? GENJUTSU.defaultQuality,
+ quality: body.quality ?? (body.mode === "character" ? CHARACTER_SWAP.defaultQuality : GENJUTSU.defaultQuality),
references,
target,
subject: body.subject?.trim() || undefined,
@@ -182,6 +208,7 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean }): Promise<
mask: target === "paint" ? body.mask : undefined,
look: body.look,
...(body.seed !== undefined ? { seed: body.seed } : {}),
+ ...(body.mode === "character" ? { character: body.character ?? {} } : {}),
},
};
}
@@ -191,31 +218,54 @@ function notesFor(body: GenjutsuBody, m: Maker, source: RemoveSource, range: Rem
const name = getModel(m.id)?.name ?? m.label;
const fps = source.fps ?? 30;
const fuobeLook = body.mode === "restyle" && m.looks === "fuobe";
- if (n > 1) {
+ const len = range.end - range.start;
+ if (body.mode === "character" && m.h3) {
+ const c = body.character ?? {};
+ if (m.engine === "open") {
+ const windows = h3Windows(len, c.windowFrames);
+ notes.push(`MiniMax H3 swaps it in ${windows} window${windows > 1 ? "s" : ""} of ${c.windowFrames ?? CHARACTER_SWAP.window} frames at 24 fps, each continuing the one before; the clip's sound stays`);
+ } else if (n > 1) notes.push(`fal's H3 takes up to 15 s a call: the part runs as ${n} pieces, joined with the clip's own sound. Each piece starts fresh (no history between them)`);
+ if (len > CHARACTER_SWAP.maxSeconds + 0.05) notes.push("Past 15 s is beyond what H3 was trained on: quality there is unverified");
+ if (m.h3.anchor && c.anchor !== false) {
+ const am = anchorModel(m.engine, c.anchorModel);
+ notes.push(`${am.label} first puts your character into the part's first frame${m.engine === "cloud" && n > 1 ? " (one per piece)" : ""}; if that fails the swap runs without it`);
+ } else if (!m.h3.anchor) notes.push(`${name} runs without an anchor frame`);
+ if (m.engine === "cloud") notes.push("On fal, H3 has no mask: who to swap is said in words, and the whole frame is regenerated around them");
+ if (body.points?.length && body.quality === "480p" && m.engine === "open") notes.push("Clicks are placed in H3's 480p frame by estimate: if the wrong person is picked, choose them by position instead");
+ const warn = cutWarning(cutsInPart(body.cuts, range));
+ if (warn) notes.push(warn);
+ notes.push(characterLicenceLine(m.engine, m.id));
+ } else if (body.mode === "character") {
+ notes.push(m.id === "h3-max-recast" ? characterLicenceLine(m.engine, m.id) : `${SOURCE_LABELS[m.source]}: ${m.note}`);
+ const warn = m.id === "h3-max-recast" ? null : cutWarning(cutsInPart(body.cuts, range));
+ if (warn) notes.push(warn);
+ }
+ if (n > 1 && body.mode !== "character") {
if (m.engine === "open" && m.window) {
notes.push(`${name} works on ${m.window.cap} frames at a time (${(m.window.cap / fps).toFixed(1)} s of this clip): it runs as ${n} windows, joined with the clip's own sound. Seams between windows aren't tested on a GPU yet`);
} else if (fuobeLook) {
- notes.push(`${name} restyles ${m.engine === "open" ? "5 s" : "up to 10 s"} at a time: the clip runs as ${n} segments, joined with its own sound`);
+ notes.push(`${name} restyles ${m.engine === "open" ? "5 s" : m.window ? `${m.window.cap} frames (${(m.window.cap / fps).toFixed(1)} s of this clip)` : "up to 10 s"} at a time: the clip runs as ${n} segments, joined with its own sound`);
} else {
const limit = m.window ? `${m.window.cap} frames (${(m.window.cap / fps).toFixed(1)} s of this clip)` : `${m.maxSeconds} s`;
notes.push(`${name} takes up to ${limit} a call: the clip runs as ${n} pieces, joined with its own sound. Seams between pieces aren't tested yet`);
}
}
if (body.mode !== "restyle" && refs > m.refs.max) notes.push(m.refs.max === 1 ? `${name} uses your first reference image` : `${name} takes ${m.refs.max} references — your first ${m.refs.max} go`);
- if (fuobeLook && refs) notes.push("Character references go with Higgsfield's looks (Genjutsu Restyle); this look restyles what is filmed");
+ if (fuobeLook && refs) notes.push("Restyle changes the whole shot: character references aren't used — try Motion transfer or Character swap for a character");
if (fuobeLook && body.look?.kind === "custom" && m.readsLookImages && body.look.images.length > m.readsLookImages) notes.push(`${name} reads ${m.readsLookImages} of your look's images`);
- if (body.mode === "restyle" && m.looks === "higgsfield" && refs > m.refs.max) notes.push(`Genjutsu Restyle takes ${m.refs.max} character references — your first ${m.refs.max} go`);
- const quality = body.quality ?? GENJUTSU.defaultQuality;
+ if (fuobeLook && body.look?.kind === "soul" && m.source === "original") notes.push("The Soul look's LoRAs restyle the first frame (Fuobe Soul's edit); every frame then follows it");
+ const quality = body.quality ?? (body.mode === "character" ? CHARACTER_SWAP.defaultQuality : GENJUTSU.defaultQuality);
const res = resolutionWords(m, quality);
if (res) notes.push(`${name} ${res}${m.qualities ? "" : " (it has no resolution setting)"}`);
if (m.id === "wan-22-vace-inpaint") {
notes.push(body.mode === "insert" ? "The spot stays where you painted it for the whole shot — best with a still or slow camera" : "Only the area you marked changes; SAM 3.1 follows it through the selection when it runs as pieces or you clicked");
}
+ if (m.source === "original" && body.mode === "swap" && m.engine === "cloud") notes.push("SAM 3.1 follows what you named, clicked or painted through the selection; Wan VACE paints your reference into its mask");
+ if (m.billFps && m.engine === "cloud" && source.fps && source.fps > m.billFps + 0.5) notes.push(`fal bills this clip's ${Math.round(source.fps)} fps as ${(source.fps / m.billFps).toFixed(1)}× its length (video seconds at ${m.billFps} fps)`);
if (m.id === "oss-vace-insert") notes.push("The spot stays where you painted it for the whole shot — best with a still or slow camera");
- if (m.people) notes.push("P-Video Replace swaps the person on camera — for objects, pick Genjutsu or Kling O3");
- if (m.higgsfield) notes.push(`${m.tier === "standard" ? "Genjutsu Lite" : "Genjutsu"} is at 50% off on Higgsfield right now (2026-10-22) — the price here is the list price`);
- if (m.engine === "open") {
- if (m.id === "oss-wan22-animate") notes.push("Wan Animate 2 needs a 24 GB GPU · Apache-2.0");
+ if (m.people && body.mode === "swap") notes.push(`${name} swaps the person on camera — for objects, pick Fuobe Genjutsu or Kling O3`);
+ if (m.engine === "open" && body.mode !== "character") {
+ if (m.modes.includes("motion")) notes.push("Wan Animate 2 needs a 24 GB GPU · Apache-2.0");
else if (m.window) notes.push(`Wan 2.1 VACE 14B needs a 24 GB GPU · Apache-2.0${body.mode === "swap" ? " (SAM 3.1: Meta's SAM License)" : ""}`);
}
if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");
@@ -230,12 +280,18 @@ const HELPER_WORDS: Record<string, string> = {
[REMOVE_TOOLS.cloud.join]: "joining the pieces",
[REMOVE_TOOLS.cloud.mux]: "putting the sound back",
[MASK_TRACKER]: "following what you marked",
- "extract-frame": "following what you marked",
+ "extract-frame": "taking the first frame",
"scale-video": "fitting the clip",
+ "gpt-image-2-5-sunburst": "the first frame with your character",
+ "nano-banana-pro": "the first frame with your character",
};
-/** The providers a step's model runs its operation on (any one of them will do). */
-const providersOf = (s: PlanStep): ProviderId[] => [...new Set((getModel(s.request.modelId)?.routes ?? []).filter((r) => !s.request.op || r.op === s.request.op).map((r) => r.provider))];
+/** The providers a step's model runs its operation on, on the step's engine (any one of them will do). */
+const providersOf = (s: PlanStep): ProviderId[] => {
+ const m = getModel(s.request.modelId);
+ const routes = m ? (s.request.engine ? onEngine(m, s.request.engine) : m).routes : [];
+ return [...new Set(routes.filter((r) => !s.request.op || r.op === s.request.op).map((r) => r.provider))];
+};
const listWords = (xs: string[]) => (xs.length < 2 ? (xs[0] ?? "") : `${xs.slice(0, -1).join(", ")} and ${xs[xs.length - 1]}`);
const cap = (t: string) => (t ? t[0].toUpperCase() + t.slice(1) : t);
@@ -249,8 +305,8 @@ interface StepMode {
/**
* A run is all real or all a demo (chainMode in src/server/generations.ts): a real step after a demo one runs as a demo
* too, a demo step after a real one fails, both after the paid steps were made. So when only some of the steps have a
- * provider — a Higgsfield key without fal for the cuts and joins, or fal without Higgsfield for Genjutsu — say which key
- * is missing (and the way around it) before anything is paid for.
+ * provider — Replicate's P-Video without fal for the cuts and joins, say — name the missing key (and the way around
+ * it) before anything is paid for.
*/
function mixProblem(modes: StepMode[], cannot: boolean, input: GenjutsuPlanInput): string | null {
const missing = modes.filter((x) => x.demo);
@@ -266,46 +322,35 @@ function mixProblem(modes: StepMode[], cannot: boolean, input: GenjutsuPlanInput
if (own.length) parts.push(`${makerName} runs on ${label(ownIds)}`);
if (helpers.length) {
const jobs = [...new Set(helpers.map((x) => HELPER_WORDS[x.step.request.modelId] ?? getModel(x.step.request.modelId)?.name ?? x.step.request.modelId))];
- parts.push(`${own.length ? listWords(jobs) : cap(listWords(jobs))} ${jobs.length > 1 || own.length ? "run" : "runs"} on ${label(helperIds)}`);
+ parts.push(`${own.length ? listWords(jobs) : cap(listWords(jobs))} ${jobs.length > 1 ? "run" : "runs"} on ${label(helperIds)}`);
}
// The fewest keys that cover it: one provider both need, else one for each.
const both = ownIds.filter((id) => helperIds.includes(id));
const key = !own.length ? `a ${label(helperIds)} key` : !helpers.length ? `a ${label(ownIds)} key` : both.length ? `a ${label(both.slice(0, 1))} key` : `a ${label(helperIds)} key and a ${label(ownIds)} key`;
- const around = own.length ? otherModel(input) : oneCall(input);
+ const around = own.length ? otherModel(input) : undefined;
return `${parts.join(", and ")} — add ${key} in Settings → API keys${around ? `, or ${around}` : ""}`;
}
-/** Another model for the same job that doesn't need Higgsfield (the way around a missing Higgsfield key). */
+/** Another model for the same job that runs with the keys set now (the way around a missing key). */
function otherModel(input: GenjutsuPlanInput): string | undefined {
- const other = makersFor(input.engine, input.mode, input.target, input.look).find((x) => x.id !== input.maker.id && !x.higgsfield);
+ const runs = (id: string) => {
+ const m = getModel(id);
+ return !!m && onEngine(m, input.engine).routes.some((r) => provider(r.provider).isConfigured());
+ };
+ const other = makersFor(input.engine, input.mode, input.target).find((x) => x.id !== input.maker.id && x.pair !== input.maker.id && runs(x.id));
return other ? `pick ${other.label}` : undefined;
}
-/** How a Higgsfield model runs without fal's cuts and joins: the whole clip, in one call. */
-function oneCall(input: GenjutsuPlanInput): string | undefined {
- const m = input.maker;
- if (!m.higgsfield || !m.maxSeconds) return undefined;
- const high = m.tier === "standard" && m.pair ? getMaker(m.pair) : undefined;
- const d = input.source.duration;
- const len = input.range.end - input.range.start;
- const fits = (t: number | undefined, s: number | undefined) => t !== undefined && s !== undefined && t <= s + 0.05;
- if (!wholeClip(input.range, d)) {
- if (fits(d, m.maxSeconds)) return "use the whole clip";
- if (high && fits(d, high.maxSeconds)) return `use the whole clip with Quality: High (up to ${high.maxSeconds} s in one call)`;
- return `add a clip of ${high?.maxSeconds ?? m.maxSeconds} s or less and use all of it`;
- }
- if (high && fits(len, high.maxSeconds)) return `pick Quality: High (up to ${high.maxSeconds} s in one call)`;
- return undefined;
-}
-
/** Whether a step's model has no route it could run on now (demo mode off: it would refuse). */
const unrunnable = (s: PlanStep) => !providersOf(s).some((id) => provider(id).isConfigured());
/** What the steps cost together (null when a price is unknown) and whether they would run as a demo. */
-function price(steps: PlanStep[], input: GenjutsuPlanInput): { costUsd: number | null; demo: boolean; providers: ProviderId[] } {
+function price(steps: PlanStep[], input: GenjutsuPlanInput): { costUsd: number | null; demo: boolean; providers: ProviderId[]; tokenBilled: string[] } {
let cost: number | null = 0;
const modes: StepMode[] = [];
const providers = new Set<ProviderId>();
+ // Steps fal bills by tokens (the Sunburst first frame): left out of the total, and named.
+ const tokenBilled = new Set<string>();
let cannot = false;
for (const s of steps) {
let p: ReturnType<typeof previewChained>;
@@ -322,24 +367,30 @@ function price(steps: PlanStep[], input: GenjutsuPlanInput): { costUsd: number |
}
modes.push({ step: s, demo: p.demo });
providers.add(p.providerId);
- // Genjutsu's tiers and Kling O3's edit price aren't in the catalog per resolution: the planner's table.
+ // Kling O3's edit price isn't the catalog's: the planner's table.
const own = p.demo ? null : makerStepUsd(s.request.modelId, s.request.params);
const usd = own ?? p.costUsd;
+ const tokens = usd === null ? ANCHOR_MODELS.cloud.find((m) => m.id === s.request.modelId && m.tokens) : undefined;
+ if (tokens) {
+ tokenBilled.add(`${tokens.label}'s first frame is billed by tokens (${tokens.tokens}) and isn't in the price`);
+ continue;
+ }
cost = cost === null || usd === null ? null : cost + usd;
}
const problem = mixProblem(modes, cannot, input);
if (problem) throw new ShortsError(problem, 422);
- return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo: modes.some((x) => x.demo), providers: [...providers] };
+ return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo: modes.some((x) => x.demo), providers: [...providers], tokenBilled: [...tokenBilled] };
}
export interface GenjutsuEstimate {
costUsd: number | null;
demo: boolean;
- /** Where the steps run ("mock" for demo steps): the evaluation harness refuses a route through Higgsfield's API. */
+ /** Where the steps run ("mock" for demo steps). */
providers: ProviderId[];
- /** The model that runs (the default, or the one picked) and its tier. */
+ /** The model that runs (the default, or the one picked), its tier and where it comes from. */
modelId: string;
modelName: string;
+ source: MakerSource;
tier?: GenjutsuTier;
/** The resolution it is asked for (none: it keeps the clip's size). */
quality?: string;
@@ -347,8 +398,10 @@ export interface GenjutsuEstimate {
seconds: number;
steps: number;
notes: string[];
- /** A Higgsfield key is set. */
- higgsfield: boolean;
+ /** Character swap: anchor frames made, the limits, and the GPU the open route was tested on. */
+ anchors?: number;
+ limits?: string[];
+ gpu?: { weightsGb: number; tested: string; advice: string; speed: string };
}
export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEstimate> {
@@ -359,17 +412,22 @@ export async function estimateGenjutsu(body: GenjutsuBody): Promise<GenjutsuEsti
} catch (e) {
throw new ShortsError((e as Error).message, 422);
}
+ const character = body.mode === "character";
+ const { tokenBilled, ...cost } = price(plan.steps, input);
return {
- ...price(plan.steps, input),
+ ...cost,
modelId: maker.id,
modelName: getModel(maker.id)?.name ?? maker.label,
+ source: maker.source,
...(maker.tier ? { tier: maker.tier } : {}),
...(qualityFor(maker, input.quality) ? { quality: qualityFor(maker, input.quality) } : {}),
pieces: plan.pieces,
seconds: Math.round((input.range.end - input.range.start) * 100) / 100,
steps: plan.steps.length,
- notes,
- higgsfield: higgsfieldReady(),
+ notes: cost.demo ? notes : [...notes, ...tokenBilled],
+ ...(plan.anchors !== undefined ? { anchors: plan.anchors } : {}),
+ ...(character ? { limits: [...CHARACTER_LIMITS] } : {}),
+ ...(character && maker.h3 && maker.engine === "open" ? { gpu: { ...CHARACTER_GPU } } : {}),
};
}
diff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.ts
index 9b29d95d..c430ee22 100644
--- a/src/server/providers/comfyui.ts
+++ b/src/server/providers/comfyui.ts
@@ -42,7 +42,8 @@ import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";
import { exportValues, exrWorkflow, framesPerPass, hdrColorSpace, upscaleShortSide, wholeClipProblem, wholeClipTool } from "@/lib/av/video-finish";
import { guessKind } from "@/lib/catalog/payload";
import { loraByFile, needsToken } from "@/lib/catalog/loras";
-import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, swapTarget } from "@/lib/catalog/genjutsu";
+import { packResolution, samCoords, SWAP_LORAS, windowFrames as h3WindowFrames, historyFrames as h3HistoryFrames } from "@/lib/catalog/character-swap";
+import { getMaker, makerPrompt, OPEN_TARGET_PROBLEM, ORIGINALS, swapTarget } from "@/lib/catalog/genjutsu";
import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, targetPhrase } from "@/lib/catalog/remove-object";
import type { GenInput, MediaKind, ModelRoute, Operation } from "@/lib/catalog/types";
import { imageSize } from "@/lib/image-size";
@@ -906,13 +907,36 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
if (b.prompt) values.prompt = REMOVE_SCENE;
}
+ // Genjutsu's Character swap (MiniMax H3 on the h3_character_swap / H3 Relay packs): the part, the quality as the
+ // unpatched pack's string, who to swap (SAM words, largest / leftmost / rightmost / index, or clicks moved into H3's
+ // canvas), the swap LoRA's release, the window plan; the anchor first frame is images[1] (absent: its nodes go).
+ const characterSwap = manifest.capability === "video-character-swap";
+ let dropAnchor = false;
+ let dropSwapLora = false;
+ if (characterSwap) {
+ values.quality = packResolution(input.resolution);
+ if (extra.windowFrames !== undefined) extra.windowFrames = h3WindowFrames(Number(extra.windowFrames));
+ if (extra.historyFrames !== undefined) extra.historyFrames = h3HistoryFrames(Number(extra.historyFrames));
+ const lora = typeof extra.lora === "string" ? extra.lora : undefined;
+ delete extra.lora;
+ if (lora === "none") dropSwapLora = true;
+ else if (lora === "v1" || lora === "v1.5") values.lora = SWAP_LORAS[lora].file;
+ if (input.points?.length) {
+ if (!clip?.width || !clip.height) throw new ProviderError("Couldn't read the clip's size to place your clicks — pick who to swap instead");
+ const [pos, neg] = samCoords(input.points, { width: clip.width, height: clip.height }, input.resolution);
+ values.positiveCoords = pos;
+ values.negativeCoords = neg;
+ }
+ if (b.image2 && !values.image2) dropAnchor = true;
+ if (!values.prompt && typeof d.prompt === "string") values.prompt = d.prompt;
+ }
// Genjutsu's Object swap: SAM 3.1 follows what goes (params.extra.maskPrompt, or the "replace … with" part of the prompt,
// as Genjutsu sends it), the reference comes in, the prompt describes the result. Insert: the painted spot and the
// reference, the prompt says what appears there. Neither graph takes clicked points.
- if (ctx.op === "video-swap" || ctx.op === "video-insert") {
+ if ((ctx.op === "video-swap" || ctx.op === "video-insert") && !characterSwap) {
if (input.points?.length && !input.mask && typeof extra.maskPrompt !== "string") throw new ProviderError(OPEN_TARGET_PROBLEM[ctx.op === "video-insert" ? "insert" : "swap"]!);
const words = input.prompt?.trim() ?? "";
- const vace = getMaker(ctx.op === "video-swap" ? "oss-vace-swap" : "oss-vace-insert")!;
+ const vace = getMaker(ctx.op === "video-swap" ? ORIGINALS.swap : "oss-vace-insert", "open")!;
if (ctx.op === "video-swap" && b.maskPrompt) {
const named = typeof extra.maskPrompt === "string" ? extra.maskPrompt.trim() : "";
if (!named && !words) throw new ProviderError("Say what to swap, e.g. “the red car”");
@@ -967,8 +991,10 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
}
}
}
+ // The Character swap without an anchor frame: its loader and fit are taken out after binding.
+ if (dropAnchor) left.push("image2");
for (const [k, prev] of [["image2", "image"], ["image3", "image2"], ["image4", "image3"]] as const) {
- if (rules.views || !b[k] || values[k] !== undefined || rules.required?.includes(k)) continue;
+ if (rules.views || !b[k] || values[k] !== undefined || rules.required?.includes(k) || left.includes(k)) continue;
if (values[prev] === undefined && !left.includes(prev)) continue;
const bypassed = b[k]!.length === 1 ? bypassReference(graph, b[k]![0].node) : null;
if (bypassed) {
@@ -1003,6 +1029,9 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
if (bound.missing.length) throw new ProviderError(`Workflow ${manifest.id} bindings point at missing nodes: ${bound.missing.join(", ")}`);
let wf = bound.workflow;
const outputIds = manifest.outputs.map((o) => o.node);
+ if (dropAnchor) wf = withoutAnchor(wf, b.image2![0].node);
+ // LoRA "none": the swap LoRA's loader is linked out (H3 runs with the Turbo LoRA alone).
+ if (dropSwapLora && b.lora?.length === 1) wf = bypassNode(wf, b.lora[0].node, "model", outputIds);
// FPS Boost to a lower rate, or one the clip divides into: no interpolation, only every n-th frame.
if (finish.bypassInterpolation) {
const id = Object.keys(wf).find((k) => wf[k].class_type === "FrameInterpolate");
@@ -1064,6 +1093,30 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,
};
}
+/**
+ * The Character swap graph without its anchor frame (Openjutsu's swapWorkflow): the anchor's loader and every node that
+ * reads only it go, the swap's input takes no anchor and its use_anchor switch is off.
+ */
+export function withoutAnchor(wf: ComfyWorkflow, loaderId: string): ComfyWorkflow {
+ const out = JSON.parse(JSON.stringify(wf)) as ComfyWorkflow;
+ const gone = new Set([loaderId]);
+ // The loader's direct readers that exist only to fit it (anchor_fit): an image node fed by nothing else.
+ for (const [id, n] of Object.entries(out)) {
+ const links = Object.values(n.inputs).filter((v) => Array.isArray(v)) as [string, number][];
+ if (links.some((v) => v[0] === loaderId) && n.class_type === "ImageScale") gone.add(id);
+ }
+ for (const id of gone) delete out[id];
+ for (const n of Object.values(out)) {
+ for (const [k, v] of Object.entries(n.inputs)) {
+ if (Array.isArray(v) && gone.has(String(v[0]))) {
+ delete n.inputs[k];
+ if ("use_anchor" in n.inputs) n.inputs.use_anchor = false;
+ }
+ }
+ }
+ return out;
+}
+
/** Friendlier words for errors that a workflow's nodes report in their own terms. */
function explainExecutionError(err: { exception_message?: string; node_type?: string } | undefined, manifest?: ManifestWorkflow): string {
if (!err) return "Execution error";
diff --git a/tests/chain-optional.test.ts b/tests/chain-optional.test.ts
new file mode 100644
index 00000000..e09b2855
--- /dev/null
+++ b/tests/chain-optional.test.ts
@@ -0,0 +1,114 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import type { Generation } from "@/lib/catalog/types";
+import { ANCHOR_FALLBACK } from "@/lib/catalog/character-swap";
+
+// An optional chain input (ChainSlot.optional, Genjutsu's anchor first frame): when its step fails the step reading it
+// runs without it, with the fallback's prompt, and says so; a retry puts the request back as it was planned.
+
+vi.setConfig({ testTimeout: 90_000 });
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-optional-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const { createPipeline } = await import("@/server/chains");
+const { saveFile } = await import("@/server/storage");
+const { db } = await import("@/server/db");
+
+beforeAll(() => setSetting("demoMode", "auto"));
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+async function settle(id: string, ms = 80_000): Promise<Generation> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > end) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 250));
+ }
+}
+
+/** A step that stays "running" until the test lets go of it. */
+function held(): { id: string; fail: () => void } {
+ const id = `held${Math.random().toString(36).slice(2, 10)}`;
+ const now = Date.now();
+ db()
+ .prepare(
+ `INSERT INTO generations (id, batch_id, feature, preset_id, model_id, engine, provider, op, kind, status, progress, message, prompt, request_json, provider_input_json, external_id, external_meta_json, outputs_json, error, cost_usd, favorite, created_at, updated_at, completed_at, depends_on)
+ VALUES (?, NULL, 't', NULL, 'nano-banana-2', 'cloud', 'mock', 'edit', 'image', 'running', NULL, 'Held for the test', NULL, ?, NULL, NULL, NULL, '[]', NULL, 0, 0, ?, ?, NULL, NULL)`,
+ )
+ .run(id, JSON.stringify({ feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "held" }), now, now);
+ return { id, fail: () => db().prepare("UPDATE generations SET status = 'failed', error = 'Refused', completed_at = ? WHERE id = ?").run(Date.now(), id) };
+}
+
+const hero = () => saveFile({ data: fs.readFileSync(path.join(process.cwd(), "public/samples/grade-sample.jpg")), contentType: "image/jpeg", source: "upload" }).url;
+const optional = { prompt: "Swap without the anchor", notice: ANCHOR_FALLBACK };
+
+describe("optional chain inputs", () => {
+ it("withoutSkipped: the fallback's prompt and notice, and what was left out", () => {
+ const req = { feature: "t", modelId: "nano-banana-2", op: "edit" as const, prompt: "Swap with the anchor" };
+ const slots = [{ slot: "video" as const }, { slot: "images" as const, optional }];
+ expect(gens.withoutSkipped(req, slots, [1])).toEqual({ ...req, prompt: "Swap without the anchor", notice: ANCHOR_FALLBACK, chainSkipped: { slots: [1], prompt: "Swap with the anchor" } });
+ // A notice from before is kept; no fallback prompt keeps the planned one.
+ expect(gens.withoutSkipped({ ...req, notice: "Earlier" }, [{ slot: "images", optional: { notice: "Left out" } }], [0])).toMatchObject({ prompt: "Swap with the anchor", notice: "Earlier · Left out", chainSkipped: { slots: [0] } });
+ });
+
+ it("a failed anchor: the swap runs without it, says so, and the next step says so too; a retry is the planned request", async () => {
+ const anchor = held();
+ const image = hero();
+ const p = createPipeline(
+ [
+ {
+ key: "swap",
+ request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Swap with the anchor", inputs: { images: [image] } },
+ after: ["anchor"],
+ chain: [{ slot: "images", position: "last", optional }],
+ },
+ { key: "after", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Grade it" }, after: ["swap"], chain: [{ slot: "images" }] },
+ ],
+ { existing: { anchor: anchor.id } },
+ );
+ expect(gens.getGeneration(p.byKey.swap.id)!.status).toBe("queued");
+ anchor.fail();
+ const swap = await settle(p.byKey.swap.id);
+ expect(swap.status, swap.error ?? "").toBe("succeeded");
+ expect(swap.request).toMatchObject({ prompt: "Swap without the anchor", notice: ANCHOR_FALLBACK, chainSkipped: { slots: [0], prompt: "Swap with the anchor" } });
+ expect(swap.request.inputs?.images).toEqual([image]);
+ const next = await settle(p.byKey.after.id);
+ expect(next.status, next.error ?? "").toBe("succeeded");
+ expect(next.request.notice).toBe(ANCHOR_FALLBACK);
+ // Back as planned: the planned prompt, no notice, the character alone.
+ const back = gens.unfilledRequest(swap.request, 1);
+ expect(back.prompt).toBe("Swap with the anchor");
+ expect(back.notice).toBeUndefined();
+ expect(back.chainSkipped).toBeUndefined();
+ expect(back.inputs?.images).toEqual([image]);
+ });
+
+ it("an anchor that came through goes in last; a required input that fails still fails the step", async () => {
+ const image = hero();
+ const p = createPipeline([
+ { key: "anchor", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Put the character in", inputs: { images: [image] } } },
+ { key: "swap", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Swap with the anchor", inputs: { images: [image] } }, after: ["anchor"], chain: [{ slot: "images", position: "last", optional }] },
+ ]);
+ const swap = await settle(p.byKey.swap.id);
+ expect(swap.status, swap.error ?? "").toBe("succeeded");
+ expect(swap.request.prompt).toBe("Swap with the anchor");
+ expect(swap.request.notice).toBeUndefined();
+ expect(swap.request.inputs?.images).toEqual([image, gens.getGeneration(p.byKey.anchor.id)!.outputs[0].url]);
+
+ const cut = held();
+ const q = createPipeline(
+ [{ key: "swap", request: { feature: "t", modelId: "nano-banana-2", op: "edit", prompt: "Swap", inputs: { images: [image] } }, after: ["cut"], chain: [{ slot: "images" }] }],
+ { existing: { cut: cut.id } },
+ );
+ cut.fail();
+ expect(await settle(q.byKey.swap.id)).toMatchObject({ status: "failed", error: "An earlier step didn't finish" });
+ });
+});
diff --git a/tests/character-swap.test.ts b/tests/character-swap.test.ts
new file mode 100644
index 00000000..382c5f9d
--- /dev/null
+++ b/tests/character-swap.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, it } from "vitest";
+import {
+ alignFrames,
+ anchorModel,
+ anchorPrompt,
+ CHARACTER_LICENCES,
+ CHARACTER_SWAP,
+ characterLicenceLine,
+ characterQuality,
+ cutsInPart,
+ cutWarning,
+ falResolution,
+ graphLoras,
+ h3Canvas,
+ h3Windows,
+ H3_NODE_PACKS,
+ historyFrames,
+ MINIMAX_H3_LICENCE,
+ packResolution,
+ partProblem,
+ samCoords,
+ seedProblem,
+ speechLine,
+ swapLoraRef,
+ swapPrompt,
+ TURBO_LORA,
+ whoWords,
+ windowFrames,
+} from "@/lib/catalog/character-swap";
+import { licenceTerms } from "@/lib/licences";
+
+// Genjutsu's Character swap (docs/research/openjutsu-6.md): Openjutsu's prompt and limits, H3's windows and canvas,
+// who to swap, the anchor frame, and the licences as information.
+
+describe("Character swap: the prompt", () => {
+ it("Openjutsu's instruction in H3's tags, the anchor sentence only with an anchor", () => {
+ expect(swapPrompt({ engine: "open", anchor: true })).toBe(
+ "Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing. Start from the first frame in <Picture 2>.",
+ );
+ expect(swapPrompt({ engine: "open", anchor: false })).toBe("Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing.");
+ });
+
+ it("fal names the inputs Video 1 / Image 1 / Image 2, and says who in words (no mask in the cloud)", () => {
+ expect(swapPrompt({ engine: "cloud", anchor: true, who: "leftmost" })).toBe(
+ "Replace the person on the left in Video 1 with the character in Image 1. Preserve the source performance, scene and audio timing. Start from the first frame in Image 2.",
+ );
+ expect(swapPrompt({ engine: "cloud", anchor: false })).toMatch(/^Replace the main person in Video 1/);
+ expect(swapPrompt({ engine: "cloud", anchor: false, subject: "man in the red jacket" })).toMatch(/^Replace the man in the red jacket in Video 1/);
+ });
+
+ it("description, speaker and direction follow; the direction is trimmed to 500 characters", () => {
+ const p = swapPrompt({ engine: "open", anchor: false, description: "a chrome robot with blue eyes.", speech: "character", dialogue: "Hello there", direction: "keep the glasses. " });
+ expect(p).toBe(
+ 'Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing. The character: a chrome robot with blue eyes. The character speaks the clip\'s lines, lips in sync with its audio. The words: "Hello there". Keep the glasses.',
+ );
+ const long = swapPrompt({ engine: "open", anchor: false, direction: "x".repeat(900) });
+ expect(long.length).toBeLessThan(160 + CHARACTER_SWAP.maxDirectionChars);
+ });
+
+ it("who speaks, as Akatz Labs' speaker choice", () => {
+ expect(speechLine("other")).toMatch(/Someone else speaks/);
+ expect(speechLine("offscreen", "Over here!")).toMatch(/off screen.*"Over here!"/);
+ expect(speechLine("none")).toBe("Nobody speaks in this part.");
+ expect(speechLine(undefined)).toBe("");
+ });
+
+ it("who to swap, in words", () => {
+ expect(whoWords({})).toBe("the main person");
+ expect(whoWords({ who: "rightmost" })).toBe("the person on the right");
+ expect(whoWords({ who: "index", index: 1 })).toBe("the second person from the left");
+ expect(whoWords({ subject: "person" })).toBe("the main person");
+ expect(whoWords({ subject: "a woman in a hat" })).toBe("a woman in a hat");
+ });
+
+ it("the anchor's edit: Openjutsu's instruction, or Akatz Labs' brief when the character is described", () => {
+ expect(anchorPrompt({})).toMatch(/^Replace the person in image 1 with the character from image 2/);
+ const brief = anchorPrompt({ description: "a ronin in black armour", who: "leftmost" });
+ expect(brief).toMatch(/^Image 1 is the source frame to edit\. Image 2 is character identity only: a ronin in black armour\. Replace ONLY the person on the left/);
+ expect(brief).toMatch(/One full-aspect edited source frame\.$/);
+ });
+
+ it("the anchor model per engine: GPT Image 2.5 Sunburst (low) or Nano Banana Pro in the cloud, Qwen-Image-Edit on your GPU", () => {
+ expect(anchorModel("cloud")).toMatchObject({ id: "gpt-image-2-5-sunburst", extra: { quality: "low" } });
+ expect(anchorModel("cloud", "nano-banana-pro").id).toBe("nano-banana-pro");
+ expect(anchorModel("open").id).toBe("oss-qwen-edit");
+ // Another engine's model falls back to the engine's own.
+ expect(anchorModel("open", "nano-banana-pro").id).toBe("oss-qwen-edit");
+ });
+});
+
+describe("Character swap: limits", () => {
+ it("a part of 5–15 s (up to 30 s continued), inside a clip of at least 5 s", () => {
+ expect(partProblem({ start: 0, end: 4 })).toMatch(/Pick a part of 5–15 seconds/);
+ expect(partProblem({ start: 0, end: 5 })).toBeNull();
+ expect(partProblem({ start: 2, end: 17 })).toBeNull();
+ expect(partProblem({ start: 0, end: 30 })).toBeNull();
+ expect(partProblem({ start: 0, end: 31 })).toMatch(/up to 30 seconds/);
+ expect(partProblem({ start: 0, end: 4 }, 4)).toBe("Choose a clip at least 5 seconds long");
+ expect(partProblem({ start: 8, end: 14 }, 12)).toBe("The part runs past the end of the clip");
+ expect(partProblem({ start: -1, end: 6 })).toBe("Choose where the part starts");
+ });
+
+ it("seeds are whole numbers 0 … 2³²−1, blank is random", () => {
+ expect(seedProblem(undefined)).toBeNull();
+ expect(seedProblem(0)).toBeNull();
+ expect(seedProblem(2 ** 32 - 1)).toBeNull();
+ expect(seedProblem(2 ** 32)).toMatch(/whole-number seed/);
+ expect(seedProblem(1.5)).toMatch(/whole-number seed/);
+ });
+
+ it("qualities: 480p stays, the rest is 768p; the unpatched pack takes strings, fal its enum", () => {
+ expect(characterQuality("480p")).toBe("480p");
+ expect(characterQuality("720p")).toBe("768p");
+ expect(characterQuality("1080p")).toBe("768p");
+ expect(characterQuality(undefined)).toBe("768p");
+ expect(packResolution("480p")).toBe("480");
+ expect(packResolution("768p")).toBe("768");
+ expect(packResolution("768p", true)).toBe(768);
+ expect(falResolution("480p")).toBe("480P");
+ expect(falResolution("1080p")).toBe("768P");
+ });
+
+ it("H3's windows: 5 s → 1, 7.5 and 10 s → 2, 12.5 and 15 s → 3 (124 frames, padded to 17n+5)", () => {
+ expect(alignFrames(120)).toBe(124);
+ expect(alignFrames(240)).toBe(243);
+ expect(alignFrames(360)).toBe(362);
+ expect(h3Windows(5)).toBe(1);
+ expect(h3Windows(7.5)).toBe(2);
+ expect(h3Windows(10)).toBe(2);
+ expect(h3Windows(12.5)).toBe(3);
+ expect(h3Windows(15)).toBe(3);
+ expect(h3Windows(30)).toBe(6);
+ // A longer window means fewer.
+ expect(h3Windows(15, 362)).toBe(1);
+ // Window sizes are the pack's combo strings (17n+5 and 0, 1, 17n+1).
+ expect(windowFrames(124)).toBe("124");
+ expect(windowFrames(130)).toBe("124");
+ expect(windowFrames(undefined)).toBe("124");
+ expect(historyFrames(18)).toBe("18");
+ expect(historyFrames(0)).toBe("0");
+ expect(historyFrames(40)).toBe("35");
+ });
+
+ it("H3's canvas and clicks moved into it", () => {
+ // ComfyUI's adapt_canvas: a 768 short edge, capped at 768 × 1344, each side on the 32 grid.
+ expect(h3Canvas(1920, 1080, "768p")).toEqual({ width: 1344, height: 768 });
+ expect(h3Canvas(1080, 1920, "768p")).toEqual({ width: 768, height: 1344 });
+ expect(h3Canvas(1024, 1024, "768p")).toEqual({ width: 768, height: 768 });
+ expect(h3Canvas(1280, 720, "480p")).toEqual({ width: 832, height: 480 });
+ const [pos, neg] = samCoords(
+ [
+ { x: 960, y: 540, label: "positive" },
+ { x: 100, y: 100, label: "negative" },
+ ],
+ { width: 1920, height: 1080 },
+ "768p",
+ );
+ expect(JSON.parse(pos)).toEqual([{ x: 672, y: 384 }]);
+ expect(JSON.parse(neg)).toEqual([{ x: 70, y: 71 }]);
+ expect(samCoords(undefined, { width: 10, height: 10 }, "768p")).toEqual(["", ""]);
+ });
+
+ it("warns about a hard cut inside the part, not at its edges", () => {
+ expect(cutsInPart([1, 7.2, 15], { start: 2, end: 12 })).toEqual([7.2]);
+ expect(cutsInPart([2.1, 11.9], { start: 2, end: 12 })).toEqual([]);
+ expect(cutWarning([7.2])).toBe("Your part has a cut at 7.2 s — the swap breaks at a cut. Move the part, or pick one continuous shot");
+ expect(cutWarning([])).toBeNull();
+ });
+});
+
+describe("Character swap: LoRAs", () => {
+ it("the swap LoRA at its pinned revision (V1.5 by default, V1 on request), hostable on fal", () => {
+ const v15 = swapLoraRef(undefined);
+ expect(v15).toMatchObject({ file: "h3_character_swap_v1.5.safetensors", weightName: "h3_character_swap_v1.5.safetensors", strength: 1, version: "d06323b7c8e70e97cdab48b78a1e05f786c8cba9" });
+ expect(v15.url).toBe("https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/d06323b7c8e70e97cdab48b78a1e05f786c8cba9/h3_character_swap_v1.5.safetensors");
+ expect(v15.licence).toMatchObject({ commercial: true, hostedOk: true, name: "MiniMax H3 Community License" });
+ expect(swapLoraRef("v1").file).toBe("h3_character_swap_pro4500_1000.safetensors");
+ });
+
+ it("the files an open Character swap graph loads itself, downloaded before it runs", () => {
+ expect(graphLoras("video-character-swap-h3", {}).map((l) => l.file)).toEqual([TURBO_LORA.file, "h3_character_swap_v1.5.safetensors"]);
+ expect(graphLoras("video-character-swap-h3-relay", { lora: "v1" }).map((l) => l.file)).toEqual([TURBO_LORA.file, "h3_character_swap_pro4500_1000.safetensors"]);
+ expect(graphLoras("video-character-swap-h3", { lora: "none" }).map((l) => l.file)).toEqual([TURBO_LORA.file]);
+ expect(graphLoras("wan-animate2", {})).toEqual([]);
+ expect(TURBO_LORA.url).toContain("/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/");
+ });
+});
+
+describe("Character swap: licences are information", () => {
+ it("records the MiniMax H3 Community License with its regions, revenue condition and notice", () => {
+ expect(MINIMAX_H3_LICENCE).toMatchObject({ name: "MiniMax H3 Community License", class: "regions", excludes: "the US, the EU, the UK and South Korea", notices: ["MiniMax H3"] });
+ expect(MINIMAX_H3_LICENCE.note).toMatch(/US\$20M/);
+ expect(MINIMAX_H3_LICENCE.url).toContain("MiniMaxAI/MiniMax-H3");
+ });
+
+ it("every part the swap touches has a licence: the SAM License, the GPL-3.0 packs, the Turbo LoRA, MIT workflows, the paid API", () => {
+ const by = Object.fromEntries(CHARACTER_LICENCES.map((l) => [l.item.split(" (")[0], l]));
+ expect(by["SAM 3.1"]).toMatchObject({ name: "Meta SAM License", class: "conditions" });
+ expect(by["FL2V Turbo 8-step LoRA"]).toMatchObject({ name: "Apache-2.0", class: "commercial" });
+ expect(by["h3_character_swap node pack"]).toMatchObject({ name: "GPL-3.0" });
+ expect(by["H3 Relay 2.0 node pack"]).toMatchObject({ name: "GPL-3.0" });
+ expect(CHARACTER_LICENCES.find((l) => l.class === "paid-api")?.item).toMatch(/fal/);
+ expect(CHARACTER_LICENCES.every((l) => l.url.startsWith("https://"))).toBe(true);
+ expect(H3_NODE_PACKS.map((p) => p.name)).toEqual(["h3_character_swap", "h3-relay"]);
+ expect(H3_NODE_PACKS[0].licence).toMatchObject({ name: "GPL-3.0" });
+ });
+
+ it("the model picker's line says it, as information", () => {
+ expect(characterLicenceLine("open", "fuobe-character-swap")).toMatch(/not licensed in the US, the EU, the UK and South Korea.*show "MiniMax H3".*GPL-3.0/);
+ expect(characterLicenceLine("cloud", "fuobe-character-swap")).toMatch(/pay per second/);
+ expect(characterLicenceLine("cloud", "h3-max-recast")).toMatch(/closed H3 Max/);
+ });
+
+ it("the manifest's licence text reads as restricted regions with the notice (About & licences)", async () => {
+ const { default: manifest } = await import("../workflows/comfyui/manifest.json");
+ const wf = (manifest as { workflows: { id: string; license?: string }[] }).workflows.find((w) => w.id === "video-character-swap-h3")!;
+ const terms = licenceTerms(wf.license!);
+ expect(terms.flags).toContain("territory");
+ expect(terms.excludes).toBe("the US, the EU, the UK and South Korea");
+ expect(terms.notices).toContain("MiniMax H3");
+ });
+});
diff --git a/tests/comfy-character-swap.test.ts b/tests/comfy-character-swap.test.ts
new file mode 100644
index 00000000..a93c84eb
--- /dev/null
+++ b/tests/comfy-character-swap.test.ts
@@ -0,0 +1,91 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import type { ComfyWorkflow, Manifest } from "@/lib/comfy";
+import { H3_NODE_PACKS, H3_WORKFLOWS, SWAP_LORAS, TURBO_LORA } from "@/lib/catalog/character-swap";
+import { getModel } from "@/lib/catalog";
+
+// Genjutsu's Character swap in the ComfyUI library (docs/research/openjutsu-6.md): the two MiniMax H3 graphs, their
+// pinned weights with sizes, their node packs pinned in install-comfyui.sh, the licence text the About page reads, and
+// the core nodes checked against this server's /object_info (the packs are not installed here, so /prompt names one).
+const dir = path.join(process.cwd(), "workflows/comfyui");
+const manifest = JSON.parse(fs.readFileSync(path.join(dir, "manifest.json"), "utf8")) as Manifest;
+const subset = JSON.parse(fs.readFileSync(path.join(dir, "object_info.subset.json"), "utf8")) as Record<string, unknown>;
+const install = fs.readFileSync(path.join(process.cwd(), "scripts/comfy/install-comfyui.sh"), "utf8");
+const entry = (id: string) => manifest.workflows.find((w) => w.id === id)!;
+const graph = (id: string) => JSON.parse(fs.readFileSync(path.join(dir, `${id}.json`), "utf8")) as ComfyWorkflow;
+const [SWAP, RELAY] = H3_WORKFLOWS;
+const IDS = [SWAP, RELAY];
+const PACK = /^(H3CharacterSwap|H3Relay)/;
+
+describe("Character swap's ComfyUI graphs", () => {
+ it("are what the Original and the Relay model run", () => {
+ expect(getModel("fuobe-character-swap")!.routes.find((r) => r.provider === "comfyui")!.endpoint).toBe(SWAP);
+ expect(getModel("oss-h3-character-swap-relay")!.routes.find((r) => r.provider === "comfyui")!.endpoint).toBe(RELAY);
+ });
+
+ it("every weight is pinned to a revision, with its size; the V1 LoRA is optional", () => {
+ for (const id of IDS) {
+ const w = entry(id);
+ expect(w.capability).toBe("video-character-swap");
+ expect(w.vramGb).toBe(24);
+ expect(w.limits).toMatchObject({ maxDurationSec: 30 });
+ for (const m of w.models) {
+ expect(m.url, m.file).toMatch(/^https:\/\/huggingface\.co\/[^/]+\/[^/]+\/resolve\/[0-9a-f]{40}\//);
+ expect(m.sizeGb, m.file).toBeGreaterThan(0);
+ }
+ const files = w.models.map((m) => m.file);
+ expect(files).toEqual(expect.arrayContaining([SWAP_LORAS["v1.5"].file, SWAP_LORAS.v1.file, TURBO_LORA.file, "minimax_h3_ref2va_pruned_int8_convrot.safetensors", "sam3.1_multiplex_fp16.safetensors"]));
+ expect(w.models.find((m) => m.file === SWAP_LORAS.v1.file)!.optional).toBe(true);
+ expect(w.models.find((m) => m.file === SWAP_LORAS["v1.5"].file)!.url).toBe(SWAP_LORAS["v1.5"].url);
+ // About 46 GB of weights for the swap.
+ expect(w.models.filter((m) => !m.optional).reduce((n, m) => n + (m.sizeGb ?? 0), 0)).toBeGreaterThan(46);
+ }
+ });
+
+ it("say the licences as information: MiniMax H3's territory and notice, SAM, the GPL node packs", () => {
+ for (const id of IDS) {
+ const l = entry(id).license;
+ expect(l).toMatch(/MiniMax H3 Community License/);
+ expect(l).toMatch(/territory EXCLUDES the US, the EU, the UK and South Korea/);
+ expect(l).toMatch(/show "MiniMax H3"/);
+ expect(l).toMatch(/SAM License/);
+ expect(l).toMatch(/GPL-3\.0/);
+ }
+ expect(H3_NODE_PACKS.map((p) => [p.name, p.licence.name])).toEqual([["h3_character_swap", "GPL-3.0"], ["h3-relay", "GPL-3.0"]]);
+ });
+
+ it("name their node packs, pinned the same in install-comfyui.sh", () => {
+ expect(entry(SWAP).customNodes).toEqual([expect.objectContaining({ name: "h3_character_swap", repo: expect.stringContaining("0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b") })]);
+ expect(entry(RELAY).customNodes).toEqual([expect.objectContaining({ name: "h3-relay", repo: "https://github.com/akatz-ai/h3-relay" })]);
+ expect(install).toContain('H3_TOOL_REF="${H3_TOOL_REF:-0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b}"');
+ expect(install).toContain('H3_RELAY_REF="${H3_RELAY_REF:-e2a7665b6eb8ea37a88c0de2c9c6b69a8f7c9220}"');
+ // The Relay changes the server's routes when it loads: opt-in.
+ expect(install).toMatch(/H3_RELAY:-0\}" = "1"/);
+ });
+
+ it("their core nodes are on this server; the pack's are not, so /prompt names one of them", () => {
+ for (const id of IDS) {
+ const classes = [...new Set(Object.values(graph(id)).map((n) => n.class_type))];
+ for (const c of classes) {
+ expect(Object.hasOwn(subset, c), c).toBe(true);
+ if (PACK.test(c)) expect(subset[c], c).toBeNull();
+ else expect(subset[c], c).not.toBeNull();
+ }
+ const w = entry(id);
+ expect(w.validated).toBe(false);
+ expect((w as typeof w & { validationError?: string }).validationError).toMatch(/missing_node_type/);
+ }
+ });
+
+ it("every media loader is bound, and the anchor is image2 on the Original's graph only", () => {
+ for (const id of IDS) {
+ const w = entry(id);
+ const loaders = Object.entries(graph(id)).filter(([, n]) => n.class_type === "LoadImage" || n.class_type === "LoadVideo").map(([k]) => k);
+ const bound = new Set(Object.values(w.bindings).flatMap((b) => (b ?? []).map((x) => x.node)));
+ for (const k of loaders) expect(bound.has(k), `${id} ${k}`).toBe(true);
+ }
+ expect(entry(SWAP).bindings.image2).toEqual([{ node: "anchor_image", input: "image" }]);
+ expect(entry(RELAY).bindings.image2).toBeUndefined();
+ });
+});
diff --git a/tests/comfy-library-4.test.ts b/tests/comfy-library-4.test.ts
index ea0af6eb..60d5dc98 100644
--- a/tests/comfy-library-4.test.ts
+++ b/tests/comfy-library-4.test.ts
@@ -82,7 +82,9 @@ describe("round-4 ComfyUI workflows", () => {
it("keeps the whole library validated, and every output role is a typed role", () => {
expect(manifest.workflows.length).toBeGreaterThanOrEqual(132);
expect(new Set(manifest.workflows.map((w) => w.id)).size).toBe(manifest.workflows.length);
- expect(manifest.workflows.filter((w) => !w.validated).map((w) => w.id)).toEqual([]);
+ // Only the Character swap graphs wait on node packs this server doesn't have (h3_character_swap, H3 Relay): never
+ // installed here, so their /prompt check names a missing node (tests/comfy-character-swap.test.ts).
+ expect(manifest.workflows.filter((w) => !w.validated).map((w) => w.id)).toEqual(["video-character-swap-h3", "video-character-swap-h3-relay"]);
for (const w of manifest.workflows) for (const o of w.outputs) if (o.role) expect(ROLES, `${w.id} ${o.role}`).toContain(o.role);
});
diff --git a/tests/genjutsu-api.test.ts b/tests/genjutsu-api.test.ts
index 3cd86e8a..786b8306 100644
--- a/tests/genjutsu-api.test.ts
+++ b/tests/genjutsu-api.test.ts
@@ -2,6 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { CLOUD_CLICK_PROBLEM } from "@/lib/catalog/genjutsu";
import type { Generation } from "@/lib/catalog/types";
vi.setConfig({ testTimeout: 120_000 });
@@ -64,47 +65,76 @@ const src = { duration: 12, fps: 16, width: 1280, height: 720, hasAudio: true };
const body = (over: Record<string, unknown> = {}) => ({ engine: "cloud", mode: "motion", references: [hero], source: { url: clip, name: "dance.mp4" }, ...over });
describe("Genjutsu: estimates", () => {
- it("without a Higgsfield key: Kling Motion Control in 10 s pieces, run as a demo", async () => {
+ it("no keys: the Original's Lite tier, run as a demo; no Higgsfield anywhere", async () => {
const res = await estimateRoute.POST(json(body({ source: { url: clip, ...src } })));
expect(res.status).toBe(200);
const e = await res.json();
- expect(e).toMatchObject({ modelId: "kling-motion-control", pieces: 2, seconds: 12, demo: true, higgsfield: false });
- expect(e.notes.join(" ")).toMatch(/2 pieces, joined with its own sound/);
+ expect(e).toMatchObject({ modelId: "fuobe-genjutsu-motion-lite", source: "original", tier: "standard", quality: "480p", pieces: 1, seconds: 12, demo: true });
+ expect(e.higgsfield).toBeUndefined();
});
describe("with keys (estimates submit nothing, so the prices are the routes' own)", () => {
- beforeAll(() => {
- setSetting("higgsfieldKey", "key-id:key-secret");
- setSetting("falKey", "fal-test-key");
- });
- afterAll(() => {
- setSetting("higgsfieldKey", "");
- setSetting("falKey", "");
- });
+ beforeAll(() => setSetting("falKey", "fal-test-key"));
+ afterAll(() => setSetting("falKey", ""));
- it("Genjutsu Lite by default; Quality: High is the full model at its own price per resolution", async () => {
- const lite = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src }, quality: "1080p" })))).json();
- // One 12 s call (Lite takes 15 s) that keeps the sound: $0.20 a second at 1080p.
- expect(lite).toMatchObject({ modelId: "genjutsu-lite-motion-transfer", tier: "standard", quality: "1080p", pieces: 1, steps: 1, demo: false, higgsfield: true });
- expect(lite.costUsd).toBeCloseTo(2.4, 4);
- expect(lite.notes.join(" ")).toMatch(/50% off/);
- const full = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src, duration: 12.3 }, range: { start: 0, end: 12.3 }, tier: "high", quality: "480p" })))).json();
- // Whole seconds: 13 × $0.318.
- expect(full).toMatchObject({ modelId: "genjutsu-motion-transfer", tier: "high" });
- expect(full.costUsd).toBeCloseTo(13 * 0.318, 4);
+ it("motion: Lite is Wan 2.2 Animate at 480p turbo; Quality: High is the full model at its own price per resolution", async () => {
+ // 12 s at 16 fps = 192 frames = 12 video seconds: $0.04 each, then the sound put back.
+ const lite = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src } })))).json();
+ expect(lite).toMatchObject({ modelId: "fuobe-genjutsu-motion-lite", tier: "standard", quality: "480p", pieces: 1, steps: 2, demo: false, providers: ["fal"] });
+ expect(lite.costUsd).toBeGreaterThanOrEqual(0.48);
+ expect(lite.costUsd).toBeLessThan(0.49);
+ const high = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src }, tier: "high", quality: "720p" })))).json();
+ expect(high).toMatchObject({ modelId: "fuobe-genjutsu-motion", tier: "high", quality: "720p" });
+ expect(high.costUsd).toBeGreaterThanOrEqual(0.96);
+ expect(high.costUsd).toBeLessThan(0.97);
+ // fal bills frames ÷ 16: a 30 fps clip costs 1.9× its length, and says so.
+ const fast = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src, fps: 30 } })))).json();
+ expect(fast.notes.join(" ")).toMatch(/fal bills this clip's 30 fps as 1\.9× its length/);
});
it("Kling O3 swap at its edit price; the hosted VACE per 16-frame second", async () => {
const kling = await (await estimateRoute.POST(json(body({ mode: "swap", modelId: "kling-o3", subject: "the red car", source: { url: clip, ...src, duration: 10 }, range: { start: 0, end: 10 } })))).json();
- expect(kling).toMatchObject({ modelId: "kling-o3", pieces: 1 });
+ expect(kling).toMatchObject({ modelId: "kling-o3", source: "partner", pieces: 1 });
expect(kling.costUsd).toBeCloseTo(1.68, 3);
expect(kling.notes.join(" ")).toMatch(/keeps your clip's size/);
const vace = await (await estimateRoute.POST(json(body({ mode: "insert", target: "paint", mask: "/api/files/m.png", quality: "480p", source: { url: clip, ...src }, range: { start: 0, end: 10 } })))).json();
// 160 frames at 16 fps → one piece of 157 frames, billed as 157 / 16 s at $0.05, then the sound put back.
- expect(vace).toMatchObject({ modelId: "wan-22-vace-inpaint", pieces: 1, quality: "480p" });
+ expect(vace).toMatchObject({ modelId: "wan-22-vace-inpaint", source: "open", pieces: 1, quality: "480p" });
expect(vace.costUsd).toBeGreaterThanOrEqual((157 / 16) * 0.05);
expect(vace.costUsd).toBeLessThan((157 / 16) * 0.05 + 0.01);
});
+
+ it("Character swap on fal: H3 with the swap LoRA per second, the first frame on its own price (or said when billed by tokens), the limits", async () => {
+ const part = { source: { url: clip, ...src }, mode: "character", range: { start: 2, end: 9 } };
+ const sun = await (await estimateRoute.POST(json(body(part)))).json();
+ // 7 s at 768p: $0.075 a second; Sunburst's first frame is billed by tokens and left out, in words.
+ expect(sun).toMatchObject({ modelId: "fuobe-character-swap", source: "original", quality: "768p", pieces: 1, anchors: 1, demo: false });
+ expect(sun.costUsd).toBeGreaterThanOrEqual(0.525);
+ expect(sun.costUsd).toBeLessThan(0.535);
+ expect(sun.notes.join(" ")).toMatch(/billed by tokens .* isn't in the price/);
+ expect(sun.notes.join(" ")).toMatch(/MiniMax H3 Community License — not licensed in the US, the EU, the UK and South Korea/);
+ expect(sun.limits).toContain("One continuous shot: a hard cut breaks the swap");
+ expect(sun.gpu).toBeUndefined();
+ const nbp = await (await estimateRoute.POST(json(body({ ...part, character: { anchorModel: "nano-banana-pro" } })))).json();
+ expect(nbp.costUsd).toBeCloseTo(sun.costUsd + 0.15, 3);
+ // No first frame, 480p: $0.0625 a second.
+ const bare = await (await estimateRoute.POST(json(body({ ...part, quality: "480p", character: { anchor: false } })))).json();
+ expect(bare).toMatchObject({ anchors: 0, quality: "480p" });
+ expect(bare.costUsd).toBeGreaterThanOrEqual(0.4375);
+ expect(bare.costUsd).toBeLessThan(0.445);
+ // MiniMax's own Recast, a partner: $0.30 a second at 768p.
+ const recast = await (await estimateRoute.POST(json(body({ ...part, modelId: "h3-max-recast", range: { start: 2, end: 12 } })))).json();
+ expect(recast).toMatchObject({ modelId: "h3-max-recast", source: "partner" });
+ expect(recast.costUsd).toBeCloseTo(3, 2);
+ });
+ });
+
+ it("Character swap on the open engine: free on your GPU, the windows, the GPU it was tested on and the licences", async () => {
+ const e = await (await estimateRoute.POST(json(body({ engine: "open", mode: "character", source: { url: clip, ...src }, range: { start: 2, end: 9 } })))).json();
+ expect(e).toMatchObject({ modelId: "fuobe-character-swap", source: "original", costUsd: 0, anchors: 1, gpu: { weightsGb: 46.33 } });
+ expect(e.notes.join(" ")).toMatch(/2 windows of 124 frames at 24 fps/);
+ expect(e.notes.join(" ")).toMatch(/nodes GPL-3\.0 · SAM License/);
+ expect(e.notes.join(" ")).toMatch(/Qwen-Image-Edit 2511 first puts your character into the part's first frame/);
});
describe("key mixes: a run is all real or all a demo, so a missing key is said before anything is paid for", () => {
@@ -115,49 +145,26 @@ describe("Genjutsu: estimates", () => {
return out.error as string;
};
afterAll(() => {
- setSetting("higgsfieldKey", "");
+ setSetting("replicateToken", "");
setSetting("falKey", "");
setSetting("demoMode", "auto");
});
- it("only a Higgsfield key: Genjutsu Lite runs the whole clip in one call; cuts and joins need fal", async () => {
- setSetting("higgsfieldKey", "key-id:key-secret");
- setSetting("falKey", "");
- const whole = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src } })))).json();
- expect(whole).toMatchObject({ modelId: "genjutsu-lite-motion-transfer", steps: 1, demo: false, higgsfield: true });
- expect(whole.costUsd).toBeCloseTo(1.2, 4);
- // A part of the 12 s clip needs a cut on fal: the way around is the whole clip.
- expect(await say(body({ source: { url: clip, ...src }, range: { start: 0, end: 10 } }))).toBe("Cutting the clip runs on fal.ai — add a fal.ai key in Settings → API keys, or use the whole clip");
- // 20 s on Lite is two 15 s calls joined on fal: Quality: High takes it in one.
- expect(await say(body({ source: { url: clip, ...src, duration: 20 }, range: { start: 0, end: 20 } }))).toBe(
- "Cutting the clip, joining the pieces and putting the sound back run on fal.ai — add a fal.ai key in Settings → API keys, or pick Quality: High (up to 30 s in one call)",
- );
- const high = await (await estimateRoute.POST(json(body({ tier: "high", source: { url: clip, ...src, duration: 20 }, range: { start: 0, end: 20 } })))).json();
- expect(high).toMatchObject({ modelId: "genjutsu-motion-transfer", steps: 1, demo: false });
+ it("only a Replicate token: P-Video Replace runs the whole clip; a part needs a cut on fal", async () => {
+ setSetting("replicateToken", "r8_test");
+ const whole = await (await estimateRoute.POST(json(body({ mode: "character", modelId: "p-video-replace", source: { url: clip, ...src } })))).json();
+ expect(whole).toMatchObject({ modelId: "p-video-replace", source: "partner", steps: 1, demo: false, providers: ["replicate"] });
+ expect(await say(body({ mode: "character", modelId: "p-video-replace", source: { url: clip, ...src }, range: { start: 0, end: 10 } }))).toBe("Cutting the clip runs on fal.ai — add a fal.ai key in Settings → API keys");
// Starting it is refused the same way, and nothing is made.
const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
- expect(await say(body({ source: { url: clip }, range: { start: 0, end: 10 } }), createRoute)).toMatch(/^Cutting the clip runs on fal\.ai/);
+ expect(await say(body({ mode: "character", modelId: "p-video-replace", source: { url: clip }, range: { start: 0, end: 10 } }), createRoute)).toMatch(/^Cutting the clip runs on fal\.ai/);
expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(before);
+ setSetting("replicateToken", "");
});
- it("only a fal key: Genjutsu Lite picked is a demo for the whole clip, and refused when a real cut would feed it", async () => {
- setSetting("higgsfieldKey", "");
- setSetting("falKey", "fal-test-key");
- const whole = await (await estimateRoute.POST(json(body({ modelId: "genjutsu-lite-motion-transfer", source: { url: clip, ...src } })))).json();
- expect(whole).toMatchObject({ modelId: "genjutsu-lite-motion-transfer", demo: true, costUsd: 0, higgsfield: false });
- expect(await say(body({ modelId: "genjutsu-lite-motion-transfer", source: { url: clip, ...src }, range: { start: 0, end: 10 } }))).toBe(
- "Genjutsu Lite Motion Transfer runs on Higgsfield — add a Higgsfield key in Settings → API keys, or pick Kling 3.0 Motion Control",
- );
- // The default without a Higgsfield key runs for real.
- const kling = await (await estimateRoute.POST(json(body({ source: { url: clip, ...src }, range: { start: 0, end: 10 } })))).json();
- expect(kling).toMatchObject({ modelId: "kling-motion-control", demo: false });
- });
-
- it("demo mode off and no keys: the keys it needs, in words", async () => {
- setSetting("higgsfieldKey", "");
- setSetting("falKey", "");
+ it("demo mode off and no keys: the key it needs, in words", async () => {
setSetting("demoMode", "off");
- expect(await say(body({ source: { url: clip, ...src } }))).toMatch(/^Kling 3\.0 Motion Control runs on .*, and cutting the clip, joining the pieces and putting the sound back run on fal\.ai — add a fal\.ai key in Settings → API keys$/);
+ expect(await say(body({ source: { url: clip, ...src } }))).toBe("Fuobe Genjutsu Lite · Motion runs on fal.ai, and putting the sound back runs on fal.ai — add a fal.ai key in Settings → API keys");
setSetting("demoMode", "auto");
});
});
@@ -173,6 +180,10 @@ describe("Genjutsu: estimates", () => {
expect(await say(body({ mode: "swap", target: "paint", engine: "open", source: { url: clip, ...src } }))).toMatch(/name what to swap/);
expect(await say(body({ mode: "swap", modelId: "kling-o3", source: { url: clip, ...src, duration: 10 }, range: { start: 0, end: 10 } }))).toMatch(/Say what to swap/);
expect(await say(body({ mode: "restyle", references: [], source: { url: clip, ...src } }))).toBe("Pick a look");
+ // Character swap: a part of 5–15 s, a click only on the open engine.
+ expect(await say(body({ mode: "character", source: { url: clip, ...src }, range: { start: 0, end: 4.5 } }))).toMatch(/Pick a part of 5–15 seconds/);
+ expect(await say(body({ mode: "character", target: "click", source: { url: clip, ...src }, range: { start: 0, end: 6 } }))).toBe(CLOUD_CLICK_PROBLEM);
+ expect(await say(body({ engine: "open", mode: "character", target: "click", source: { url: clip, ...src }, range: { start: 0, end: 6 } }))).toBe("Click the person to swap on the first frame");
setSetting("engineMode", "open");
expect(await say(body({ source: { url: clip, ...src } }))).toMatch(/open-source models only/);
setSetting("engineMode", "both");
@@ -187,13 +198,14 @@ describe("Genjutsu: runs (demo)", () => {
return out as { final: Generation; items: Generation[] };
};
- it("cloud motion transfer: pieces, a join and the sound, the finished video under feature genjutsu", async () => {
+ it("cloud motion transfer on the Original: one call and the sound, the finished video under feature genjutsu", async () => {
const { final, items } = await run(body({ prompt: "a knight in silver armour" }));
expect(final.feature).toBe("genjutsu");
expect(items.filter((g) => g.feature === "genjutsu")).toHaveLength(1);
const rows = batchOf(final.id);
- expect(rows.filter((r) => r.op === "motion-transfer").map((r) => r.model_id)).toEqual(["kling-motion-control", "kling-motion-control"]);
- expect(rows.some((r) => r.op === "concat") && rows.some((r) => r.op === "mux")).toBe(true);
+ // Wan 2.2 Animate takes the whole 12 s selection in one call; the sound goes back on after.
+ expect(rows.filter((r) => r.op === "motion-transfer").map((r) => r.model_id)).toEqual(["fuobe-genjutsu-motion-lite"]);
+ expect(rows.some((r) => r.op === "mux")).toBe(true);
expect((await settle(final.id)).status).toBe("succeeded");
});
@@ -208,7 +220,7 @@ describe("Genjutsu: runs (demo)", () => {
const { final } = await run(body({ engine: "open", mode: "swap", subject: "the skateboard", references: [hero, hero] }));
const rows = batchOf(final.id);
// 192 frames at 16 fps → 3 windows of ≤81.
- expect(rows.filter((r) => r.op === "video-swap").map((r) => r.model_id)).toEqual(["oss-vace-swap", "oss-vace-swap", "oss-vace-swap"]);
+ expect(rows.filter((r) => r.op === "video-swap").map((r) => r.model_id)).toEqual(["fuobe-genjutsu-swap-lite", "fuobe-genjutsu-swap-lite", "fuobe-genjutsu-swap-lite"]);
const swap = gens.getGeneration(rows.find((r) => r.op === "video-swap")!.id)!;
expect(swap.request.params?.extra).toEqual({ maskPrompt: "the skateboard" });
expect(swap.request.inputs?.images).toEqual([hero]);
@@ -216,7 +228,7 @@ describe("Genjutsu: runs (demo)", () => {
});
it("cloud swap by paint on one hosted VACE piece: the paint itself, no track", async () => {
- const { final } = await run(body({ mode: "swap", target: "paint", mask, range: { start: 0, end: 12 } }));
+ const { final } = await run(body({ mode: "swap", modelId: "wan-22-vace-inpaint", target: "paint", mask, range: { start: 0, end: 12 } }));
const rows = batchOf(final.id);
expect(rows.some((r) => r.model_id === "sam-3-1-video-mask")).toBe(false);
// 12 s at 16 fps is one hosted VACE piece (≤241 frames): the paint itself, no track.
@@ -234,4 +246,32 @@ describe("Genjutsu: runs (demo)", () => {
expect(rows.filter((r) => r.feature === "genjutsu")).toHaveLength(1);
expect((await settle(look.final.id)).status).toBe("succeeded");
});
+
+ it("Character swap on fal: the part cut, its first frame, the anchor, H3 with the swap LoRA, the sound put back", async () => {
+ const { final } = await run(body({ mode: "character", range: { start: 2, end: 9 }, seed: 9, character: { who: "rightmost" } }));
+ const rows = batchOf(final.id);
+ // The part and the sound's part cut, the first frame, the anchor, the swap, the sound put back.
+ expect(rows.map((r) => `${r.model_id}:${r.op}`).sort()).toEqual(
+ ["trim-video:trim", "trim-video:trim", "extract-frame:frame", "gpt-image-2-5-sunburst:edit", "fuobe-character-swap:video-swap", "merge-audio-video:mux"].sort(),
+ );
+ const swapRow = rows.find((r) => r.op === "video-swap")!;
+ expect(swapRow.model_id).toBe("fuobe-character-swap");
+ expect((await settle(final.id)).status).toBe("succeeded");
+ const swap = gens.getGeneration(swapRow.id)!;
+ expect(swap.request.loras).toEqual([expect.objectContaining({ file: "h3_character_swap_v1.5.safetensors" })]);
+ expect(swap.request.params).toMatchObject({ duration: 7, resolution: "768p", seed: 9 });
+ expect(swap.request.prompt).toMatch(/^Replace the person on the right in Video 1 with the character in Image 1\./);
+ // The character first, then the anchor frame made from the part's first frame.
+ const anchor = gens.getGeneration(rows.find((r) => r.model_id === "gpt-image-2-5-sunburst")!.id)!;
+ expect(swap.request.inputs?.images).toEqual([hero, anchor.outputs[0].url]);
+ });
+
+ it("Character swap on the open engine: the first frame, the anchor on Qwen-Image-Edit, one H3 job on the upload", async () => {
+ const { final } = await run(body({ engine: "open", mode: "character", range: { start: 2, end: 9 }, character: { who: "index", index: 1, subject: "the drummer", lora: "v1" } }));
+ const rows = batchOf(final.id);
+ expect(rows.map((r) => r.model_id).sort()).toEqual(["fuobe-character-swap", "oss-extract-frame", "oss-qwen-edit"]);
+ expect(final.modelId).toBe("fuobe-character-swap");
+ expect(final.request.params).toMatchObject({ startTime: 2, endTime: 9, resolution: "768p", extra: { selection: "index", subjectIndex: 1, maskPrompt: "the drummer", lora: "v1" } });
+ expect((await settle(final.id)).status).toBe("succeeded");
+ });
});
diff --git a/tests/genjutsu-comfy.test.ts b/tests/genjutsu-comfy.test.ts
index f3eb1435..1da6f880 100644
--- a/tests/genjutsu-comfy.test.ts
+++ b/tests/genjutsu-comfy.test.ts
@@ -2,16 +2,16 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
-import { getMaker, OPEN_TARGET_PROBLEM, planGenjutsu } from "@/lib/catalog/genjutsu";
+import { getMaker, OPEN_TARGET_PROBLEM, ORIGINALS, planGenjutsu } from "@/lib/catalog/genjutsu";
import type { GenInput, Operation } from "@/lib/catalog/types";
import type { MediaInfo } from "@/lib/media-probe";
-// The comfyui provider driving Genjutsu's open graphs (Wan 2.1 VACE swap / insert, Wan Animate 2), bound for real on
-// the library graphs, and a planned window going through it.
+// The comfyui provider driving Genjutsu's open graphs (Wan 2.1 VACE swap / insert, Wan Animate 2, MiniMax H3's
+// Character swap), bound for real on the library graphs, and planned steps going through it.
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-genjutsu-comfy-"));
process.env.FUOBE_DATA_DIR = tmp;
process.env.COMFYUI_URL = "http://comfy.test:8188";
-const { prepareWorkflow } = await import("@/server/providers/comfyui");
+const { prepareWorkflow, withoutAnchor } = await import("@/server/providers/comfyui");
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
const clip: MediaInfo = { container: "mp4", hasVideo: true, hasAudio: true, duration: 12, videoDuration: 12, width: 1280, height: 720, fps: 30, frames: 360 };
@@ -62,7 +62,7 @@ describe("Genjutsu's open graphs through the provider", () => {
const plan = planGenjutsu({
engine: "open",
mode: "swap",
- maker: getMaker("oss-vace-swap")!,
+ maker: getMaker(ORIGINALS.swap, "open")!,
title: "t",
source: { url: "/api/files/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true },
range: { start: 0, end: 12 },
@@ -87,3 +87,100 @@ describe("Genjutsu's open graphs through the provider", () => {
expect([at(wf, "672:600", "resize_type.width"), at(wf, "672:600", "resize_type.height")]).toEqual([1280, 720]);
});
});
+
+describe("Character swap's open graphs through the provider (MiniMax H3)", () => {
+ type Graph = Record<string, { class_type: string; inputs: Record<string, unknown> }>;
+ const h3 = (input: Partial<GenInput>) => prepare("video-character-swap-h3", input, "video-swap").then((r) => r.workflow as Graph);
+ const relay = (input: Partial<GenInput>) => prepare("video-character-swap-h3-relay", input, "video-swap").then((r) => r.workflow as Graph);
+
+ it("the clip, the character, the part, the quality as the pack's string, the words and the seed", async () => {
+ const wf = await h3({ images: ["hero.png", "anchor.png"], startTime: 2, endTime: 9, resolution: "768p", seed: 77, prompt: "Replace the selected person in <Video 1> with the character in <Picture 1>." });
+ expect(at(wf, "30", "file")).toBe("clip.mp4");
+ expect(at(wf, "9", "image")).toBe("hero.png");
+ expect(at(wf, "anchor_image", "image")).toBe("anchor.png");
+ expect([at(wf, "trim", "start_time"), at(wf, "trim", "duration"), at(wf, "31", "duration_seconds")]).toEqual([2, 7, 7]);
+ expect(at(wf, "31", "resolution")).toBe("768");
+ expect(at(wf, "801", "prompt")).toBe("Replace the selected person in <Video 1> with the character in <Picture 1>.");
+ expect(at(wf, "801", "seed")).toBe(77);
+ expect(at(wf, "803", "use_anchor")).toBe(true);
+ expect(at(wf, "803", "anchor")).toEqual(["anchor_fit", 0]);
+ // The swap LoRA v1.5 by default; the output is the saved video.
+ expect(at(wf, "850", "lora_name")).toBe("h3_character_swap_v1.5.safetensors");
+ expect(wf["809"].class_type).toBe("SaveVideo");
+ const low = await h3({ images: ["hero.png"], startTime: 0, endTime: 5, resolution: "480p" });
+ expect(at(low, "31", "resolution")).toBe("480");
+ });
+
+ it("who to swap: SAM 3.1's words, largest / leftmost / rightmost / by number, the mask's margin", async () => {
+ const wf = await h3({ images: ["hero.png"], startTime: 0, endTime: 6, extra: { selection: "index", subjectIndex: 2, maskPrompt: "the dancer", maskGrow: 32, useMask: false, audioGuide: false } });
+ expect(at(wf, "101", "text")).toBe("the dancer");
+ expect([at(wf, "104", "selection"), at(wf, "104", "index")]).toEqual(["index", 2]);
+ expect(at(wf, "110", "expansion_px")).toBe(32);
+ expect(at(wf, "803", "use_mask")).toBe(false);
+ expect(at(wf, "801", "audio_guide")).toBe(false);
+ });
+
+ it("clicks are moved into H3's canvas for SAM 3.1 (positive and negative)", async () => {
+ const wf = await h3({ images: ["hero.png"], startTime: 0, endTime: 6, resolution: "768p", points: [{ x: 640, y: 360, label: "positive" }, { x: 10, y: 10, label: "negative" }] });
+ // 1280×720 → 1344×768 at 768p: the clip's middle stays the canvas's middle.
+ expect(JSON.parse(String(at(wf, "103", "positive_coords")))).toEqual([{ x: 672, y: 384 }]);
+ expect(JSON.parse(String(at(wf, "103", "negative_coords")))).toHaveLength(1);
+ });
+
+ it("the window plan as the pack's choices, and the LoRA's release (v1, or none: the Turbo LoRA alone)", async () => {
+ const wf = await h3({ images: ["hero.png"], startTime: 0, endTime: 6, extra: { windowFrames: 120, historyFrames: 20, lora: "v1" } });
+ expect([at(wf, "805", "window_frames"), at(wf, "805", "history_frames")]).toEqual(["124", "18"]);
+ expect(at(wf, "850", "lora_name")).toBe("h3_character_swap_pro4500_1000.safetensors");
+ const bare = await h3({ images: ["hero.png"], startTime: 0, endTime: 6, extra: { lora: "none" } });
+ expect(bare["850"]).toBeUndefined();
+ expect(at(bare, "800", "model")).toEqual(["4", 0]);
+ });
+
+ it("no anchor frame: its loader and fit go, the shot takes none and its switch is off", async () => {
+ const wf = await h3({ images: ["hero.png"], startTime: 0, endTime: 6 });
+ expect(wf.anchor_image).toBeUndefined();
+ expect(wf.anchor_fit).toBeUndefined();
+ expect(at(wf, "803", "anchor")).toBeUndefined();
+ expect(at(wf, "803", "use_anchor")).toBe(false);
+ expect(at(wf, "803", "reference")).toEqual(["9", 0]);
+ // withoutAnchor leaves a graph with no dangling links.
+ const ids = new Set(Object.keys(wf));
+ for (const n of Object.values(wf)) for (const v of Object.values(n.inputs)) if (Array.isArray(v) && typeof v[0] === "string") expect(ids.has(v[0])).toBe(true);
+ expect(withoutAnchor({ a: { class_type: "LoadImage", inputs: { image: "x" } }, b: { class_type: "Shot", inputs: { anchor: ["a", 0], use_anchor: true } } }, "a")).toEqual({ b: { class_type: "Shot", inputs: { use_anchor: false } } });
+ });
+
+ it("H3 Relay: the same part, quality, words, seed and who, on Akatz's relay graph", async () => {
+ const wf = await relay({ images: ["hero.png"], startTime: 1, endTime: 11, resolution: "480p", seed: 5, prompt: "Replace the selected person in <Video 1> with the character in <Picture 1>.", extra: { selection: "leftmost", maskPrompt: "the singer" } });
+ expect(at(wf, "source", "file")).toBe("clip.mp4");
+ expect(at(wf, "reference", "image")).toBe("hero.png");
+ expect([at(wf, "trim", "start_time"), at(wf, "trim", "duration"), at(wf, "prepare", "duration_seconds")]).toEqual([1, 10, 10]);
+ expect(at(wf, "prepare", "resolution")).toBe("480");
+ expect(at(wf, "plan", "seed")).toBe(5);
+ expect(at(wf, "reference_conditioning", "prompt")).toMatch(/<Picture 1>/);
+ expect([at(wf, "select", "selection"), at(wf, "subject", "text")]).toEqual(["leftmost", "the singer"]);
+ expect(wf.save.class_type).toBe("SaveVideo");
+ });
+
+ it("a planned open Character swap is what the graph is given", async () => {
+ const p = planGenjutsu({
+ engine: "open",
+ mode: "character",
+ maker: getMaker(ORIGINALS.character, "open")!,
+ title: "t",
+ source: { url: "/api/files/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true },
+ range: { start: 2, end: 9 },
+ quality: "768p",
+ references: ["/api/files/hero.png"],
+ seed: 11,
+ character: { who: "rightmost", subject: "the drummer" },
+ });
+ const req = p.steps.find((s) => s.key === "swap")!.request;
+ const wf = (await prepare("video-character-swap-h3", { prompt: req.prompt, images: ["hero.png", "anchor.png"], ...req.params } as Partial<GenInput>, "video-swap")).workflow as Graph;
+ expect([at(wf, "trim", "start_time"), at(wf, "trim", "duration")]).toEqual([2, 7]);
+ expect(at(wf, "31", "resolution")).toBe("768");
+ expect([at(wf, "104", "selection"), at(wf, "101", "text")]).toEqual(["rightmost", "the drummer"]);
+ expect(at(wf, "801", "seed")).toBe(11);
+ expect(at(wf, "801", "prompt")).toMatch(/<Video 1>.*<Picture 1>.*<Picture 2>/s);
+ expect(at(wf, "anchor_image", "image")).toBe("anchor.png");
+ });
+});
diff --git a/tests/genjutsu.test.ts b/tests/genjutsu.test.ts
index f9e8b3cb..294dbbba 100644
--- a/tests/genjutsu.test.ts
+++ b/tests/genjutsu.test.ts
@@ -1,14 +1,19 @@
import { describe, expect, it } from "vitest";
import {
+ billedSeconds,
chooseMaker,
+ CLOUD_CLICK_PROBLEM,
decodeSetup,
encodeSetup,
genjutsuProblem,
getMaker,
+ h3Extra,
+ LEGACY_MAKERS,
makerPrompt,
makersFor,
makerStepUsd,
- OPEN_LOOK_PROBLEM,
+ MAKERS,
+ ORIGINALS,
planGenjutsu,
planMakerPieces,
qualityFor,
@@ -18,300 +23,436 @@ import {
type GenjutsuPlanInput,
type Maker,
} from "@/lib/catalog/genjutsu";
-import { planGeneration } from "@/lib/catalog/plan";
+import { ANCHOR_FALLBACK } from "@/lib/catalog/character-swap";
+import { estimateCost, planGeneration } from "@/lib/catalog/plan";
import { getModel, getPreset } from "@/lib/catalog";
+import { onEngine } from "@/lib/catalog/engines";
+import type { Engine } from "@/lib/catalog/types";
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 maker = (id: string, engine: Engine = "cloud") => getMaker(id, engine)!;
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)!;
+const step = (p: ReturnType<typeof planGenjutsu>, key: string) => {
+ const s = p.steps.find((x) => x.key === key);
+ if (!s) throw new Error(`no step ${key} in ${p.steps.map((x) => x.key).join(", ")}`);
+ return s;
+};
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("each mode's default is its Fuobe Original on both engines, Lite unless Quality is High", () => {
+ for (const engine of ["cloud", "open"] as const) {
+ expect(chooseMaker({ engine, mode: "motion" })).toEqual({ maker: maker(ORIGINALS.motionLite, engine) });
+ expect(chooseMaker({ engine, mode: "motion", tier: "high" })).toEqual({ maker: maker(ORIGINALS.motion, engine) });
+ expect(chooseMaker({ engine, mode: "swap", target: "type" })).toEqual({ maker: maker(ORIGINALS.swapLite, engine) });
+ expect(chooseMaker({ engine, mode: "swap", target: "type", tier: "high" })).toEqual({ maker: maker(ORIGINALS.swap, engine) });
+ expect(chooseMaker({ engine, mode: "restyle", look: { kind: "preset", id: "shorts-claymation" } })).toEqual({ maker: maker(ORIGINALS.restyle, engine) });
+ expect(chooseMaker({ engine, mode: "character" })).toEqual({ maker: maker(ORIGINALS.character, engine) });
+ }
+ // Clicking or painting what to swap is the cloud Original too.
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "paint" })).toMatchObject({ maker: { id: ORIGINALS.swapLite } });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", target: "click" })).toMatchObject({ maker: { id: ORIGINALS.swapLite } });
+ // The picker lists Lite; the full Original is the same choice.
+ expect(makersFor("cloud", "motion").map((m) => m.id)).toEqual([ORIGINALS.motionLite, "scail-2", "wan-motion", "kling-motion-control"]);
+ expect(makersFor("cloud", "motion").map((m) => m.id)).not.toContain(ORIGINALS.motion);
+ });
+
+ it("no Higgsfield model is offered, and old setups naming one open the Original that replaced it", () => {
+ expect(MAKERS.some((m) => m.id.startsWith("genjutsu-"))).toBe(false);
+ // Every maker runs without Higgsfield (Kling's own models may also list Higgsfield as one more provider).
+ expect(MAKERS.every((m) => onEngine(getModel(m.id)!, m.engine).routes.some((r) => r.provider !== "higgsfield"))).toBe(true);
+ expect(chooseMaker({ engine: "cloud", mode: "motion", modelId: "genjutsu-motion-transfer" })).toEqual({ maker: maker(ORIGINALS.motion) });
+ expect(chooseMaker({ engine: "cloud", mode: "swap", modelId: "genjutsu-lite-object-swap" })).toEqual({ maker: maker(ORIGINALS.swapLite) });
+ expect(chooseMaker({ engine: "open", mode: "motion", modelId: "oss-wan22-animate" })).toEqual({ maker: maker(ORIGINALS.motion, "open") });
+ expect(Object.values(LEGACY_MAKERS).every((id) => MAKERS.some((m) => m.id === id))).toBe(true);
});
- 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("partners and other open weights stay as labelled alternatives", () => {
+ const sources = (engine: Engine, mode: "motion" | "character" | "swap" | "restyle" | "insert", target?: "type" | "click" | "paint") =>
+ Object.fromEntries(makersFor(engine, mode, target).map((m) => [m.id, m.source]));
+ expect(sources("cloud", "character")).toEqual({ [ORIGINALS.character]: "original", "scail-2": "open", "h3-max-recast": "partner", "wan-22-animate-replace": "open", "kling-o3": "partner", "p-video-replace": "partner" });
+ expect(sources("cloud", "swap", "type")).toEqual({ [ORIGINALS.swapLite]: "original", "kling-o3": "partner", "p-video-replace": "partner" });
+ expect(sources("cloud", "swap", "paint")).toEqual({ [ORIGINALS.swapLite]: "original", "wan-22-vace-inpaint": "open" });
+ expect(sources("cloud", "restyle")).toEqual({ [ORIGINALS.restyle]: "original", "gemini-omni-flash": "partner", "kling-o3-4k-edit": "partner", "happy-horse-video-edit": "partner" });
+ expect(sources("open", "character", "type")).toEqual({ [ORIGINALS.character]: "original", "oss-h3-character-swap-relay": "open" });
+ // A picked partner runs.
+ expect(chooseMaker({ engine: "cloud", mode: "character", modelId: "h3-max-recast" })).toMatchObject({ maker: { id: "h3-max-recast" } });
});
- 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/) });
- // Higgsfield's looks are cloud-only: said as such, not "nothing does that".
- expect(chooseMaker({ engine: "open", mode: "restyle", look: { kind: "higgsfield", id: "abc" }, higgsfield: true })).toEqual({ problem: OPEN_LOOK_PROBLEM });
+ it("refuses in words what an engine can't do", () => {
+ expect(chooseMaker({ engine: "cloud", mode: "character", target: "click" })).toEqual({ problem: CLOUD_CLICK_PROBLEM });
+ expect(chooseMaker({ engine: "open", mode: "character", target: "click" })).toMatchObject({ maker: { id: ORIGINALS.character, engine: "open" } });
+ expect(chooseMaker({ engine: "open", mode: "swap", target: "paint" })).toEqual({ problem: expect.stringMatching(/name what to swap/) });
+ expect(chooseMaker({ engine: "open", mode: "insert", target: "type" })).toEqual({ problem: expect.stringMatching(/paint where it goes/) });
+ expect(chooseMaker({ engine: "cloud", mode: "character", target: "paint" })).toEqual({ problem: expect.stringMatching(/doesn't take paint/) });
});
- 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);
+ it("every maker is a catalog model that does its mode's operation on its engine", () => {
+ const ops = { motion: "motion-transfer", character: "video-swap", swap: "video-swap", insert: "video-insert", restyle: "v2v" } as const;
+ for (const m of MAKERS) {
+ const model = getModel(m.id);
+ expect(model, m.id).toBeDefined();
+ expect(model!.engines ?? [model!.engine], m.id).toContain(m.engine);
+ const providers = m.engine === "open" ? ["comfyui"] : ["fal", "replicate"];
+ for (const mode of m.modes) expect(model!.routes.some((r) => r.op === ops[mode] && providers.includes(r.provider)), `${m.id} ${m.engine} ${mode}`).toBe(true);
}
+ // The Originals are one model on both engines.
+ for (const id of Object.values(ORIGINALS)) expect(getModel(id)?.engines).toEqual(["open", "cloud"]);
});
});
describe("Genjutsu: checks", () => {
- const base = { mode: "motion" as const, maker: maker("genjutsu-lite-motion-transfer"), source: clip, range: { start: 0, end: 20 }, references: 1 };
+ const base = { mode: "motion" as const, maker: maker(ORIGINALS.motionLite), source: clip, range: { start: 0, end: 20 }, references: 1 };
- it("the source window is 4–30 s", () => {
+ it("the source window is 4–30 s; Character swap's part is 5–15 s (up to 30 s continued)", () => {
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();
+ const ch = { ...base, mode: "character" as const, maker: maker(ORIGINALS.character) };
+ expect(genjutsuProblem({ ...ch, range: { start: 0, end: 4.5 } })).toMatch(/Pick a part of 5–15 seconds/);
+ expect(genjutsuProblem({ ...ch, range: { start: 2, end: 9 } })).toBeNull();
+ expect(genjutsuProblem({ ...ch, range: { start: 2, end: 9 }, seed: 2 ** 33 })).toMatch(/whole-number seed/);
+ expect(genjutsuProblem({ ...ch, range: { start: 2, end: 9 }, references: 0 })).toBe("Add a picture of your character");
+ expect(genjutsuProblem({ ...ch, maker: maker(ORIGINALS.character, "open"), range: { start: 2, end: 9 }, target: "click" })).toBe("Click the person to swap on the first frame");
+ // Recast takes 5–30 s.
+ expect(genjutsuProblem({ ...ch, maker: maker("h3-max-recast"), source: { ...clip, duration: 30 }, range: { start: 0, end: 24 } })).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: "swap", maker: maker(ORIGINALS.swapLite), target: "type" })).toMatch(/Say what to swap/);
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("p-video-replace"), target: "type" })).toBeNull();
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker(ORIGINALS.swapLite), target: "click" })).toMatch(/Click what to swap/);
+ expect(genjutsuProblem({ ...base, mode: "insert", maker: maker("oss-vace-insert", "open"), target: "paint" })).toMatch(/Paint where it goes/);
+ expect(genjutsuProblem({ ...base, mode: "restyle", maker: maker(ORIGINALS.restyle), 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();
+ expect(genjutsuProblem({ ...base, mode: "restyle", maker: maker(ORIGINALS.restyle), references: 0, look: { kind: "soul", id: "v1-general" } })).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/);
- // The hosted VACE is the only model for clicks and paint: the way out is words, not "another model".
- expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("wan-22-vace-inpaint"), source: { ...clip, fps: 60 }, target: "paint", mask: true })).toBe(
- "Wan 2.2 VACE (hosted) takes up to 30 fps (this clip is 60 fps) — switch to “Type it”, or save the clip at 30 fps and add it again",
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker(ORIGINALS.swapLite), source: { ...clip, fps: 60 }, target: "paint", mask: true })).toBe(
+ "Fuobe Genjutsu takes up to 30 fps (this clip is 60 fps) — pick another model",
);
- expect(genjutsuProblem({ ...base, mode: "insert", maker: maker("wan-22-vace-inpaint"), source: { ...clip, fps: 60 }, target: "paint", mask: true })).toMatch(/switch to “Say where”/);
- expect(genjutsuProblem({ ...base, mode: "swap", maker: maker("oss-vace-swap"), source: { ...clip, fps: undefined }, target: "type", subject: "the cup" })).toMatch(/frame rate/);
+ expect(genjutsuProblem({ ...base, mode: "swap", maker: maker(ORIGINALS.swap, "open"), 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 });
+ it("cloud motion on the Original: Wan 2.2 Animate on the whole selection, billed as frames ÷ 16, the sound put back", () => {
+ const p = plan({ maker: maker(ORIGINALS.motion), prompt: "a knight in silver armour", quality: "1080p" });
+ expect(p.pieces).toBe(1);
+ const make = step(p, "make0").request;
+ expect(make).toMatchObject({ modelId: ORIGINALS.motion, engine: "cloud", op: "motion-transfer", feature: "genjutsu-step", inputs: { video: clip.url, images: [ref] } });
+ // 20 s at 30 fps = 600 frames = 37.5 video seconds; 1080p goes to its top, 720p.
+ expect(make.params).toMatchObject({ resolution: "720p", duration: 37.5, sourceDuration: 20 });
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();
+ // $0.08 a video second at 720p: $3.00.
+ expect(estimateCost(onEngine(getModel(ORIGINALS.motion)!, "cloud"), make.params!, 1, "motion-transfer")).toBeCloseTo(3, 6);
+ // Lite: 480p turbo, $0.04.
+ const lite = step(plan({ maker: maker(ORIGINALS.motionLite) }), "make0").request;
+ expect(lite.params).toMatchObject({ resolution: "480p" });
+ expect(estimateCost(onEngine(getModel(ORIGINALS.motionLite)!, "cloud"), lite.params!, 1, "motion-transfer")).toBeCloseTo(1.5, 6);
});
- 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("open motion on the Original: Wan Animate 2 on the cut selection; Lite runs it in 4 steps at 480p", () => {
+ const anim = plan({ maker: maker(ORIGINALS.motion, "open"), 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({ engine: "open", op: "motion-transfer", feature: "genjutsu", params: { aspectRatio: "auto", resolution: "720p" } });
+ expect(anim.final).toBe("make0");
+ const lite = plan({ maker: maker(ORIGINALS.motionLite, "open"), range: { start: 4, end: 14 } });
+ expect(step(lite, "make0").request.params).toMatchObject({ resolution: "480p", extra: { steps: 4 } });
});
- 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("cloud swap on the Original: SAM 3.1 follows what you name, Wan VACE paints into each piece's part of its mask video", () => {
+ const p = plan({ mode: "swap", maker: maker(ORIGINALS.swap), target: "type", subject: "Replace the coffee cup with a red apple", references: [ref, "/api/files/b.png"], range: { start: 2, end: 18 } });
+ expect(p.tracked).toBe(true);
+ expect(step(p, "range").request).toMatchObject({ modelId: "trim-video", params: { startTime: 2, endTime: 18 } });
+ expect(step(p, "track").request).toMatchObject({ modelId: "sam-3-1-video-mask", op: "bg-remove-video", prompt: "the coffee cup" });
+ expect(step(p, "track").request.params?.points).toBeUndefined();
+ // 16 s at 30 fps = 480 frames → two windows of ≤241.
+ expect(p.pieces).toBe(2);
+ expect(step(p, "make1").after).toEqual(["cut1", "mcut1"]);
+ expect(step(p, "make1").chain).toEqual([{ slot: "video" }, { slot: "mask" }]);
+ expect(step(p, "mcut1").after).toEqual(["track"]);
+ expect(step(p, "make0").request).toMatchObject({ modelId: ORIGINALS.swap, engine: "cloud", inputs: { images: [ref, "/api/files/b.png"] }, prompt: "A red apple in place of the coffee cup, matching the light, perspective and motion of the shot." });
+ expect(p.steps.some((s) => s.key.startsWith("mframe"))).toBe(false);
+ // Clicks: the points go to the tracker.
+ const c = plan({ mode: "swap", maker: maker(ORIGINALS.swapLite), target: "click", points: [{ x: 10, y: 20, label: "positive" }], range: { start: 0, end: 6 } });
+ expect(step(c, "track").request.params?.points).toEqual([{ x: 10, y: 20, label: "positive" }]);
+ expect(step(c, "make0").after).toEqual(["range", "track"]);
+ expect(step(c, "make0").request.params).toMatchObject({ resolution: "480p" });
});
- it("hosted VACE swap by paint over several pieces: the paint for the first, SAM 3.1's track for the rest", () => {
+ it("hosted Wan 2.2 VACE by paint over several pieces: the paint for the first, SAM 3.1's first frames 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.
+ it("open swap on the Original: windows straight from the upload, SAM 3.1's words, the first reference only", () => {
+ const p = plan({ mode: "swap", maker: maker(ORIGINALS.swap, "open"), target: "type", subject: "Replace the coffee cup with a red apple", references: [ref, "/api/files/b.png"], quality: "720p" });
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).toMatchObject({ modelId: ORIGINALS.swap, engine: "open", 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("cloud restyle on the Original: per piece the first frame takes the look, then Wan Fun VACE by depth", () => {
+ const p = plan({ mode: "restyle", maker: maker(ORIGINALS.restyle), look: { kind: "preset", id: "shorts-claymation" }, references: [], range: { start: 0, end: 10 } });
+ expect(p.pieces).toBe(2);
+ expect(step(p, "frame0").request).toMatchObject({ modelId: "extract-frame", op: "frame" });
+ expect(step(p, "look0").request).toMatchObject({ modelId: "qwen-image-edit-2511-cloud", op: "edit" });
+ expect(step(p, "look0").request.prompt).toMatch(/claymation/i);
+ expect(step(p, "restyle0").request).toMatchObject({ modelId: ORIGINALS.restyle, engine: "cloud", op: "v2v", params: { aspectRatio: "auto", resolution: "720p" } });
+ expect(step(p, "restyle0").chain).toEqual([{ slot: "video" }, { slot: "images", position: "first" }]);
+ expect(step(p, "final").request.op).toBe("mux");
+ // A Soul look restyles the first frame with its LoRAs (Fuobe Soul's edit).
+ const soul = plan({ mode: "restyle", maker: maker(ORIGINALS.restyle), look: { kind: "soul", id: "v1-general" }, references: [], range: { start: 0, end: 6 } });
+ expect(step(soul, "look0").request).toMatchObject({ modelId: "fuobe-soul", engine: "cloud", op: "edit", presetId: "v1-general" });
});
- 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("open restyle on the Original: the Shorts chain on the Original's graph; a Soul look's frame on Fuobe Soul", () => {
+ const open = plan({ mode: "restyle", maker: maker(ORIGINALS.restyle, "open"), look: { kind: "custom", images: [ref, "/api/files/b.png", "/api/files/c.png"] }, references: [] });
+ expect(open.steps.find((s) => s.request.modelId === "oss-segment")!.request.params?.aspectRatio).toBe("auto");
+ expect(open.steps.find((s) => s.request.modelId === "oss-qwen-edit")!.request.inputs?.images).toEqual([ref, "/api/files/b.png"]);
+ const look = open.steps.find((s) => s.request.modelId === ORIGINALS.restyle)!.request;
+ expect(look).toMatchObject({ engine: "open", op: "v2v" });
+ const soul = plan({ mode: "restyle", maker: maker(ORIGINALS.restyle, "open"), look: { kind: "soul", id: "v1-general" }, references: [], range: { start: 0, end: 5 } });
+ const frame = soul.steps.find((s) => s.key.startsWith("frame"))!.request;
+ expect(frame).toMatchObject({ modelId: "fuobe-soul", engine: "open", op: "edit", presetId: "v1-general" });
+ expect(frame.inputs).toBeUndefined();
});
- 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: [] });
+ it("partners still restyle through the Shorts chain in the clip's own shape", () => {
+ const p = plan({ mode: "restyle", maker: maker("gemini-omni-flash"), look: { kind: "soul", id: "v1-general" }, 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)", () => {
+ 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(s.final).toBe("make0");
+ expect(makerStepUsd("kling-o3", { duration: 10 })).toBeCloseTo(1.68, 6);
+ });
+});
+
+describe("Genjutsu: Character swap", () => {
+ const ch = (o: Partial<GenjutsuPlanInput> & { maker: Maker }) => plan({ mode: "character", range: { start: 2, end: 12 }, quality: "768p", seed: 42, ...o });
+
+ it("open: the part's first frame, your character put in it, then the H3 swap with the anchor as Picture 2", () => {
+ const p = ch({ maker: maker(ORIGINALS.character, "open"), prompt: "keep the glasses", character: { description: "a chrome robot", who: "leftmost", maskGrow: 80, lora: "v1", windowFrames: 158, historyFrames: 18 } });
+ expect(p.steps.map((s) => s.key)).toEqual(["frame", "anchor", "swap"]);
+ expect(step(p, "frame").request).toMatchObject({ modelId: "oss-extract-frame", op: "frame", inputs: { video: clip.url }, params: { startTime: 2, endTime: 2.5, extra: { frameIndex: 0 } } });
+ expect(step(p, "anchor").request).toMatchObject({ modelId: "oss-qwen-edit", op: "edit", inputs: { images: [ref] } });
+ expect(step(p, "anchor").request.prompt).toMatch(/^Image 1 is the source frame to edit\. Image 2 is character identity only: a chrome robot/);
+ expect(step(p, "anchor").chain).toEqual([{ slot: "images", position: "first" }]);
+ const swap = step(p, "swap");
+ expect(swap.request).toMatchObject({
+ modelId: ORIGINALS.character,
+ engine: "open",
+ op: "video-swap",
+ feature: "genjutsu",
+ inputs: { video: clip.url, images: [ref] },
+ params: { startTime: 2, endTime: 12, resolution: "768p", seed: 42, extra: { selection: "leftmost", subjectIndex: 0, maskGrow: 80, lora: "v1", windowFrames: 158, historyFrames: 18 } },
+ });
+ expect(swap.request.prompt).toMatch(/^Replace the selected person in <Video 1> with the character in <Picture 1>\. .*Start from the first frame in <Picture 2>\. The character: a chrome robot\. Keep the glasses\.$/);
+ // The anchor is optional: without it the swap runs with the prompt that doesn't name it, and says so.
+ expect(swap.after).toEqual(["anchor"]);
+ expect(swap.chain).toEqual([{ slot: "images", position: "last", optional: { prompt: expect.not.stringContaining("Picture 2"), notice: ANCHOR_FALLBACK } }]);
+ // The graph keeps the clip's sound: the swap is the result.
+ expect(p.final).toBe("swap");
+ expect(p.sound).toBe(false);
+ expect(p.anchors).toBe(1);
+ });
+
+ it("open: the anchor switch, clicks and the Relay graph (no anchor)", () => {
+ const off = ch({ maker: maker(ORIGINALS.character, "open"), character: { anchor: false }, points: [{ x: 300, y: 200, label: "positive" }] });
+ expect(off.steps.map((s) => s.key)).toEqual(["swap"]);
+ expect(step(off, "swap").request.params?.points).toEqual([{ x: 300, y: 200, label: "positive" }]);
+ expect(step(off, "swap").request.prompt).not.toMatch(/Picture 2/);
+ expect(off.anchors).toBe(0);
+ const relay = ch({ maker: maker("oss-h3-character-swap-relay", "open") });
+ expect(relay.steps.map((s) => s.key)).toEqual(["swap"]);
+ expect(step(relay, "swap").request).toMatchObject({ modelId: "oss-h3-character-swap-relay" });
+ // A part longer than 15 s is one prompt on your GPU (the graph continues window by window).
+ const long = ch({ maker: maker(ORIGINALS.character, "open"), range: { start: 0, end: 20 } });
+ expect(long.steps.filter((s) => s.request.op === "video-swap").length).toBe(1);
+ });
+
+ it("cloud: the part cut, its anchor, then fal's H3 with the swap LoRA; whole seconds trimmed back; the clip's sound put back", () => {
+ const p = ch({ maker: maker(ORIGINALS.character), range: { start: 2, end: 9.4 }, quality: "1080p", character: { who: "rightmost" } });
+ expect(p.steps.map((s) => s.key)).toEqual(["cut0", "frame0", "anchor0", "swap0", "fit0", "sound", "final"]);
+ expect(step(p, "anchor0").request).toMatchObject({ modelId: "gpt-image-2-5-sunburst", op: "edit", params: { extra: { quality: "low" } } });
+ const swap = step(p, "swap0");
+ expect(swap.request).toMatchObject({ modelId: ORIGINALS.character, engine: "cloud", op: "video-swap", inputs: { images: [ref] }, params: { duration: 8, sourceDuration: 7.4, resolution: "768p", seed: 42 } });
+ expect(swap.request.loras).toEqual([expect.objectContaining({ file: "h3_character_swap_v1.5.safetensors", weightName: "h3_character_swap_v1.5.safetensors", strength: 1 })]);
+ expect(swap.request.prompt).toMatch(/^Replace the person on the right in Video 1 with the character in Image 1\. .*Image 2\.$/);
+ expect(swap.after).toEqual(["cut0", "anchor0"]);
+ expect(swap.chain).toEqual([{ slot: "video" }, { slot: "images", position: "last", optional: { prompt: expect.any(String), notice: ANCHOR_FALLBACK } }]);
+ expect(step(p, "fit0").request).toMatchObject({ modelId: "trim-video", params: { startTime: 0, endTime: 7.4 } });
+ expect(step(p, "final").request).toMatchObject({ op: "mux", feature: "genjutsu" });
+ // $0.075 a second at 768p on 8 whole seconds; 480p $0.0625.
+ expect(estimateCost(onEngine(getModel(ORIGINALS.character)!, "cloud"), swap.request.params!, 1, "video-swap")).toBeCloseTo(0.6, 6);
+ expect(estimateCost(onEngine(getModel(ORIGINALS.character)!, "cloud"), { ...swap.request.params!, resolution: "480p" }, 1, "video-swap")).toBeCloseTo(0.5, 6);
+ });
+
+ it("cloud: a part over 15 s runs as pieces of 5–15 s, each with its own anchor, joined", () => {
+ const p = ch({ maker: maker(ORIGINALS.character), range: { start: 0, end: 20 }, character: { anchorModel: "nano-banana-pro" } });
+ expect(p.pieces).toBe(2);
+ expect(p.anchors).toBe(2);
+ expect(step(p, "anchor1").request.modelId).toBe("nano-banana-pro");
+ expect(step(p, "swap0").request.params).toMatchObject({ duration: 10, sourceDuration: 10 });
+ expect(p.steps.some((s) => s.key.startsWith("fit"))).toBe(false);
+ expect(step(p, "join").after).toEqual(["swap0", "swap1"]);
+ });
+
+ it("partners in Character swap: MiniMax's Recast, Wan Animate Replace, Kling O3 with who in words", () => {
+ const r = ch({ maker: maker("h3-max-recast"), range: { start: 2, end: 20 }, quality: "1080p", character: { who: "leftmost", description: "a ronin" } });
+ expect(r.steps.map((s) => s.key)).toEqual(["cut0", "make0"]);
+ expect(step(r, "make0").request).toMatchObject({ modelId: "h3-max-recast", op: "video-swap", params: { resolution: "1080p" } });
+ expect(step(r, "make0").request.prompt).toBe("The person on the left becomes the person in the photo, a ronin.");
+ expect(r.final).toBe("make0");
+ const w = ch({ maker: maker("wan-22-animate-replace") });
+ expect(step(w, "make0").request).toMatchObject({ op: "video-swap", params: { resolution: "720p" } });
+ expect(w.final).toBe("final");
+ expect(makerPrompt({ mode: "character", maker: maker("kling-o3"), refs: 1, character: { who: "rightmost" } })).toBe(
+ "Replace the person on the right in @Video1 with @Image1. Keep everything else the same: the performance, camera, framing, light and timing.",
+ );
+ });
+
+ it("the H3 settings the open graph takes", () => {
+ expect(h3Extra(undefined)).toEqual({ selection: "largest", subjectIndex: 0 });
+ expect(h3Extra({ who: "index", index: 2, subject: "man in red", audioGuide: false, useMask: false, lora: "none" })).toEqual({
+ selection: "index",
+ subjectIndex: 2,
+ maskPrompt: "man in red",
+ audioGuide: false,
+ useMask: false,
+ lora: "none",
+ });
+ });
+
+ it("qualities: 480p or 768p for H3, Recast's 768p / 1080p", () => {
+ expect(qualityFor(maker(ORIGINALS.character), "720p")).toBe("768p");
+ expect(qualityFor(maker(ORIGINALS.character, "open"), "480p")).toBe("480p");
+ expect(qualityFor(maker("h3-max-recast"), "480p")).toBe("768p");
+ expect(resolutionWords(maker("h3-max-recast"), "480p")).toBe("renders 768p (its lowest)");
+ });
+});
+
+describe("Genjutsu: the steps plan as catalog generations", () => {
+ it("every step of every mode on both engines is a request the catalog accepts", () => {
const plans = [
- plan({ maker: maker("genjutsu-lite-motion-transfer") }),
+ plan({ maker: maker(ORIGINALS.motionLite) }),
+ plan({ maker: maker(ORIGINALS.motion, "open"), range: { start: 0, end: 10 } }),
+ plan({ maker: maker("scail-2") }),
+ plan({ maker: maker("wan-motion") }),
plan({ maker: maker("kling-motion-control") }),
- plan({ mode: "swap", maker: maker("genjutsu-lite-object-swap"), target: "type" }),
+ plan({ mode: "swap", maker: maker(ORIGINALS.swap), target: "type", subject: "the cup", range: { start: 0, end: 10 } }),
+ plan({ mode: "swap", maker: maker(ORIGINALS.swapLite), target: "click", points: [{ x: 1, y: 2, label: "positive" }], range: { start: 0, end: 6 } }),
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: [] }),
+ plan({ mode: "swap", maker: maker(ORIGINALS.swap, "open"), target: "type", subject: "the cup", range: { start: 0, end: 6 } }),
+ plan({ mode: "insert", maker: maker("oss-vace-insert", "open"), target: "paint", mask: "/api/files/m.png", range: { start: 0, end: 6 } }),
+ plan({ mode: "restyle", maker: maker(ORIGINALS.restyle), look: { kind: "soul", id: "v1-general" }, references: [], range: { start: 0, end: 6 } }),
+ plan({ mode: "restyle", maker: maker(ORIGINALS.restyle), look: { kind: "preset", id: "shorts-claymation" }, references: [], range: { start: 0, end: 6 } }),
+ plan({ mode: "restyle", maker: maker(ORIGINALS.restyle, "open"), look: { kind: "soul", id: "v1-general" }, references: [], range: { start: 0, end: 5 } }),
+ plan({ mode: "character", maker: maker(ORIGINALS.character), range: { start: 0, end: 12 }, quality: "768p" }),
+ plan({ mode: "character", maker: maker(ORIGINALS.character, "open"), range: { start: 0, end: 12 }, quality: "480p" }),
+ plan({ mode: "character", maker: maker("h3-max-recast"), range: { start: 0, end: 12 } }),
+ plan({ mode: "character", maker: maker("scail-2"), range: { start: 0, end: 8 } }),
+ plan({ mode: "character", maker: maker("oss-h3-character-swap-relay", "open"), range: { start: 0, end: 8 } }),
];
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 chained: Record<string, unknown> = {};
+ for (const c of s.chain ?? []) {
+ if (c.slot === "videos") chained.videos = ["/api/files/x.mp4", "/api/files/y.mp4"];
+ else if (c.slot === "images") chained.images = [...((chained.images as string[]) ?? s.request.inputs?.images ?? []), "/api/files/x.png"];
+ else chained[c.slot] = "/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();
}
}
});
+
+ it("billed seconds: fal's video seconds count 16 (Wan Motion 24) frames a second at the clip's own rate", () => {
+ const piece = { index: 0, start: 0, end: 10 };
+ expect(billedSeconds(maker(ORIGINALS.motion), piece, 30)).toBeCloseTo(18.75, 6);
+ expect(billedSeconds(maker("wan-motion"), piece, 30)).toBeCloseTo(12.5, 6);
+ expect(billedSeconds(maker("kling-motion-control"), piece, 30)).toBe(10);
+ expect(billedSeconds(maker(ORIGINALS.swap), { ...piece, frames: 241 }, 30)).toBeCloseTo(241 / 16, 6);
+ });
});
-describe("Genjutsu: words and qualities", () => {
+describe("Genjutsu: words", () => {
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();
- });
-
- it("says what comes out when it isn't the quality picked", () => {
- // Above the pick is the model's lowest, below it the most it renders.
- expect(resolutionWords(maker("p-video-replace"), "480p")).toBe("renders 720p (its lowest)");
- expect(resolutionWords(maker("gemini-omni-flash"), "480p")).toBe("renders 720p (its lowest)");
- expect(resolutionWords(maker("wan-22-vace-inpaint"), "1080p")).toBe("renders up to 720p");
- expect(resolutionWords(maker("genjutsu-lite-motion-transfer"), "1080p")).toBeUndefined();
- // No setting: each model's own words.
- expect(resolutionWords(maker("kling-o3"), "720p")).toBe("keeps your clip's size");
- expect(resolutionWords(maker("kling-o3-4k-edit"), "720p")).toBe("renders 4K");
- expect(resolutionWords(maker("oss-wan22-vace-restyle"), "1080p")).toBe("renders 480p at 16 fps");
- expect(resolutionWords(maker("kling-motion-control"), "720p")).toBe("picks its own size");
+ it("optional words stay optional", () => {
+ expect(makerPrompt({ mode: "swap", maker: maker("p-video-replace"), refs: 2 })).toBeUndefined();
+ expect(makerPrompt({ mode: "motion", maker: maker(ORIGINALS.motion), refs: 1 })).toBeUndefined();
+ expect(makerPrompt({ mode: "character", maker: maker("p-video-replace"), refs: 1 })).toBeUndefined();
});
});
describe("Genjutsu: setup codes", () => {
- it("round-trips a setup through a short code", () => {
+ it("round-trips a setup, Character swap's settings included (not the part's words)", () => {
const setup = {
- mode: "swap" as const,
- engine: "cloud" as const,
- model: "genjutsu-lite-object-swap",
- tier: "high" as const,
- quality: "1080p" as const,
+ mode: "character" as const,
+ engine: "open" as const,
+ model: ORIGINALS.character,
+ quality: "768p" as const,
target: "type" as const,
- subject: "the red jacket — ünïcode",
- prompt: "a yellow raincoat",
- references: [ref, "/api/files/b.png"],
+ prompt: "keep the glasses — ünïcode",
+ references: [ref],
+ character: { who: "index" as const, index: 2, subject: "man in red", anchor: false, description: "a ronin", speech: "other" as const, lora: "v1" as const, windowFrames: 158 },
};
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);
+ expect(decodeSetup(encodeSetup({ mode: "character", character: { dialogue: "secret words", who: "largest" } as never }))?.character).toEqual({ who: "largest" });
});
- it("keeps looks and drops what isn't valid", () => {
+ it("keeps looks, maps old models to the Originals and drops what isn't valid (Higgsfield's looks too)", () => {
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: "soul", id: "v1-general" } }))?.look).toEqual({ kind: "soul", id: "v1-general" });
expect(decodeSetup(encodeSetup({ mode: "restyle", look: { kind: "preset", id: "nope" } }))?.look).toBeUndefined();
+ const old = `gj1.${btoa(JSON.stringify({ m: "restyle", x: "genjutsu-restyle", l: { k: "h", id: "9b1c", n: "Anime" } }))}`;
+ expect(decodeSetup(old)).toEqual({ mode: "restyle", model: ORIGINALS.restyle });
+ expect(decodeSetup(`gj1.${btoa(JSON.stringify({ m: "motion", x: "genjutsu-lite-motion-transfer", t: "high" }))}`)).toEqual({ mode: "motion", model: ORIGINALS.motionLite, tier: "high" });
expect(decodeSetup(encodeSetup({ mode: "motion", target: "paint", model: "not-a-model" }))).toEqual({ mode: "motion" });
expect(decodeSetup("gj1.!!!")).toBeNull();
- // A link with a broken %-escape is no code (it doesn't throw).
expect(decodeSetup("https://x/genjutsu?setup=%E0%A4%A")).toBeNull();
- expect(decodeSetup("hello")).toBeNull();
expect(decodeSetup(`gj1.${btoa(JSON.stringify({ m: "fly" }))}`)).toBeNull();
});
});
diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.json
index 7f3e07e5..c86defc9 100644
--- a/workflows/comfyui/manifest.json
+++ b/workflows/comfyui/manifest.json
@@ -1,6 +1,6 @@
{
"version": 1,
- "generatedAt": "2026-10-26T09:24:31.157Z",
+ "generatedAt": "2026-10-27T04:10:33.286Z",
"comfyuiCommit": "fc04da91b2ab12f99e4716371a7e4f98ac982597",
"comfyuiVersion": "0.41.0",
"workflowTemplatesVersion": "0.11.86",
@@ -13018,6 +13018,473 @@
"validated": true,
"notes": "mask = the region where the new object should appear, a PNG in the clip's shape read from the red channel (white = the region, black = keep), scaled (not cropped) to the work size; it is held for every frame of the window (RepeatImageBatch), so it suits a static or slow camera (without the repeat WanVaceToVideo would pad a one-frame mask with 1 = generate and regenerate the whole clip). image = the object (best cut out on white); prompt = what appears where and what it does. No SAM. Changed from the research graph: the mask is read from the red channel (Fuobe's mask convention) instead of alpha. Window rules (startTime / duration in seconds, at most 81 frames), the work-size budget, paste-back and the kept sound as video-inpaint-wan-vace. Validated by /prompt only (no GPU here)."
},
+ {
+ "id": "video-character-swap-h3",
+ "title": "Character swap: SAM 3.1 picks the person, MiniMax H3 + the Character Swap LoRA regenerate only them (h3_character_swap pack)",
+ "capability": "video-character-swap",
+ "file": "video-character-swap-h3.json",
+ "source": "hand-built (scripts/comfy/hand-built/video-character-swap-h3.json)",
+ "bindings": {
+ "video": [
+ {
+ "node": "30",
+ "input": "file"
+ }
+ ],
+ "image": [
+ {
+ "node": "9",
+ "input": "image"
+ }
+ ],
+ "image2": [
+ {
+ "node": "anchor_image",
+ "input": "image"
+ }
+ ],
+ "startTime": [
+ {
+ "node": "trim",
+ "input": "start_time"
+ }
+ ],
+ "duration": [
+ {
+ "node": "trim",
+ "input": "duration"
+ },
+ {
+ "node": "31",
+ "input": "duration_seconds"
+ }
+ ],
+ "quality": [
+ {
+ "node": "31",
+ "input": "resolution"
+ }
+ ],
+ "prompt": [
+ {
+ "node": "801",
+ "input": "prompt"
+ }
+ ],
+ "seed": [
+ {
+ "node": "801",
+ "input": "seed"
+ }
+ ],
+ "steps": [
+ {
+ "node": "801",
+ "input": "steps"
+ }
+ ],
+ "cfg": [
+ {
+ "node": "801",
+ "input": "cfg"
+ }
+ ],
+ "audioGuide": [
+ {
+ "node": "801",
+ "input": "audio_guide"
+ }
+ ],
+ "maskPrompt": [
+ {
+ "node": "101",
+ "input": "text"
+ }
+ ],
+ "selection": [
+ {
+ "node": "104",
+ "input": "selection"
+ }
+ ],
+ "subjectIndex": [
+ {
+ "node": "104",
+ "input": "index"
+ }
+ ],
+ "maskGrow": [
+ {
+ "node": "110",
+ "input": "expansion_px"
+ }
+ ],
+ "positiveCoords": [
+ {
+ "node": "103",
+ "input": "positive_coords"
+ }
+ ],
+ "negativeCoords": [
+ {
+ "node": "103",
+ "input": "negative_coords"
+ }
+ ],
+ "useMask": [
+ {
+ "node": "803",
+ "input": "use_mask"
+ }
+ ],
+ "windowFrames": [
+ {
+ "node": "805",
+ "input": "window_frames"
+ }
+ ],
+ "historyFrames": [
+ {
+ "node": "805",
+ "input": "history_frames"
+ }
+ ],
+ "lora": [
+ {
+ "node": "850",
+ "input": "lora_name"
+ }
+ ],
+ "loraStrength": [
+ {
+ "node": "850",
+ "input": "strength_model"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "809",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "809",
+ "kind": "video"
+ }
+ ],
+ "defaults": {
+ "steps": 8,
+ "cfg": 1,
+ "duration": 5,
+ "loraStrength": 1,
+ "startTime": 0,
+ "maskGrow": 64,
+ "quality": "768",
+ "maskPrompt": "person",
+ "selection": "largest",
+ "subjectIndex": 0,
+ "audioGuide": true,
+ "useMask": true,
+ "windowFrames": "124",
+ "historyFrames": "18",
+ "lora": "h3_character_swap_v1.5.safetensors"
+ },
+ "limits": {
+ "maxDurationSec": 30,
+ "maxFrames": 3592
+ },
+ "models": [
+ {
+ "file": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "sizeGb": 20.97
+ },
+ {
+ "file": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "sizeGb": 1.96
+ },
+ {
+ "file": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "folder": "text_encoders",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "sizeGb": 15.69
+ },
+ {
+ "file": "minimax_h3_video_vae_fp16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_video_vae_fp16.safetensors",
+ "sizeGb": 5.21
+ },
+ {
+ "file": "minimax_h3_audio_vae_fp32.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_audio_vae_fp32.safetensors",
+ "sizeGb": 0.61
+ },
+ {
+ "file": "sam3.1_multiplex_fp16.safetensors",
+ "folder": "checkpoints",
+ "url": "https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors",
+ "sizeGb": 1.75
+ },
+ {
+ "file": "h3_character_swap_v1.5.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/d06323b7c8e70e97cdab48b78a1e05f786c8cba9/h3_character_swap_v1.5.safetensors",
+ "sizeGb": 0.16
+ },
+ {
+ "file": "h3_character_swap_pro4500_1000.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/a665bb7e3bb9804e487d2925f67744f554c8ad49/h3_character_swap_pro4500_1000.safetensors",
+ "sizeGb": 0.16,
+ "optional": true
+ }
+ ],
+ "customNodes": [
+ {
+ "name": "h3_character_swap",
+ "repo": "https://github.com/akatz-labs/h3-character-swap-tool/tree/0670e4fdf95adf2262caa4b81afed2a9c4ae4b7b/worker_nodes/h3_character_swap"
+ }
+ ],
+ "vramGb": 24,
+ "license": "MiniMax H3 Community License (H3 Ref2VA, its video and audio VAEs, the packaged Qwen3-VL text encoder, Akatz Labs' Character Swap LoRA): territory EXCLUDES the US, the EU, the UK and South Korea; commercial use above US$20M yearly revenue needs MiniMax's written authorization; show \"MiniMax H3\" on the product's interface; no outputs used to improve other AI models · Qwen3-VL-32B base Apache-2.0 · SAM 3.1 under Meta's SAM License (commercial use allowed under its terms) · FL2V Turbo LoRA Apache-2.0 at the pinned revision · h3_character_swap nodes GPL-3.0 (Akatz Labs; NVIDIA INT8 kernel derivative Apache-2.0)",
+ "validated": false,
+ "notes": "Genjutsu \"Character swap\" on the open engine (Openjutsu, comfy-openjutsu @ 70ec62d; Akatz Labs h3-character-swap-tool @ 0670e4f). video = the clip, image = the character, image2 = the anchor first frame (absent: the provider deletes anchor_image and anchor_fit, unlinks 803.anchor and sets 803.use_anchor false); startTime / duration pick the part (trim and 31.duration_seconds both get the length, 5-15 s; up to 30 s plans more windows, beyond H3's trained range). quality \"480\" | \"768\" (strings: the unpatched pack; Openjutsu's patched pack takes integers). prompt in H3's reference tags (<Video 1> the clip, <Picture 1> the character, <Picture 2> the anchor). Who to swap: maskPrompt (SAM words, \"person\"), selection largest | leftmost | rightmost | index with subjectIndex, or clicks as positiveCoords / negativeCoords (JSON pixel points on the prepared first frame). lora V1.5 (h3_character_swap_v1.5) or V1 (h3_character_swap_pro4500_1000); \"none\" deletes node 850 and feeds 800.model from the Turbo LoRA (node 4). 8 steps, CFG 1, er_sde / normal for the FL2V Turbo LoRA; windows 124 frames with 18 of history (17n+5 / 0, 1, 17n+1). The clip's own sound is put back by the pack (807) and kept by CreateVideo; the pack also writes its own MP4 under output/H3-Character-Swap. Needs FFmpeg and FFprobe on PATH. Tested by its authors on a 96 GB RTX PRO 6000 (Comfy) and a 24 GB RTX 4090 with 128 GB RAM and model offloading (Akatz); NVFP4 text encoding runs natively on compute capability 10+ (Blackwell), slower elsewhere. 46.33 GB of weights. Not validated here: the h3_character_swap nodes are not installed on this server (the 22 core nodes were checked against /object_info, docs/research/openjutsu-6.md §3.3).",
+ "validationError": "HTTP 400: missing_node_type: Node 'Prepare · 24 fps / pixel budget' not found. The custom node may not be installed. (Node ID '#31')"
+ },
+ {
+ "id": "video-character-swap-h3-relay",
+ "title": "Character swap on H3 Relay 2.0: SAM 3.1 subject, MiniMax H3 + the Character Swap LoRA in native loop windows (h3-relay pack)",
+ "capability": "video-character-swap",
+ "file": "video-character-swap-h3-relay.json",
+ "source": "hand-built (scripts/comfy/hand-built/video-character-swap-h3-relay.json)",
+ "bindings": {
+ "video": [
+ {
+ "node": "source",
+ "input": "file"
+ }
+ ],
+ "image": [
+ {
+ "node": "reference",
+ "input": "image"
+ }
+ ],
+ "startTime": [
+ {
+ "node": "trim",
+ "input": "start_time"
+ }
+ ],
+ "duration": [
+ {
+ "node": "trim",
+ "input": "duration"
+ },
+ {
+ "node": "prepare",
+ "input": "duration_seconds"
+ }
+ ],
+ "quality": [
+ {
+ "node": "prepare",
+ "input": "resolution"
+ }
+ ],
+ "prompt": [
+ {
+ "node": "reference_conditioning",
+ "input": "prompt"
+ }
+ ],
+ "seed": [
+ {
+ "node": "plan",
+ "input": "seed"
+ }
+ ],
+ "steps": [
+ {
+ "node": "schedule",
+ "input": "steps"
+ }
+ ],
+ "cfg": [
+ {
+ "node": "guider",
+ "input": "cfg"
+ }
+ ],
+ "audioGuide": [
+ {
+ "node": "history",
+ "input": "target_audio_guide"
+ }
+ ],
+ "maskPrompt": [
+ {
+ "node": "subject",
+ "input": "text"
+ }
+ ],
+ "selection": [
+ {
+ "node": "select",
+ "input": "selection"
+ }
+ ],
+ "subjectIndex": [
+ {
+ "node": "select",
+ "input": "index"
+ }
+ ],
+ "maskGrow": [
+ {
+ "node": "expand_mask",
+ "input": "expansion_px"
+ }
+ ],
+ "positiveCoords": [
+ {
+ "node": "detect",
+ "input": "positive_coords"
+ }
+ ],
+ "negativeCoords": [
+ {
+ "node": "detect",
+ "input": "negative_coords"
+ }
+ ],
+ "windowFrames": [
+ {
+ "node": "plan",
+ "input": "window_frames"
+ }
+ ],
+ "historyFrames": [
+ {
+ "node": "plan",
+ "input": "history_frames"
+ }
+ ],
+ "lora": [
+ {
+ "node": "adapter",
+ "input": "lora_name"
+ }
+ ],
+ "loraStrength": [
+ {
+ "node": "adapter",
+ "input": "strength_model"
+ }
+ ],
+ "filenamePrefix": [
+ {
+ "node": "save",
+ "input": "filename_prefix"
+ }
+ ]
+ },
+ "outputs": [
+ {
+ "node": "save",
+ "kind": "video"
+ }
+ ],
+ "defaults": {
+ "steps": 8,
+ "cfg": 1,
+ "duration": 5,
+ "loraStrength": 1,
+ "startTime": 0,
+ "maskGrow": 64,
+ "quality": "768",
+ "maskPrompt": "person",
+ "selection": "largest",
+ "subjectIndex": 0,
+ "audioGuide": true,
+ "windowFrames": "124",
+ "historyFrames": "18",
+ "lora": "h3_character_swap_v1.5.safetensors"
+ },
+ "limits": {
+ "maxDurationSec": 30,
+ "maxFrames": 3592
+ },
+ "models": [
+ {
+ "file": "h3_character_swap_v1.5.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/d06323b7c8e70e97cdab48b78a1e05f786c8cba9/h3_character_swap_v1.5.safetensors",
+ "sizeGb": 0.16
+ },
+ {
+ "file": "minimax_h3_audio_vae_fp32.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_audio_vae_fp32.safetensors",
+ "sizeGb": 0.61
+ },
+ {
+ "file": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "folder": "diffusion_models",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/diffusion_models/minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "sizeGb": 20.97
+ },
+ {
+ "file": "sam3.1_multiplex_fp16.safetensors",
+ "folder": "checkpoints",
+ "url": "https://huggingface.co/Comfy-Org/sam3.1/resolve/7bb8374780a725b4353ed31f3a9395c9742b5621/checkpoints/sam3.1_multiplex_fp16.safetensors",
+ "sizeGb": 1.75
+ },
+ {
+ "file": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "folder": "text_encoders",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "sizeGb": 15.69
+ },
+ {
+ "file": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/lightx2v/Minimax-h3-Turbo/resolve/3ec17a324ced54151364f24f8b5fb6bf7e26414f/minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "sizeGb": 1.96
+ },
+ {
+ "file": "minimax_h3_video_vae_fp16.safetensors",
+ "folder": "vae",
+ "url": "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/1c41cfca8ebba91d0af792a05c5761fb2c3a7975/vae/minimax_h3_video_vae_fp16.safetensors",
+ "sizeGb": 5.21
+ },
+ {
+ "file": "h3_character_swap_pro4500_1000.safetensors",
+ "folder": "loras",
+ "url": "https://huggingface.co/akatz-ai/MiniMax-H3-Character-Swap-LoRA/resolve/a665bb7e3bb9804e487d2925f67744f554c8ad49/h3_character_swap_pro4500_1000.safetensors",
+ "sizeGb": 0.16,
+ "optional": true
+ }
+ ],
+ "customNodes": [
+ {
+ "name": "h3-relay",
+ "repo": "https://github.com/akatz-ai/h3-relay"
+ }
+ ],
+ "vramGb": 24,
+ "license": "MiniMax H3 Community License (H3 Ref2VA, its video and audio VAEs, the packaged Qwen3-VL text encoder, Akatz Labs' Character Swap LoRA): territory EXCLUDES the US, the EU, the UK and South Korea; commercial use above US$20M yearly revenue needs MiniMax's written authorization; show \"MiniMax H3\" on the product's interface; no outputs used to improve other AI models · Qwen3-VL-32B base Apache-2.0 · SAM 3.1 under Meta's SAM License (commercial use allowed under its terms) · FL2V Turbo LoRA Apache-2.0 at the pinned revision · H3 Relay nodes GPL-3.0 (Sendy Software LLC and contributors; vendored Context Loop and Spectrum GPL-3.0); the graph is H3 Relay's example workflow (GPL-3.0 repository)",
+ "validated": false,
+ "notes": "Akatz Labs' newer route for the same swap (h3-relay @ e2a7665b, 2.0.1; example_workflows/toolkit/H3-Character-Swap.api.json, which Akatz's tool ships at 5f83374). Changed: a Trim Video node picks the part, the mask preview is removed, the adapter loads the V1.5 file by its Hugging Face name. Bindings as video-character-swap-h3 without an anchor frame or a masked-generation switch; lora \"none\" deletes the adapter and feeds its users from the Turbo LoRA. H3 Relay registers HTTP routes and an in-memory H3 layout compatibility layer on import: run it on the isolated worker if you prefer (install-comfyui.sh installs it with H3_RELAY=1). Needs FFmpeg and FFprobe on PATH. Not validated here: the pack is not installed on this server.",
+ "validationError": "HTTP 400: missing_node_type: Node 'H3RelayAppendWindow' not found. The custom node may not be installed. (Node ID '#append')"
+ },
{
"id": "kenburns-still",
"title": "Ken Burns pan and zoom over a still for N seconds at F fps (core loops, chunk-encoded, no model)",
diff --git a/workflows/comfyui/object_info.subset.json b/workflows/comfyui/object_info.subset.json
index a6dd9937..1a43467a 100644
--- a/workflows/comfyui/object_info.subset.json
+++ b/workflows/comfyui/object_info.subset.json
@@ -5962,6 +5962,28 @@
"has_intermediate_output": false,
"search_aliases": []
},
+ "H3CharacterSwapAssemble": null,
+ "H3CharacterSwapController": null,
+ "H3CharacterSwapExpandMask": null,
+ "H3CharacterSwapModels": null,
+ "H3CharacterSwapPrepareVideo": null,
+ "H3CharacterSwapRecoverMasks": null,
+ "H3CharacterSwapSelectSubject": null,
+ "H3CharacterSwapSettings": null,
+ "H3CharacterSwapShot": null,
+ "H3CharacterSwapWindowPlan": null,
+ "H3RelayAppendWindow": null,
+ "H3RelayApplyEditMask": null,
+ "H3RelayApplyHistory": null,
+ "H3RelayExpandMask": null,
+ "H3RelayFinishWindows": null,
+ "H3RelayPrepareSource": null,
+ "H3RelayRecoverMasks": null,
+ "H3RelaySamplingMemory": null,
+ "H3RelaySelectMask": null,
+ "H3RelayTextMemory": null,
+ "H3RelayWindowInputs": null,
+ "H3RelayWindowPlan": null,
"Hunyuan3Dv2Conditioning": {
"input": {
"required": {
@@ -10880,6 +10902,363 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "MiniMaxH3AddGuide": {
+ "input": {
+ "required": {
+ "positive": [
+ "CONDITIONING",
+ {}
+ ],
+ "latent": [
+ "LATENT",
+ {}
+ ],
+ "frame_idx": [
+ "INT",
+ {
+ "tooltip": "Frame index to anchor the image or the clip's first frame at. Negative values are counted from the end of the video.",
+ "default": 0,
+ "min": -9999,
+ "max": 9999
+ }
+ ]
+ },
+ "optional": {
+ "vae": [
+ "VAE",
+ {
+ "tooltip": "Video VAE, needed when an image is connected."
+ }
+ ],
+ "audio_vae": [
+ "VAE",
+ {
+ "tooltip": "Audio VAE, needed when an audio is connected."
+ }
+ ],
+ "image": [
+ "IMAGE",
+ {
+ "tooltip": "Image or video frames to anchor. Multi-frame batches are anchored as a clip and cropped down to the model's valid clip lengths: 5, 22, 39... (17k + 5) frames. Batches shorter than 5 frames use only the first image."
+ }
+ ],
+ "audio": [
+ "AUDIO",
+ {
+ "tooltip": "Soundtrack to anchor starting at the same frame index, cropped to the video's remaining duration."
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "positive",
+ "latent",
+ "frame_idx"
+ ],
+ "optional": [
+ "vae",
+ "audio_vae",
+ "image",
+ "audio"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "CONDITIONING"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "positive"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "MiniMaxH3AddGuide",
+ "display_name": "Add Guide for MiniMax H3",
+ "description": "Anchor an image, a short clip, audio, or a clip with its soundtrack at any frame of a MiniMax H3 video. Chain several nodes to anchor several frames.",
+ "python_module": "comfy_extras.nodes_minimax_h3",
+ "category": "model/conditioning/minimax",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
+ "MiniMaxH3ReferenceToVideo": {
+ "input": {
+ "required": {
+ "clip": [
+ "CLIP",
+ {}
+ ],
+ "prompt": [
+ "STRING",
+ {
+ "multiline": true,
+ "dynamicPrompts": true
+ }
+ ],
+ "width": [
+ "INT",
+ {
+ "default": 1344,
+ "min": 32,
+ "max": 16384,
+ "step": 32
+ }
+ ],
+ "height": [
+ "INT",
+ {
+ "default": 768,
+ "min": 32,
+ "max": 16384,
+ "step": 32
+ }
+ ],
+ "length": [
+ "INT",
+ {
+ "tooltip": "Frame count at 24 fps, (124 = ~5s, trained range is ~124-362)",
+ "default": 124,
+ "min": 5,
+ "max": 3600,
+ "step": 17
+ }
+ ],
+ "ref_image_size": [
+ "COMBO",
+ {
+ "tooltip": "Reference image sizing. 'match' scales each ref (down only, keeping aspect) to the generation's pixel area; 'max' uses the reference pipeline's 2048px short edge for best identity fidelity. Reference tokens ride through every sampling step, so 'max' can be several times slower.",
+ "default": "match",
+ "multiselect": false,
+ "options": [
+ "match",
+ "max"
+ ]
+ }
+ ]
+ },
+ "optional": {
+ "vae": [
+ "VAE",
+ {
+ "tooltip": "Video VAE. Without it reference images/videos only condition the text encoder."
+ }
+ ],
+ "audio_vae": [
+ "VAE",
+ {
+ "tooltip": "Audio VAE. Without it reference audio only conditions the text encoder."
+ }
+ ],
+ "ref_images": [
+ "COMFY_AUTOGROW_V3",
+ {
+ "template": {
+ "input": {
+ "required": {
+ "ref_image": [
+ "IMAGE",
+ {
+ "tooltip": "Reference image (downscaled to 2048 short edge if larger, never upscaled)"
+ }
+ ]
+ }
+ },
+ "prefix": "ref_image_",
+ "min": 0,
+ "max": 9
+ }
+ }
+ ],
+ "ref_videos": [
+ "COMFY_AUTOGROW_V3",
+ {
+ "template": {
+ "input": {
+ "required": {
+ "ref_video": [
+ "IMAGE",
+ {
+ "tooltip": "Reference video frames at 24 fps (2-15s)"
+ }
+ ]
+ }
+ },
+ "prefix": "ref_video_",
+ "min": 0,
+ "max": 3
+ }
+ }
+ ],
+ "ref_video_audios": [
+ "COMFY_AUTOGROW_V3",
+ {
+ "template": {
+ "input": {
+ "required": {
+ "ref_video_audio": [
+ "AUDIO",
+ {
+ "tooltip": "Soundtrack of the same-numbered reference video"
+ }
+ ]
+ }
+ },
+ "prefix": "ref_video_audio_",
+ "min": 0,
+ "max": 3
+ }
+ }
+ ],
+ "ref_audios": [
+ "COMFY_AUTOGROW_V3",
+ {
+ "template": {
+ "input": {
+ "required": {
+ "ref_audio": [
+ "AUDIO",
+ {
+ "tooltip": "Standalone reference audio"
+ }
+ ]
+ }
+ },
+ "prefix": "ref_audio_",
+ "min": 0,
+ "max": 3
+ }
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "clip",
+ "prompt",
+ "width",
+ "height",
+ "length",
+ "ref_image_size"
+ ],
+ "optional": [
+ "vae",
+ "audio_vae",
+ "ref_images",
+ "ref_videos",
+ "ref_video_audios",
+ "ref_audios"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "CONDITIONING",
+ "LATENT"
+ ],
+ "output_is_list": [
+ false,
+ false
+ ],
+ "output_name": [
+ "positive",
+ "LATENT"
+ ],
+ "output_tooltips": [
+ null,
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "MiniMaxH3ReferenceToVideo",
+ "display_name": "MiniMax H3 Reference to Video",
+ "description": "<Picture i> / <Video k> / <Audio j> reference conditioning for MiniMax H3. Use the same tags when prompting.",
+ "python_module": "comfy_extras.nodes_minimax_h3",
+ "category": "model/conditioning/minimax",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
+ "MiniMaxH3SigmaShift": {
+ "input": {
+ "required": {
+ "model": [
+ "MODEL",
+ {}
+ ],
+ "shift_video": [
+ "FLOAT",
+ {
+ "default": 12,
+ "min": 0.01,
+ "max": 100,
+ "step": 0.01
+ }
+ ],
+ "shift_audio": [
+ "FLOAT",
+ {
+ "default": 3,
+ "min": 0.01,
+ "max": 100,
+ "step": 0.01
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "model",
+ "shift_video",
+ "shift_audio"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "MODEL"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "MODEL"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "MiniMaxH3SigmaShift",
+ "display_name": "ModelSamplingMiniMaxH3",
+ "description": "Set the video/audio flow shifts.",
+ "python_module": "comfy_extras.nodes_minimax_h3",
+ "category": "model/patch/minimax",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "sigma shift",
+ "minimax shift"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"MoGeGeometryToFOV": {
"input": {
"required": {
@@ -11226,6 +11605,69 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "ModelAttentionBackend": {
+ "input": {
+ "required": {
+ "model": [
+ "MODEL",
+ {
+ "tooltip": "The model to patch."
+ }
+ ],
+ "attention": [
+ "COMBO",
+ {
+ "display_name": "backend",
+ "tooltip": "The dense attention backend. Comfy Kitchen attention uses quantized INT8 attention and is available only on Nvidia and AMD GPUs.",
+ "default": "pytorch attention",
+ "multiselect": false,
+ "options": [
+ "pytorch attention"
+ ]
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "model",
+ "attention"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "MODEL"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "model"
+ ],
+ "output_tooltips": [
+ "The model with the selected attention backend."
+ ],
+ "output_matchtypes": null,
+ "name": "ModelAttentionBackend",
+ "display_name": "Model Attention Backend",
+ "description": "Selects the dense attention implementation for the model. When used with Block Sparse Attention, this backend is used whenever sparse attention is inactive or unsupported.",
+ "python_module": "comfy_extras.nodes_model_advanced",
+ "category": "model/patch",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": true,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "comfy kitchen",
+ "attention",
+ "pytorch",
+ "kitchen attention"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"ModelPatchLoader": {
"input": {
"required": {
@@ -13786,6 +14228,147 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "SAM3_Detect": {
+ "input": {
+ "required": {
+ "model": [
+ "MODEL",
+ {
+ "display_name": "model"
+ }
+ ],
+ "image": [
+ "IMAGE",
+ {
+ "display_name": "image"
+ }
+ ],
+ "threshold": [
+ "FLOAT",
+ {
+ "display_name": "threshold",
+ "default": 0.5,
+ "min": 0,
+ "max": 1,
+ "step": 0.01
+ }
+ ],
+ "refine_iterations": [
+ "INT",
+ {
+ "display_name": "refine_iterations",
+ "tooltip": "SAM decoder refinement passes (0=use raw detector masks)",
+ "default": 2,
+ "min": 0,
+ "max": 5
+ }
+ ],
+ "individual_masks": [
+ "BOOLEAN",
+ {
+ "display_name": "individual_masks",
+ "tooltip": "Output per-object masks instead of union",
+ "default": false
+ }
+ ]
+ },
+ "optional": {
+ "conditioning": [
+ "CONDITIONING",
+ {
+ "display_name": "conditioning",
+ "tooltip": "Text conditioning from CLIPTextEncode"
+ }
+ ],
+ "bboxes": [
+ "BOUNDING_BOX",
+ {
+ "display_name": "bboxes",
+ "tooltip": "Bounding boxes to segment within",
+ "default": {
+ "x": 0,
+ "y": 0,
+ "width": 512,
+ "height": 512
+ },
+ "socketless": true,
+ "forceInput": true
+ }
+ ],
+ "positive_coords": [
+ "STRING",
+ {
+ "display_name": "positive_coords",
+ "tooltip": "Positive point prompts as JSON [{\"x\": int, \"y\": int}, ...] (pixel coords)",
+ "forceInput": true,
+ "multiline": false
+ }
+ ],
+ "negative_coords": [
+ "STRING",
+ {
+ "display_name": "negative_coords",
+ "tooltip": "Negative point prompts as JSON [{\"x\": int, \"y\": int}, ...] (pixel coords)",
+ "forceInput": true,
+ "multiline": false
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "model",
+ "image",
+ "threshold",
+ "refine_iterations",
+ "individual_masks"
+ ],
+ "optional": [
+ "conditioning",
+ "bboxes",
+ "positive_coords",
+ "negative_coords"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "MASK",
+ "BOUNDING_BOX"
+ ],
+ "output_is_list": [
+ false,
+ false
+ ],
+ "output_name": [
+ "masks",
+ "bboxes"
+ ],
+ "output_tooltips": [
+ null,
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "SAM3_Detect",
+ "display_name": "SAM3 Detect",
+ "description": "",
+ "python_module": "comfy_extras.nodes_sam3",
+ "category": "image/detection",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": [
+ "sam3",
+ "segment anything",
+ "open vocabulary",
+ "text detection",
+ "segment"
+ ],
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"SAM3_TrackToMask": {
"input": {
"required": {
@@ -15909,6 +16492,60 @@
"essentials_category": null,
"has_intermediate_output": false
},
+ "SelectCLIPDevice": {
+ "input": {
+ "required": {
+ "clip": [
+ "CLIP",
+ {}
+ ],
+ "device": [
+ "COMBO",
+ {
+ "multiselect": false,
+ "options": [
+ "default",
+ "cpu"
+ ]
+ }
+ ]
+ }
+ },
+ "input_order": {
+ "required": [
+ "clip",
+ "device"
+ ]
+ },
+ "is_input_list": false,
+ "output": [
+ "CLIP"
+ ],
+ "output_is_list": [
+ false
+ ],
+ "output_name": [
+ "CLIP"
+ ],
+ "output_tooltips": [
+ null
+ ],
+ "output_matchtypes": null,
+ "name": "SelectCLIPDevice",
+ "display_name": "Select CLIP Device",
+ "description": "Place the CLIP text encoder on a specific device (default / cpu / gpu:N).\n\n- \"default\" restores the device assigned by the loader.\n- \"cpu\" pins both the load and offload device to CPU.\n- \"gpu:N\" pins the load device to the Nth available GPU.\n\nWhen the selected device does not exist on the current machine\n(e.g. a workflow built on a 2-GPU box opened on a 1-GPU box),\nthe node passes the CLIP through unchanged and logs a message\ninstead of failing.",
+ "python_module": "comfy_extras.nodes_multigpu",
+ "category": "advanced/multigpu",
+ "output_node": false,
+ "deprecated": false,
+ "experimental": false,
+ "dev_only": false,
+ "api_node": false,
+ "price_badge": null,
+ "search_aliases": null,
+ "essentials_category": null,
+ "has_intermediate_output": false
+ },
"SolidMask": {
"input": {
"required": {
diff --git a/workflows/comfyui/video-character-swap-h3-relay.json b/workflows/comfyui/video-character-swap-h3-relay.json
new file mode 100644
index 00000000..4e0d9091
--- /dev/null
+++ b/workflows/comfyui/video-character-swap-h3-relay.json
@@ -0,0 +1,788 @@
+{
+ "adapter": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "model": [
+ "turbo",
+ 0
+ ],
+ "lora_name": "h3_character_swap_v1.5.safetensors",
+ "strength_model": 1
+ },
+ "_meta": {
+ "title": "LoraLoaderModelOnly"
+ }
+ },
+ "append": {
+ "class_type": "H3RelayAppendWindow",
+ "inputs": {
+ "frames": [
+ "decode",
+ 0
+ ],
+ "window": [
+ "window",
+ 12
+ ],
+ "previous": [
+ "start",
+ 4
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayAppendWindow"
+ }
+ },
+ "attention": {
+ "class_type": "ModelAttentionBackend",
+ "inputs": {
+ "model": [
+ "shift",
+ 0
+ ],
+ "attention": "comfy kitchen attention"
+ },
+ "_meta": {
+ "title": "ModelAttentionBackend"
+ }
+ },
+ "audio_vae": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_audio_vae_fp32.safetensors"
+ },
+ "_meta": {
+ "title": "VAELoader"
+ }
+ },
+ "decode": {
+ "class_type": "VAEDecode",
+ "inputs": {
+ "samples": [
+ "separate",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "VAEDecode"
+ }
+ },
+ "detect": {
+ "class_type": "SAM3_Detect",
+ "inputs": {
+ "model": [
+ "sam",
+ 0
+ ],
+ "image": [
+ "first_frame",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "threshold": 0.35,
+ "refine_iterations": 2,
+ "individual_masks": true,
+ "positive_coords": "",
+ "negative_coords": ""
+ },
+ "_meta": {
+ "title": "SAM3_Detect"
+ }
+ },
+ "dimensions": {
+ "class_type": "GetImageSize",
+ "inputs": {
+ "image": [
+ "prepare",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "GetImageSize"
+ }
+ },
+ "edit_mask": {
+ "class_type": "H3RelayApplyEditMask",
+ "inputs": {
+ "latent": [
+ "history",
+ 1
+ ],
+ "source_latent": [
+ "encode_source",
+ 0
+ ],
+ "mask": [
+ "window",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayApplyEditMask"
+ }
+ },
+ "encode_source": {
+ "class_type": "VAEEncode",
+ "inputs": {
+ "pixels": [
+ "window",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "VAEEncode"
+ }
+ },
+ "end": {
+ "class_type": "EndLoop",
+ "inputs": {
+ "output_value": [
+ "append",
+ 0
+ ],
+ "next_iteration_value": [
+ "append",
+ 0
+ ],
+ "accumulate": false
+ },
+ "_meta": {
+ "title": "EndLoop"
+ }
+ },
+ "expand_mask": {
+ "class_type": "H3RelayExpandMask",
+ "inputs": {
+ "masks": [
+ "recover",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "expansion_px": 64
+ },
+ "_meta": {
+ "title": "H3RelayExpandMask"
+ }
+ },
+ "finish": {
+ "class_type": "H3RelayFinishWindows",
+ "inputs": {
+ "state": [
+ "end",
+ 0
+ ],
+ "audio_mode": "source",
+ "source_audio": [
+ "prepare",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayFinishWindows"
+ }
+ },
+ "first_frame": {
+ "class_type": "ImageFromBatch",
+ "inputs": {
+ "image": [
+ "prepare",
+ 0
+ ],
+ "batch_index": 0,
+ "length": 1
+ },
+ "_meta": {
+ "title": "ImageFromBatch"
+ }
+ },
+ "guide": {
+ "class_type": "MiniMaxH3AddGuide",
+ "inputs": {
+ "positive": [
+ "history",
+ 0
+ ],
+ "latent": [
+ "edit_mask",
+ 0
+ ],
+ "frame_idx": 0,
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "audio": [
+ "window",
+ 2
+ ]
+ },
+ "_meta": {
+ "title": "Native target guide"
+ }
+ },
+ "guider": {
+ "class_type": "CFGGuider",
+ "inputs": {
+ "model": [
+ "sampling_memory",
+ 0
+ ],
+ "positive": [
+ "guide",
+ 0
+ ],
+ "negative": [
+ "guide",
+ 0
+ ],
+ "cfg": 1
+ },
+ "_meta": {
+ "title": "CFGGuider"
+ }
+ },
+ "history": {
+ "class_type": "H3RelayApplyHistory",
+ "inputs": {
+ "positive": [
+ "reference_conditioning",
+ 0
+ ],
+ "latent": [
+ "reference_conditioning",
+ 1
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ],
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "frames": [
+ "window",
+ 3
+ ],
+ "history_frames": [
+ "window",
+ 7
+ ],
+ "first_frame_guide": false,
+ "target_audio_guide": true,
+ "audio": [
+ "window",
+ 4
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayApplyHistory"
+ }
+ },
+ "mask": {
+ "class_type": "SAM3_TrackToMask",
+ "inputs": {
+ "track_data": [
+ "track",
+ 0
+ ],
+ "object_indices": ""
+ },
+ "_meta": {
+ "title": "SAM3_TrackToMask"
+ }
+ },
+ "model": {
+ "class_type": "UNETLoader",
+ "inputs": {
+ "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "_meta": {
+ "title": "UNETLoader"
+ }
+ },
+ "noise": {
+ "class_type": "RandomNoise",
+ "inputs": {
+ "noise_seed": [
+ "window",
+ 10
+ ]
+ },
+ "_meta": {
+ "title": "RandomNoise"
+ }
+ },
+ "plan": {
+ "class_type": "H3RelayWindowPlan",
+ "inputs": {
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "window_frames": "124",
+ "history_frames": "18",
+ "seed": 904239,
+ "schedule": "adaptive",
+ "seed_mode": "fixed",
+ "seed_overrides": "{}"
+ },
+ "_meta": {
+ "title": "Plan source-aligned windows"
+ }
+ },
+ "prepare": {
+ "class_type": "H3RelayPrepareSource",
+ "inputs": {
+ "video": [
+ "trim",
+ 0
+ ],
+ "resolution": "768",
+ "duration_seconds": 5,
+ "missing_audio": "silence"
+ },
+ "_meta": {
+ "title": "H3RelayPrepareSource"
+ }
+ },
+ "recover": {
+ "class_type": "H3RelayRecoverMasks",
+ "inputs": {
+ "masks": [
+ "mask",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "source_frames": [
+ "prepare",
+ 5
+ ],
+ "model": [
+ "sam",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "selection": [
+ "select",
+ 1
+ ],
+ "recover_empty_frames": true
+ },
+ "_meta": {
+ "title": "H3RelayRecoverMasks"
+ }
+ },
+ "reference": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "reference.png"
+ },
+ "_meta": {
+ "title": "LoadImage"
+ }
+ },
+ "reference_conditioning": {
+ "class_type": "MiniMaxH3ReferenceToVideo",
+ "inputs": {
+ "clip": [
+ "text_memory",
+ 0
+ ],
+ "prompt": "Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing.",
+ "width": [
+ "dimensions",
+ 0
+ ],
+ "height": [
+ "dimensions",
+ 1
+ ],
+ "length": [
+ "window",
+ 8
+ ],
+ "ref_image_size": "match",
+ "ref_videos.ref_video_0": [
+ "window",
+ 5
+ ],
+ "ref_images.ref_image_0": [
+ "reference",
+ 0
+ ],
+ "vae": [
+ "video_vae",
+ 0
+ ],
+ "audio_vae": [
+ "audio_vae",
+ 0
+ ],
+ "ref_audios.ref_audio_0": [
+ "window",
+ 6
+ ]
+ },
+ "_meta": {
+ "title": "Native H3 reference conditioning"
+ }
+ },
+ "sam": {
+ "class_type": "CheckpointLoaderSimple",
+ "inputs": {
+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "CheckpointLoaderSimple"
+ }
+ },
+ "sample": {
+ "class_type": "SamplerCustomAdvanced",
+ "inputs": {
+ "noise": [
+ "noise",
+ 0
+ ],
+ "guider": [
+ "guider",
+ 0
+ ],
+ "sampler": [
+ "sampler",
+ 0
+ ],
+ "sigmas": [
+ "schedule",
+ 0
+ ],
+ "latent_image": [
+ "edit_mask",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "SamplerCustomAdvanced"
+ }
+ },
+ "sampler": {
+ "class_type": "KSamplerSelect",
+ "inputs": {
+ "sampler_name": "er_sde"
+ },
+ "_meta": {
+ "title": "KSamplerSelect"
+ }
+ },
+ "sampling_memory": {
+ "class_type": "H3RelaySamplingMemory",
+ "inputs": {
+ "model": [
+ "adapter",
+ 0
+ ],
+ "latent": [
+ "edit_mask",
+ 0
+ ],
+ "conditioning": [
+ "guide",
+ 0
+ ],
+ "activation_memory_gib": 17
+ },
+ "_meta": {
+ "title": "H3RelaySamplingMemory"
+ }
+ },
+ "save": {
+ "class_type": "SaveVideo",
+ "inputs": {
+ "video": [
+ "video",
+ 0
+ ],
+ "filename_prefix": "fuobe/video-character-swap-h3-relay",
+ "format": "mp4",
+ "format.codec": "h264",
+ "format.codec.encoding": "re-encode",
+ "format.codec.encoding.crf": 16
+ },
+ "_meta": {
+ "title": "SaveVideo"
+ }
+ },
+ "schedule": {
+ "class_type": "BasicScheduler",
+ "inputs": {
+ "model": [
+ "adapter",
+ 0
+ ],
+ "scheduler": "normal",
+ "steps": 8,
+ "denoise": 1
+ },
+ "_meta": {
+ "title": "BasicScheduler"
+ }
+ },
+ "select": {
+ "class_type": "H3RelaySelectMask",
+ "inputs": {
+ "masks": [
+ "detect",
+ 0
+ ],
+ "selection": "largest",
+ "index": 0
+ },
+ "_meta": {
+ "title": "H3RelaySelectMask"
+ }
+ },
+ "separate": {
+ "class_type": "LTXVSeparateAVLatent",
+ "inputs": {
+ "av_latent": [
+ "sample",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "LTXVSeparateAVLatent"
+ }
+ },
+ "shift": {
+ "class_type": "MiniMaxH3SigmaShift",
+ "inputs": {
+ "model": [
+ "model",
+ 0
+ ],
+ "shift_video": 12,
+ "shift_audio": 3
+ },
+ "_meta": {
+ "title": "MiniMaxH3SigmaShift"
+ }
+ },
+ "source": {
+ "class_type": "LoadVideo",
+ "inputs": {
+ "file": "source.mp4"
+ },
+ "_meta": {
+ "title": "LoadVideo"
+ }
+ },
+ "start": {
+ "class_type": "StartLoop",
+ "inputs": {
+ "mode": "simple",
+ "mode.num_iterations": [
+ "plan",
+ 2
+ ],
+ "cache_iterations": false
+ },
+ "_meta": {
+ "title": "Native loop · one H3 window"
+ }
+ },
+ "subject": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {
+ "clip": [
+ "sam",
+ 1
+ ],
+ "text": "person"
+ },
+ "_meta": {
+ "title": "CLIPTextEncode"
+ }
+ },
+ "text": {
+ "class_type": "CLIPLoader",
+ "inputs": {
+ "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "type": "minimax",
+ "device": "default"
+ },
+ "_meta": {
+ "title": "CLIPLoader"
+ }
+ },
+ "text_device": {
+ "class_type": "SelectCLIPDevice",
+ "inputs": {
+ "clip": [
+ "text",
+ 0
+ ],
+ "device": "gpu:0"
+ },
+ "_meta": {
+ "title": "SelectCLIPDevice"
+ }
+ },
+ "text_memory": {
+ "class_type": "H3RelayTextMemory",
+ "inputs": {
+ "clip": [
+ "text_device",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayTextMemory"
+ }
+ },
+ "track": {
+ "class_type": "SAM3_VideoTrack",
+ "inputs": {
+ "model": [
+ "sam",
+ 0
+ ],
+ "images": [
+ "prepare",
+ 0
+ ],
+ "initial_mask": [
+ "select",
+ 0
+ ],
+ "conditioning": [
+ "subject",
+ 0
+ ],
+ "detection_threshold": 0.5,
+ "max_objects": 1,
+ "detect_interval": 1
+ },
+ "_meta": {
+ "title": "SAM3_VideoTrack"
+ }
+ },
+ "trim": {
+ "class_type": "Video Slice",
+ "inputs": {
+ "video": [
+ "source",
+ 0
+ ],
+ "start_time": 0,
+ "duration": 5,
+ "strict_duration": false
+ },
+ "_meta": {
+ "title": "The chosen part"
+ }
+ },
+ "turbo": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "model": [
+ "attention",
+ 0
+ ],
+ "lora_name": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "strength_model": 1
+ },
+ "_meta": {
+ "title": "LoraLoaderModelOnly"
+ }
+ },
+ "video": {
+ "class_type": "CreateVideo",
+ "inputs": {
+ "images": [
+ "finish",
+ 0
+ ],
+ "fps": [
+ "finish",
+ 2
+ ],
+ "audio": [
+ "finish",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "CreateVideo"
+ }
+ },
+ "video_vae": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_video_vae_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "VAELoader"
+ }
+ },
+ "window": {
+ "class_type": "H3RelayWindowInputs",
+ "inputs": {
+ "source": [
+ "prepare",
+ 0
+ ],
+ "window": [
+ "plan",
+ 3
+ ],
+ "iteration_index": [
+ "start",
+ 0
+ ],
+ "previous": [
+ "start",
+ 4
+ ],
+ "reference_history": true,
+ "fps": 24,
+ "resize_anchor": true,
+ "history_audio_mode": "source",
+ "source_audio": [
+ "prepare",
+ 1
+ ],
+ "mask": [
+ "expand_mask",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3RelayWindowInputs"
+ }
+ }
+}
diff --git a/workflows/comfyui/video-character-swap-h3.json b/workflows/comfyui/video-character-swap-h3.json
new file mode 100644
index 00000000..38c4ffe1
--- /dev/null
+++ b/workflows/comfyui/video-character-swap-h3.json
@@ -0,0 +1,529 @@
+{
+ "1": {
+ "class_type": "UNETLoader",
+ "inputs": {
+ "unet_name": "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
+ "weight_dtype": "default"
+ },
+ "_meta": {
+ "title": "H3 Ref2VA · INT8"
+ }
+ },
+ "2": {
+ "class_type": "MiniMaxH3SigmaShift",
+ "inputs": {
+ "shift_video": 12,
+ "shift_audio": 3,
+ "model": [
+ "1",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "H3 sampling shift"
+ }
+ },
+ "3": {
+ "class_type": "ModelAttentionBackend",
+ "inputs": {
+ "attention": "comfy kitchen attention",
+ "model": [
+ "2",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Optimized attention"
+ }
+ },
+ "4": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "lora_name": "minimax_h3_fl2v_turbo_8step_v1.0_768p_comfyui_bf16.safetensors",
+ "strength_model": 1,
+ "model": [
+ "3",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "FL2V Turbo · 8-step LoRA"
+ }
+ },
+ "6": {
+ "class_type": "CLIPLoader",
+ "inputs": {
+ "clip_name": "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
+ "type": "minimax",
+ "device": "default"
+ },
+ "_meta": {
+ "title": "Qwen · H3 text encoder"
+ }
+ },
+ "7": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_video_vae_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "H3 video VAE"
+ }
+ },
+ "8": {
+ "class_type": "VAELoader",
+ "inputs": {
+ "vae_name": "minimax_h3_audio_vae_fp32.safetensors"
+ },
+ "_meta": {
+ "title": "H3 audio VAE"
+ }
+ },
+ "9": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "reference.png"
+ },
+ "_meta": {
+ "title": "2 · Character reference"
+ }
+ },
+ "30": {
+ "class_type": "LoadVideo",
+ "inputs": {
+ "file": "source.mp4"
+ },
+ "_meta": {
+ "title": "1 · Source performance video"
+ }
+ },
+ "31": {
+ "class_type": "H3CharacterSwapPrepareVideo",
+ "inputs": {
+ "resolution": "768",
+ "duration_seconds": 5,
+ "video": [
+ "trim",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Prepare · 24 fps / pixel budget"
+ }
+ },
+ "58": {
+ "class_type": "SelectCLIPDevice",
+ "inputs": {
+ "device": "gpu:0",
+ "clip": [
+ "6",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Text encoder device"
+ }
+ },
+ "100": {
+ "class_type": "CheckpointLoaderSimple",
+ "inputs": {
+ "ckpt_name": "sam3.1_multiplex_fp16.safetensors"
+ },
+ "_meta": {
+ "title": "SAM 3.1 · model"
+ }
+ },
+ "101": {
+ "class_type": "CLIPTextEncode",
+ "inputs": {
+ "text": "person",
+ "clip": [
+ "100",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "4 · Find the subject"
+ }
+ },
+ "102": {
+ "class_type": "ImageFromBatch",
+ "inputs": {
+ "batch_index": 0,
+ "length": 1,
+ "image": [
+ "31",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Detection frame · first frame"
+ }
+ },
+ "103": {
+ "class_type": "SAM3_Detect",
+ "inputs": {
+ "threshold": 0.35,
+ "refine_iterations": 2,
+ "individual_masks": true,
+ "model": [
+ "100",
+ 0
+ ],
+ "image": [
+ "102",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ],
+ "positive_coords": "",
+ "negative_coords": ""
+ },
+ "_meta": {
+ "title": "Detect individual people"
+ }
+ },
+ "104": {
+ "class_type": "H3CharacterSwapSelectSubject",
+ "inputs": {
+ "selection": "largest",
+ "index": 0,
+ "masks": [
+ "103",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Select the person to replace"
+ }
+ },
+ "105": {
+ "class_type": "SAM3_VideoTrack",
+ "inputs": {
+ "detection_threshold": 0.5,
+ "max_objects": 1,
+ "detect_interval": 1,
+ "images": [
+ "31",
+ 0
+ ],
+ "model": [
+ "100",
+ 0
+ ],
+ "initial_mask": [
+ "104",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Track selected person"
+ }
+ },
+ "106": {
+ "class_type": "SAM3_TrackToMask",
+ "inputs": {
+ "object_indices": "",
+ "track_data": [
+ "105",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Selected track → mask"
+ }
+ },
+ "107": {
+ "class_type": "H3CharacterSwapRecoverMasks",
+ "inputs": {
+ "recover_empty_frames": true,
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "masks": [
+ "106",
+ 0
+ ],
+ "images": [
+ "31",
+ 0
+ ],
+ "model": [
+ "100",
+ 0
+ ],
+ "conditioning": [
+ "101",
+ 0
+ ],
+ "selection": [
+ "104",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "Recover empty frames · same as app"
+ }
+ },
+ "110": {
+ "class_type": "H3CharacterSwapExpandMask",
+ "inputs": {
+ "expansion_px": 64,
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "masks": [
+ "107",
+ 0
+ ],
+ "images": [
+ "31",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Expand mask · matches the app"
+ }
+ },
+ "800": {
+ "class_type": "H3CharacterSwapModels",
+ "inputs": {
+ "model": [
+ "850",
+ 0
+ ],
+ "clip": [
+ "58",
+ 0
+ ],
+ "video_vae": [
+ "7",
+ 0
+ ],
+ "audio_vae": [
+ "8",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Shared models"
+ }
+ },
+ "801": {
+ "class_type": "H3CharacterSwapSettings",
+ "inputs": {
+ "prompt": "Replace the selected person in <Video 1> with the character in <Picture 1>. Preserve the source performance, scene and audio timing. Start from the first frame in <Picture 2>.",
+ "seed": 904239,
+ "audio_guide": true,
+ "steps": 8,
+ "cfg": 1,
+ "sampler_name": "er_sde",
+ "scheduler": "normal",
+ "activation_memory_gib": 17
+ },
+ "_meta": {
+ "title": "5 · Prompt & audio guide"
+ }
+ },
+ "803": {
+ "class_type": "H3CharacterSwapShot",
+ "inputs": {
+ "use_anchor": true,
+ "use_mask": true,
+ "shot_id": "character-swap",
+ "source_frames": [
+ "31",
+ 5
+ ],
+ "fps": [
+ "31",
+ 6
+ ],
+ "source_video": [
+ "trim",
+ 0
+ ],
+ "source": [
+ "31",
+ 0
+ ],
+ "source_audio": [
+ "31",
+ 1
+ ],
+ "reference": [
+ "9",
+ 0
+ ],
+ "anchor": [
+ "anchor_fit",
+ 0
+ ],
+ "body_mask": [
+ "110",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Prepare swap inputs"
+ }
+ },
+ "805": {
+ "class_type": "H3CharacterSwapWindowPlan",
+ "inputs": {
+ "window_frames": "124",
+ "history_frames": "18",
+ "shot": [
+ "803",
+ 0
+ ],
+ "settings": [
+ "801",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Continuation · window / history"
+ }
+ },
+ "806": {
+ "class_type": "H3CharacterSwapController",
+ "inputs": {
+ "models": [
+ "800",
+ 0
+ ],
+ "shot": [
+ "803",
+ 0
+ ],
+ "plan": [
+ "805",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "6 · Generate character swap"
+ }
+ },
+ "807": {
+ "class_type": "H3CharacterSwapAssemble",
+ "inputs": {
+ "filename_prefix": "fuobe-character-swap",
+ "state": [
+ "806",
+ 0
+ ],
+ "shot": [
+ "806",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "7 · Result with source audio"
+ }
+ },
+ "808": {
+ "class_type": "CreateVideo",
+ "inputs": {
+ "fps": 24,
+ "bit_depth": 8,
+ "color_space": "sRGB",
+ "codec": "none",
+ "images": [
+ "807",
+ 0
+ ],
+ "audio": [
+ "807",
+ 1
+ ]
+ },
+ "_meta": {
+ "title": "Video for the app"
+ }
+ },
+ "809": {
+ "class_type": "SaveVideo",
+ "inputs": {
+ "filename_prefix": "fuobe/video-character-swap-h3",
+ "format": "mp4",
+ "format.codec": "h264",
+ "video": [
+ "808",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Save result"
+ }
+ },
+ "850": {
+ "class_type": "LoraLoaderModelOnly",
+ "inputs": {
+ "lora_name": "h3_character_swap_v1.5.safetensors",
+ "strength_model": 1,
+ "model": [
+ "4",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "Character Swap LoRA (V1.5)"
+ }
+ },
+ "anchor_fit": {
+ "class_type": "ImageScale",
+ "inputs": {
+ "upscale_method": "lanczos",
+ "crop": "center",
+ "image": [
+ "anchor_image",
+ 0
+ ],
+ "width": [
+ "31",
+ 2
+ ],
+ "height": [
+ "31",
+ 3
+ ]
+ },
+ "_meta": {
+ "title": "Anchor at the video's exact size"
+ }
+ },
+ "anchor_image": {
+ "class_type": "LoadImage",
+ "inputs": {
+ "image": "anchor.png"
+ },
+ "_meta": {
+ "title": "First frame made by the app"
+ }
+ },
+ "trim": {
+ "class_type": "Video Slice",
+ "inputs": {
+ "start_time": 0,
+ "duration": 5,
+ "strict_duration": false,
+ "video": [
+ "30",
+ 0
+ ]
+ },
+ "_meta": {
+ "title": "The chosen part"
+ }
+ }
+}