Skip to content

One-click character swap for videos: an open-source, local Higgsfield Genjutsu alternative built on ComfyUI and MiniMax H3, with FLUX.3 Klein relighting.

Add welcome page and configurable model components

D3voz26696f759914
diff --git a/.gitignore b/.gitignore
index a9a252b..162378e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,4 @@ node_modules
AGENTS.md
CLAUDE.md
public/_test
+public/_montage_test
diff --git a/README.md b/README.md
index 5995ecf..32f151b 100644
--- a/README.md
+++ b/README.md
@@ -4,6 +4,12 @@ An open-source, Genjutsu-style character and object swap for video. Drop a video
The app is a small Next.js front end over a ComfyUI workflow. It uses [`@comfyorg/sdk`](https://www.npmjs.com/package/@comfyorg/sdk), following Comfy's [comfy-reshoot](https://github.com/Comfy-Org/comfy-reshoot) reference app.
+## First visit: visual describer
+
+The welcome page lets you choose the vision-language model that describes pictures and video frames and writes prompts. Qwen3-VL 8B INT8 remains the default; Qwen3-VL 4B FP8 and Gemma 4 E2B INT8 are smaller alternatives. Install a compatible single-file model including its vision weights in `ComfyUI/models/text_encoders`, then press **Refresh models**. Other installed models can be selected if they support image/video input and text generation through ComfyUI's CLIPLoader and Generate Text nodes. Text-only models and files requiring a different loader are unsuitable.
+
+Choose according to available VRAM and leave room for image/video context and working memory; file size is not a VRAM requirement, and H3 generation has separate memory needs. Your selection is saved in this browser and used for swaps, prompt descriptions and **Find people**. Reopen **Welcome & models** to change it, or use **Visual describer** under Model components. Alternative describers may change prompt quality and person matching. **Set up later** opens the editor; generation still checks the required files. The separate H3 text encoder remains unchanged.
+
## Modes
- **Simple motion transfer**: available. One character replaces the main person (the one who fills the most of the frame). Runs `workflows/simple.api.json`, exported from `H3 One-Click Single Swap (DMAD 6 step).json`.
@@ -101,6 +107,7 @@ Advanced motion transfer has a **Montage** tab for edited clips where different
- **No lip-sync** (off by default) is for songs the people in the video do not sing or talk along to. Otherwise H3 makes the new people lip-sync any vocals. It gives H3 silent audio and a prompt saying nobody sings, and shows it the source faces for head turns (about 30 s more per clip); the final video still has the original soundtrack. Mouths can still smile more widely than the source.
- **Check mask** runs only SAM and the mask (about a minute per 3 s of video) and shows a preview you can scrub frame by frame: cyan is the area H3 regenerates, orange the tracked person, and on the right the grey mannequin H3 copies the motion from. Anything outside the cyan area stays as it is. If the character is cut off or too much background changes, set **Mask margin** (Tight, Normal, Loose) and check again; a re-check takes seconds.
- **Motion reference** (under Advanced) is the size of the grey figures H3 copies the motion from: 512 px by default, or 768 or 1376 px. For general, simple videos 512 px is probably enough, but a bigger size does seem to improve quality a bit: H3 follows the source poses and placement more closely. Sampling takes about a third longer at 768 px and about 2.4× as long at 1376 px (H3 uses at most 768×1344 for references). Each size keeps its own saved clips, so switching size renders again instead of resuming.
+- **Model components** (under Advanced): choose the H3 Qwen3-VL 32B text encoder quantization and the video and audio VAEs from ComfyUI's installed files. **Use LoRAs** turns all selected LoRAs on or off without removing them. Each LoRA also has its own **Use this LoRA** or **Use speed LoRA** switch; turn off only the speed LoRA to keep style LoRAs and enable Spectrum. **Acceleration → Spectrum** requires [ComfyUI-Spectrum-MiniMax-H3](https://github.com/xmarre/ComfyUI-Spectrum-MiniMax-H3) and is unavailable with an active speed LoRA. DMAD, Turbo, LightX2V and common few-step filenames are recognized; mark renamed speed LoRAs with **Speed LoRA**. Without a speed LoRA, use 20 or more steps. Spectrum is approximate and can change the output.
- Change the **seed** (under Advanced) for a new take. Running the same inputs again resumes from the last finished clip.
- **Steps**, **Base model** and **LoRAs** (under Advanced) default to the H3 pruned INT8 model with the DMAD speed LoRA at 6 steps. LoRAs apply in order; without a speed LoRA, use 20 steps or more. Check mask ignores them.
- **Object swap:** name what SAM tracks in a word or two (`hair`, `jacket`, `poster`), or several separated by commas (`hair, top`) to change them together. Every match changes unless **Only the biggest one** is on (one of each thing). A picture of an outfit, hairstyle, product or place is copied onto it. For **Remove**, say what shows instead only when it is not obvious (`a plain wall`). Mask margin is smaller here (10, 20 or 40 px). Change keeps the outline of what it replaces: a tank top turned into a flannel shirt stays sleeveless.
diff --git a/app/api/jobs/route.ts b/app/api/jobs/route.ts
index 3fef141..88e8dd9 100644
--- a/app/api/jobs/route.ts
+++ b/app/api/jobs/route.ts
@@ -5,7 +5,7 @@ import { TRACKS_FILE, type Label } from "../../../lib/montage.ts";
import { DEFAULT_TONE, DETAIL, TONE_MODES, TONE_RANGES, type ColorSettings, type ToneMode, type ToneSettings, type ToneValue } from "../../../lib/color.ts";
import { CHUNK_SECONDS, FACE_STYLES, type FaceSettings, type FaceStyle } from "../../../lib/face.ts";
import { MAX_CHARACTERS } from "../../../lib/advanced.ts";
-import { MAX_LORAS, STEPS, STRENGTH, type ModelSettings } from "../../../lib/model.ts";
+import { checkAcceleration, MAX_LORAS, STEPS, STRENGTH, type Acceleration, type ModelFiles, type ModelSettings } from "../../../lib/model.ts";
import { EDIT_MODES, OBJECT_MARGINS, parsePaint, parsePlacement, type EditMode, type ObjectMargin, type ObjectSettings } from "../../../lib/object.ts";
import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, CUSTOM_SIZE, type Margin, type MotionSize, type Preset, type Resolution, type Section, type SimpleSettings } from "../../../lib/simple.ts";
@@ -89,20 +89,40 @@ function parseObject(form: FormData) {
return { picture, settings };
}
-function parseModel(form: FormData, available: { models: string[]; loras: string[] }): ModelSettings {
+function parseDescriber(form: FormData, available: ModelFiles) {
+ if (!form.has("describer")) return undefined;
+ const name = String(form.get("describer")).trim();
+ if (!available.textEncoders.includes(name)) throw new Error("Choose a visual describer ComfyUI has in models/text_encoders.");
+ return name;
+}
+
+function parseModel(form: FormData, available: ModelFiles): ModelSettings {
const steps = Number(form.get("steps"));
if (!Number.isInteger(steps) || steps < STEPS.min || steps > STEPS.max) throw new Error(`Steps must be a whole number from ${STEPS.min} to ${STEPS.max}.`);
const model = String(form.get("model") ?? "").trim();
if (!model || !available.models.includes(model)) throw new Error("Choose a base model ComfyUI has.");
const names = form.getAll("lora").map((name) => String(name).trim());
const strengths = form.getAll("lora_strength").map(Number);
+ const speed = form.getAll("lora_speed");
if (names.length > MAX_LORAS || strengths.length !== names.length) throw new Error(`Use at most ${MAX_LORAS} LoRAs, each with a strength.`);
const loras = names.map((name, i) => {
if (!name || !available.loras.includes(name)) throw new Error("Choose LoRAs ComfyUI has.");
if (!(strengths[i] >= STRENGTH.min && strengths[i] <= STRENGTH.max)) throw new Error(`LoRA strength must be ${STRENGTH.min} to ${STRENGTH.max}.`);
- return { name, strength: strengths[i] };
+ return { name, strength: strengths[i], speed: speed[i] === "true" };
});
- return { steps, model, loras };
+ const selected: ModelSettings = { steps, model, loras, describer: parseDescriber(form, available), acceleration: String(form.get("acceleration") ?? "none") as Acceleration };
+ for (const [field, key, names, label] of [
+ ["text_encoder", "textEncoder", available.textEncoders, "H3 text encoder"],
+ ["video_vae", "videoVae", available.vaes, "video VAE"],
+ ["audio_vae", "audioVae", available.vaes, "audio VAE"],
+ ] as const) {
+ if (!form.has(field)) continue;
+ const name = String(form.get(field)).trim();
+ if (!names.includes(name)) throw new Error(`Choose a ${label} ComfyUI has.`);
+ selected[key] = name;
+ }
+ checkAcceleration(selected);
+ return selected;
}
function parseFace(form: FormData) {
@@ -234,7 +254,8 @@ async function submitForm(form: FormData) {
submit = () => submitFit(video, section, placement, resolution, action);
} else if (mode === "people") {
const { roles, resolution } = parsePeople(form);
- submit = () => submitPeople(video, section, roles, resolution);
+ const describer = form.has("describer") ? parseDescriber(form, await listModels()) : undefined;
+ submit = () => submitPeople(video, section, roles, resolution, describer);
} else if (mode === "montage") {
const { pictures, settings, review } = parseMontage(form);
const model = parseModel(form, await listModels());
diff --git a/app/api/models/route.ts b/app/api/models/route.ts
index db94ae5..440a4e5 100644
--- a/app/api/models/route.ts
+++ b/app/api/models/route.ts
@@ -12,6 +12,6 @@ export async function GET(request: Request) {
return NextResponse.json(await listModels());
} catch {
// Empty lists turn the pickers into text fields.
- return NextResponse.json({ models: [], loras: [], error: MODELS_UNAVAILABLE }, { status: 502 });
+ return NextResponse.json({ models: [], loras: [], textEncoders: [], vaes: [], error: MODELS_UNAVAILABLE }, { status: 502 });
}
}
diff --git a/app/globals.css b/app/globals.css
index 4c27101..88d03b1 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -176,6 +176,7 @@ input[type="range"] { accent-color: var(--accent); width: 220px; max-width: 100%
.target-input { width: 12rem; }
.setting.loras { align-items: flex-start; }
.lora-list { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; flex: 1 1 100%; }
+.lora-entry { width: 100%; }
.lora { display: grid; grid-template-columns: minmax(0, 1fr) 4.5rem auto; gap: 8px; width: 100%; }
.lora .file-name { width: 100%; }
@@ -220,3 +221,34 @@ input[type="range"] { accent-color: var(--accent); width: 220px; max-width: 100%
@media (max-width: 760px) {
.history li button { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
}
+
+
+.welcome { max-width: 940px; gap: 26px; }
+.welcome-intro { padding: 22px 0 4px; }
+.eyebrow { margin: 0 0 9px; color: var(--accent); font-size: 0.73rem; font-weight: 700; letter-spacing: 0.12em; }
+.welcome-intro h2 { margin: 0; font-size: clamp(2rem, 5vw, 3.1rem); letter-spacing: -0.04em; line-height: 1.12; }
+.welcome-intro > p:last-of-type { color: var(--muted); max-width: 650px; font-size: 1.05rem; }
+.welcome-flow { list-style: none; padding: 0; margin: 26px 0 0; display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; counter-reset: welcome; }
+.welcome-flow li { border-top: 1px solid var(--line); padding-top: 14px; display: grid; gap: 7px; counter-increment: welcome; }
+.welcome-flow strong::before { content: "0" counter(welcome) " / "; color: var(--accent); }
+.welcome-flow span { color: var(--muted); font-size: 0.85rem; }
+.welcome .panel { padding: 24px; gap: 12px; }
+.welcome .panel h2 { font-size: 1.25rem; margin-bottom: 6px; }
+.welcome-picker { border-color: #657931; }
+.welcome-picker > label { font-size: 0.88rem; font-weight: 600; margin-top: 4px; }
+.welcome-picker > select { width: 100%; min-width: 0; }
+.welcome-install { padding: 16px; background: var(--bg); border: 1px solid var(--line); border-radius: 12px; display: grid; gap: 10px; margin-top: 6px; }
+.welcome-install code { color: var(--accent); overflow-wrap: anywhere; }
+.welcome-table { overflow-x: auto; }
+.welcome table { width: 100%; border-collapse: collapse; font-size: 0.88rem; text-align: left; }
+.welcome caption { text-align: left; color: var(--muted); font-size: 0.8rem; padding-bottom: 8px; }
+.welcome th, .welcome td { border-bottom: 1px solid var(--line); padding: 12px 10px; }
+.welcome thead th { color: var(--muted); font-weight: 500; }
+.welcome a { color: var(--accent); text-underline-offset: 3px; }
+.welcome-actions { display: flex; flex-wrap: wrap; gap: 20px; justify-content: space-between; align-items: center; }
+@media (max-width: 640px) {
+ .welcome-flow { grid-template-columns: 1fr; }
+ .welcome .panel { padding: 18px; }
+ .welcome-actions > .row { width: 100%; }
+ .welcome-actions button { flex: 1; }
+}
diff --git a/components/openjutsu.tsx b/components/openjutsu.tsx
index 3d90f1a..96b99f9 100644
--- a/components/openjutsu.tsx
+++ b/components/openjutsu.tsx
@@ -7,8 +7,9 @@ import type { NodeInfo } from "../lib/progress.ts";
import { clipCount, clipStarts } from "../lib/clips.ts";
import { CLIP_SECONDS, DEFAULT_TARGET, MARGINS, MAX_SEED, MIN_SECTION_SECONDS, MOTION_SIZES, RESOLUTIONS, CUSTOM_SIZE, canvasSize, type Margin, type MotionSize, type Resolution, type Section, type Size } from "../lib/simple.ts";
import { MAX_CHARACTERS } from "../lib/advanced.ts";
-import { DEFAULT_MODEL, MAX_LORAS, STEPS, STRENGTH, type Lora } from "../lib/model.ts";
+import { ACCELERATIONS, DEFAULT_DESCRIBER, DEFAULT_MODEL, hasSpeedLora, isSpeedLora, MAX_LORAS, STEPS, STRENGTH, type Acceleration, type Lora, type ModelFiles } from "../lib/model.ts";
import type { EditMode, FitSummary, PaintKeyframe, PlacementKeyframe } from "../lib/object.ts";
+import { Welcome } from "./welcome.tsx";
import { ObjectPlacement } from "./object-placement.tsx";
import { FromPicture } from "./from-picture.tsx";
import { CHUNK_SECONDS, FACE_STYLES, faceChunkCount, type FaceStyle } from "../lib/face.ts";
@@ -29,6 +30,7 @@ type Progress = NodeInfo & { step: number | null; steps: number | null; pass: nu
const TERMINAL = new Set(["succeeded", "failed", "canceled", "expired"]);
const RUN_KEY = "openjutsu.run";
const SETTINGS_KEY = "openjutsu.settings";
+const WELCOME_KEY = "openjutsu.welcome";
const HISTORY_KEY = "openjutsu.history";
const HISTORY_LENGTH = 20;
@@ -93,6 +95,7 @@ type Settings = {
margin: Margin; target: string; editMode: EditTab; editTarget: string; biggestOnly: boolean; keepOutline: boolean; post: Post;
detailOn: boolean; detail: number; toneOn: boolean; tone: ToneSettings; tonePreset: string; faceStyle: FaceStyle;
chunkSeconds: number; seed: number; clipSeconds: number; motion: MotionSize; steps: number; model: string; loras: Lora[];
+ useLoras: boolean; describer: string; textEncoder: string; videoVae: string; audioVae: string; acceleration: Acceleration;
};
const isBoolean = (value: unknown) => typeof value === "boolean";
@@ -113,7 +116,8 @@ const SETTING_CHECKS: Record<keyof Settings, (value: unknown) => boolean> = {
tonePreset: isString, faceStyle: oneOf(FACE_STYLES), chunkSeconds: inRange(CHUNK_SECONDS),
seed: (value) => Number.isInteger(value) && inRange({ min: 0, max: MAX_SEED })(value), clipSeconds: inRange(CLIP_SECONDS),
motion: oneOf(MOTION_SIZES), steps: (value) => Number.isInteger(value) && inRange(STEPS)(value), model: isString,
- loras: (value) => Array.isArray(value) && value.length <= MAX_LORAS && value.every((l) => !!l && isString(l.name) && inRange(STRENGTH)(l.strength)),
+ loras: (value) => Array.isArray(value) && value.length <= MAX_LORAS && value.every((l) => !!l && isString(l.name) && inRange(STRENGTH)(l.strength) && (l.speed === undefined || isBoolean(l.speed)) && (l.enabled === undefined || isBoolean(l.enabled))),
+ useLoras: isBoolean, describer: isString, textEncoder: isString, videoVae: isString, audioVae: isString, acceleration: oneOf(ACCELERATIONS),
};
function readSettings(defaults: Settings): Settings {
@@ -271,7 +275,19 @@ export function Openjutsu() {
const [steps, setSteps] = useState(DEFAULT_MODEL.steps);
const [model, setModel] = useState(DEFAULT_MODEL.model);
const [loras, setLoras] = useState<Lora[]>(DEFAULT_MODEL.loras);
- const [files, setFiles] = useState<{ models: string[]; loras: string[] }>({ models: [], loras: [] });
+ const [useLoras, setUseLoras] = useState(true);
+ const [describer, setDescriber] = useState(DEFAULT_DESCRIBER);
+ const [welcome, setWelcome] = useState(false);
+ const [modelsLoading, setModelsLoading] = useState(true);
+ const [modelsError, setModelsError] = useState("");
+ const [textEncoder, setTextEncoder] = useState(DEFAULT_MODEL.textEncoder);
+ const [videoVae, setVideoVae] = useState(DEFAULT_MODEL.videoVae);
+ const [audioVae, setAudioVae] = useState(DEFAULT_MODEL.audioVae);
+ const [acceleration, setAcceleration] = useState<Acceleration>(DEFAULT_MODEL.acceleration);
+ const enabledLoras = useLoras ? loras.filter((lora) => lora.enabled !== false) : [];
+ const speedLora = hasSpeedLora(enabledLoras);
+ const selectedAcceleration = speedLora ? "none" : acceleration;
+ const [files, setFiles] = useState<ModelFiles>({ models: [], loras: [], textEncoders: [], vaes: [] });
const [submitting, setSubmitting] = useState(false);
const [checkingSetup, setCheckingSetup] = useState(false);
const [setup, setSetup] = useState<SetupResult | null>(null);
@@ -294,6 +310,7 @@ export function Openjutsu() {
const settings: Settings = {
mode, maxQuality, montage, resolution, customSize, hatFix, noLipSync, margin, target, editMode, editTarget, biggestOnly, keepOutline, post,
detailOn, detail, toneOn, tone, tonePreset, faceStyle, chunkSeconds, seed, clipSeconds, motion, steps, model, loras,
+ useLoras, describer, textEncoder, videoVae, audioVae, acceleration,
};
const savedSettings = JSON.stringify(settings);
@@ -304,6 +321,9 @@ export function Openjutsu() {
setBiggestOnly(s.biggestOnly); setKeepOutline(s.keepOutline); setPost(s.post); setDetailOn(s.detailOn); setDetail(s.detail); setToneOn(s.toneOn);
setTone(s.tone); setTonePreset(s.tonePreset); setFaceStyle(s.faceStyle); setChunkSeconds(s.chunkSeconds); setSeed(s.seed);
setClipSeconds(s.clipSeconds); setMotion(s.motion); setSteps(s.steps); setModel(s.model); setLoras(s.loras);
+ try { setWelcome(localStorage.getItem(WELCOME_KEY) !== "1"); } catch { setWelcome(true); }
+ setDescriber(s.describer);
+ setUseLoras(s.useLoras); setTextEncoder(s.textEncoder); setVideoVae(s.videoVae); setAudioVae(s.audioVae); setAcceleration(s.acceleration);
setRestored(true);
}, []);
@@ -327,10 +347,30 @@ export function Openjutsu() {
setHistory((list) => list.map((p) => p.id !== job.id || (p.status && job.status === "expired") ? p : { ...p, status: job.status, result: job.video?.name }));
}, [job?.id, job?.status]);
- useEffect(() => setSetup(null), [mode, post, montage, maxQuality, resolution, motion, hatFix, noLipSync, model, loras, detailOn, toneOn, faceStyle, editMode, characters.length, !!look]);
+ useEffect(() => setSetup(null), [mode, post, montage, maxQuality, resolution, motion, hatFix, noLipSync, model, loras, useLoras, describer, textEncoder, videoVae, audioVae, acceleration, detailOn, toneOn, faceStyle, editMode, characters.length, !!look]);
+
+ async function refreshModels() {
+ setModelsLoading(true);
+ setModelsError("");
+ try {
+ const response = await fetch("/api/models");
+ const result = await response.json();
+ if (!response.ok) throw new Error(result.error ?? "Could not read models from ComfyUI.");
+ setFiles(result);
+ } catch (error) {
+ setModelsError(error instanceof Error ? error.message : "Could not read models from ComfyUI.");
+ } finally {
+ setModelsLoading(false);
+ }
+ }
+
+ function finishWelcome() {
+ try { localStorage.setItem(WELCOME_KEY, "1"); } catch {}
+ setWelcome(false);
+ }
useEffect(() => {
- fetch("/api/models").then((response) => response.json()).then(setFiles, () => {});
+ void refreshModels();
fetch("/api/presets").then((response) => response.json()).then(({ tone }: { tone: TonePreset[] }) => setPresets(tone), () => {});
}, []);
@@ -567,13 +607,19 @@ export function Openjutsu() {
form.set("motion", String(motion));
form.set("steps", String(steps));
form.set("model", model);
- for (const l of loras) {
+ form.set("text_encoder", textEncoder);
+ form.set("video_vae", videoVae);
+ form.set("audio_vae", audioVae);
+ form.set("acceleration", selectedAcceleration);
+ for (const l of enabledLoras) {
form.append("lora", l.name);
form.append("lora_strength", String(l.strength));
+ form.append("lora_speed", String(isSpeedLora(l)));
}
}
+ if (kind !== "mask" && kind !== "color" && kind !== "fit") form.set("describer", describer);
const shared = { resolution, motion, hatFix, noLipSync, margin, seed, clipSeconds };
- const selectedModel = { model, loras, steps };
+ const selectedModel = { model, loras: enabledLoras, steps, describer, textEncoder, videoVae, audioVae, acceleration: selectedAcceleration };
let selection: SetupRequest;
if (kind === "simple") selection = { kind, settings: { ...shared, role: character?.role ?? "", target: String(form.get("target")) }, model: selectedModel };
else if (kind === "advanced" || kind === "advanced_maxq") selection = { kind, settings: { ...shared, roles: shown.map((c) => c.role) }, pictures: shown.length, model: selectedModel };
@@ -584,7 +630,7 @@ export function Openjutsu() {
else if (kind === "face") selection = { kind, settings: { style: faceStyle, seed, chunkSeconds }, model: selectedModel };
else if (kind === "color") selection = { kind, settings: { detail: detailOn ? detail : null, tone: toneOn ? tone : null } };
else if (kind === "mask") selection = { kind, hatFix, margin, target: String(form.get("target")) };
- else selection = { kind, resolution };
+ else selection = kind === "people" ? { kind, resolution, describer } : { kind, resolution };
try {
const checked = await fetch("/api/setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(selection) });
@@ -660,9 +706,13 @@ export function Openjutsu() {
setPost(next);
}
+ if (!restored) return <main className="shell"><p className="hint" role="status">Loading Openjutsu…</p></main>;
+ if (welcome && !run) return <Welcome value={describer} options={files.textEncoders} onChange={setDescriber}
+ loading={modelsLoading} error={modelsError} onRefresh={refreshModels} onContinue={finishWelcome} />;
+
return (
<main className="shell">
- <header className="top">
+ <header className="top row">
<div className="brand">
<span className="mark" aria-hidden>忍</span>
<div>
@@ -670,6 +720,7 @@ export function Openjutsu() {
<p>Swap the people or things in any video. Open weights, on your own GPU.</p>
</div>
</div>
+ <button className="secondary" disabled={!!run || submitting} onClick={() => setWelcome(true)}>Welcome &amp; models</button>
</header>
<nav className="modes" aria-label="Mode">
@@ -702,7 +753,8 @@ export function Openjutsu() {
<h2>Setup needs attention</h2>
{setup.error && <p className="error">{setup.error}</p>}
{setup.packs.length > 0 && <>
- <p className="hint">Install or update the items below, then restart ComfyUI and try again.</p>
+ <p className="hint">Install or update each custom node pack in the <code>custom_nodes</code> folder of the ComfyUI installation Openjutsu connects to, with one subfolder per pack (for example, <code>ComfyUI/custom_nodes/ComfyUI-KJNodes</code>).</p>
+ <p className="hint">Use ComfyUI Manager or follow the links below for installation and Python dependency instructions. If ComfyUI itself is listed, update ComfyUI. Then restart ComfyUI and try again.</p>
<ul>{setup.packs.map((pack) => <li key={pack.url}>
<a href={pack.url} target="_blank" rel="noopener noreferrer">{pack.name} ↗</a>
<small>Missing nodes: {pack.nodes.join(", ")}</small>
@@ -1042,23 +1094,65 @@ export function Openjutsu() {
<span>Base model <small>The H3 diffusion model in ComfyUI&apos;s models/diffusion_models.</small></span>
<FilePicker label="Base model" value={model} options={files.models} onChange={setModel} />
</div>
- <div className="setting loras">
- <span>LoRAs <small>Applied in order to the base model. Remove the DMAD LoRA only together with more steps.</small></span>
+ <div className="setting">
+ <span>Visual describer <small>Reads pictures and video frames to write prompts. Use a vision-language model in models/text_encoders.</small></span>
+ <FilePicker label="Visual describer" value={describer} options={files.textEncoders} onChange={setDescriber} />
+ </div>
+ <div className="setting">
+ <span>H3 text encoder <small>Choose your MiniMax H3 Qwen3-VL 32B quantization from models/text_encoders.</small></span>
+ <FilePicker label="H3 text encoder" value={textEncoder} options={files.textEncoders} onChange={setTextEncoder} />
+ </div>
+ <div className="setting">
+ <span>Video VAE <small>Choose a MiniMax H3 video VAE from models/vae.</small></span>
+ <FilePicker label="Video VAE" value={videoVae} options={files.vaes} onChange={setVideoVae} />
+ </div>
+ <div className="setting">
+ <span>Audio VAE <small>Choose a MiniMax H3 audio VAE from models/vae.</small></span>
+ <FilePicker label="Audio VAE" value={audioVae} options={files.vaes} onChange={setAudioVae} />
+ </div>
+ <label className="setting toggle">
+ <span>Use LoRAs <small>Turn off to use the base model alone. Without a speed LoRA, use 20 or more steps.</small></span>
+ <input type="checkbox" checked={useLoras} onChange={(event) => setUseLoras(event.target.checked)} />
+ <i />
+ </label>
+ {useLoras && <div className="setting loras">
+ <span>LoRAs <small>Applied in order to the base model.</small></span>
<div className="lora-list">
{loras.map((l, i) => (
- <div className="lora" key={i}>
- <FilePicker label={`LoRA ${i + 1}`} value={l.name} options={files.loras} onChange={(name) => setLoras(loras.map((x, j) => (j === i ? { ...x, name } : x)))} />
- <input
- type="number" aria-label={`LoRA ${i + 1} strength`} min={STRENGTH.min} max={STRENGTH.max} step={0.05} value={l.strength}
- onChange={(event) => setLoras(loras.map((x, j) => (j === i ? { ...x, strength: Math.min(STRENGTH.max, Math.max(STRENGTH.min, Number(event.target.value) || 0)) } : x)))}
- />
- <button className="secondary" onClick={() => setLoras(loras.filter((_, j) => j !== i))} aria-label={`Remove LoRA ${i + 1}`}>×</button>
+ <div className="lora-entry" key={i}>
+ <div className="lora">
+ <FilePicker label={`LoRA ${i + 1}`} value={l.name} options={files.loras} onChange={(name) => setLoras(loras.map((x, j) => (j === i ? { ...x, name } : x)))} />
+ <input
+ type="number" aria-label={`LoRA ${i + 1} strength`} min={STRENGTH.min} max={STRENGTH.max} step={0.05} value={l.strength}
+ onChange={(event) => setLoras(loras.map((x, j) => (j === i ? { ...x, strength: Math.min(STRENGTH.max, Math.max(STRENGTH.min, Number(event.target.value) || 0)) } : x)))}
+ />
+ <button className="secondary" onClick={() => setLoras(loras.filter((_, j) => j !== i))} aria-label={`Remove LoRA ${i + 1}`}>×</button>
+ </div>
+ <label className="setting toggle">
+ <span>{isSpeedLora(l) ? "Use speed LoRA" : "Use this LoRA"}<small>Turn off to skip this LoRA and keep its settings.</small></span>
+ <input type="checkbox" aria-label={`Use LoRA ${i + 1}`} checked={l.enabled !== false}
+ onChange={(event) => setLoras(loras.map((x, j) => j === i ? { ...x, enabled: event.target.checked } : x))} />
+ <i />
+ </label>
+ {!isSpeedLora({ ...l, speed: false }) && <label className="setting toggle">
+ <span>Speed LoRA <small>Mark renamed or other few-step LoRAs here.</small></span>
+ <input type="checkbox" aria-label={`LoRA ${i + 1} is a speed LoRA`} checked={l.speed === true}
+ onChange={(event) => setLoras(loras.map((x, j) => j === i ? { ...x, speed: event.target.checked } : x))} />
+ <i />
+ </label>}
</div>
))}
{loras.length < MAX_LORAS && (
<button className="secondary" onClick={() => setLoras([...loras, { name: files.loras[0] ?? "", strength: 1 }])}>Add LoRA</button>
)}
</div>
+ </div>}
+ <div className="setting">
+ <span>Acceleration <small>{speedLora ? "Turn off the speed LoRA to use Spectrum." : "Spectrum skips some H3 evaluations and can change the result. Requires ComfyUI-Spectrum-MiniMax-H3; use 20 or more steps."}</small></span>
+ <select className="file-name" aria-label="Acceleration" value={selectedAcceleration} disabled={speedLora} onChange={(event) => setAcceleration(event.target.value as Acceleration)}>
+ <option value="none">Off</option>
+ <option value="spectrum">Spectrum</option>
+ </select>
</div>
</details>
</section>
diff --git a/components/welcome.tsx b/components/welcome.tsx
new file mode 100644
index 0000000..c762c82
--- /dev/null
+++ b/components/welcome.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import { DEFAULT_DESCRIBER } from "../lib/model.ts";
+
+const SUGGESTIONS = [
+ { name: "qwen3vl_8b_int8_convrot.safetensors", label: "Qwen3-VL 8B · INT8", size: "9.35 GB", note: "Openjutsu default", url: "https://huggingface.co/Comfy-Org/Qwen3-VL/blob/main/text_encoders/qwen3vl_8b_int8_convrot.safetensors" },
+ { name: "qwen3vl_4b_fp8_scaled.safetensors", label: "Qwen3-VL 4B · FP8", size: "5.24 GB", note: "Smaller Qwen alternative", url: "https://huggingface.co/Comfy-Org/Qwen3-VL/blob/main/text_encoders/qwen3vl_4b_fp8_scaled.safetensors" },
+ { name: "gemma4_e2b_it_int8_convrot.safetensors", label: "Gemma 4 E2B · INT8", size: "5.2 GB", note: "Smaller vision alternative", url: "https://huggingface.co/Comfy-Org/gemma-4/blob/main/text_encoders/gemma4_e2b_it_int8_convrot.safetensors" },
+];
+
+export function Welcome({ value, options, onChange, loading, error, onRefresh, onContinue }: {
+ value: string; options: string[]; onChange: (value: string) => void; loading: boolean; error: string;
+ onRefresh: () => void; onContinue: () => void;
+}) {
+ const installed = !error && options.includes(value);
+ const suggested = SUGGESTIONS.filter((model) => options.includes(model.name));
+ const other = options.filter((name) => !SUGGESTIONS.some((model) => model.name === name));
+
+ return <main className="shell welcome">
+ <header className="top"><div className="brand">
+ <span className="mark" aria-hidden>忍</span>
+ <div><h1>Openjutsu</h1><p>Open weights. Your video. Your GPU.</p></div>
+ </div></header>
+
+ <section className="welcome-intro">
+ <p className="eyebrow">BEFORE YOUR FIRST SWAP</p>
+ <h2>Welcome to Openjutsu.</h2>
+ <p>Give your video a new cast, change an object or rebuild the scene. Start by choosing the model that helps Openjutsu understand what it sees.</p>
+ <ol className="welcome-flow">
+ <li><strong>See &amp; describe</strong><span>A vision-language model reads your photos and video frames, identifies people and writes prompts.</span></li>
+ <li><strong>Track the edit</strong><span>SAM follows the people or things you want to change.</span></li>
+ <li><strong>Make the video</strong><span>MiniMax H3 uses those prompts and references to generate the result.</span></li>
+ </ol>
+ </section>
+
+ <section className="panel welcome-picker" aria-labelledby="describer-heading">
+ <div><p className="eyebrow">01 / CHOOSE YOUR VISUAL DESCRIBER</p>
+ <h2 id="describer-heading">A model that can see and write.</h2>
+ <p className="hint">Use a vision-language model (VLM) with image understanding and text generation. This choice also applies to Find people.</p>
+ </div>
+ <label htmlFor="describer">Visual describer</label>
+ <select id="describer" className="file-name" value={value} onChange={(event) => onChange(event.target.value)} disabled={loading} aria-describedby="describer-help">
+ {!options.includes(value) && <option value={value}>{value}{loading ? " — checking…" : " — not installed"}</option>}
+ {suggested.length > 0 && <optgroup label="Suggested models installed in ComfyUI">
+ {suggested.map((model) => <option key={model.name} value={model.name}>{model.label}{model.name === DEFAULT_DESCRIBER ? " (default)" : ""}</option>)}
+ </optgroup>}
+ {other.length > 0 && <optgroup label="Other installed models — check vision support">
+ {other.map((name) => <option key={name} value={name}>{name}</option>)}
+ </optgroup>}
+ </select>
+ <p id="describer-help" className="hint">Other models must work with ComfyUI’s CLIPLoader and Generate Text nodes, including image and video-frame input. A file appearing here confirms it is installed; it does not confirm vision support. Text-only models and GGUF files needing a different loader cannot be used here.</p>
+ <p className="hint">The separate MiniMax H3 text encoder stays in Model components. Choose a full vision-language model here, rather than an H3-specific encoder.</p>
+
+ <div className="welcome-install">
+ <strong>Put the model in this folder first</strong>
+ <code>ComfyUI\models\text_encoders</code>
+ <p className="hint">Use your ComfyUI installation folder. Add a compatible single-file model with its vision weights, then refresh the list. If it still does not appear, restart ComfyUI and refresh again.</p>
+ <div className="row"><span className="hint" role="status">{loading ? "Reading installed models…" : error ? "ComfyUI model list unavailable" : installed ? "Selected file is installed" : "Selected file is not installed"}</span>
+ <button className="secondary" disabled={loading} onClick={onRefresh}>{loading ? "Refreshing…" : "Refresh models"}</button></div>
+ {error && <p className="error" role="alert">{error}</p>}
+ </div>
+ </section>
+
+ <section className="panel welcome-memory" aria-labelledby="vram-heading">
+ <div><p className="eyebrow">02 / LEAVE ROOM FOR THE WORK</p><h2 id="vram-heading">Choose for your available VRAM.</h2></div>
+ <p className="hint">For limited VRAM, start with a smaller quantized model such as Qwen3-VL 4B FP8 or Gemma 4 E2B INT8. With more headroom, keep the Qwen3-VL 8B INT8 default. Higher precision usually needs more memory.</p>
+ <div className="welcome-table"><table>
+ <caption>Examples available as ComfyUI model files</caption>
+ <thead><tr><th scope="col">Model</th><th scope="col">File size</th><th scope="col">Use</th></tr></thead>
+ <tbody>{SUGGESTIONS.map((model) => <tr key={model.name}>
+ <th scope="row"><a href={model.url} target="_blank" rel="noreferrer">{model.label}</a></th>
+ <td>{model.size}</td><td>{model.note}</td>
+ </tr>)}</tbody>
+ </table></div>
+ <p className="hint">File size is a rough guide to weight storage, not a VRAM requirement. Images, video frames, context and working memory need extra space. ComfyUI may offload to system RAM, which can be slower. H3 video generation has its own, larger memory needs; this choice alone does not guarantee a full swap will fit.</p>
+ <p className="hint">Gemma needs a version with vision support. Alternative models can change prompt quality and how reliably people are matched; Openjutsu’s workflows default to Qwen3-VL 8B.</p>
+ </section>
+
+ <footer className="welcome-actions">
+ <div><strong>Your choice stays in this browser.</strong><p className="hint">Reopen Welcome &amp; models any time to change it.</p></div>
+ <div className="row"><button className="secondary" onClick={onContinue}>Set up later</button>
+ <button className="primary" disabled={loading || !installed} onClick={onContinue}>Continue to Openjutsu →</button></div>
+ </footer>
+ </main>;
+}
diff --git a/lib/comfy.ts b/lib/comfy.ts
index 9c80ff1..dc852ef 100644
--- a/lib/comfy.ts
+++ b/lib/comfy.ts
@@ -6,7 +6,7 @@ import { Asset, Comfy, COMFY_CLOUD_BASE_URL, NotFound, resolveCredentials, type
import { ComfyLow } from "@comfyorg/sdk/low";
import { MASK_NODES, NODES, cropSource, isLink, pruneMask, pruneSimple, setSection, type ApiGraph, type Margin, type Resolution, type Section, type SimpleSettings } from "./simple.ts";
import { VIDEO, nodeByTitle, pruneAdvanced, type AdvancedSettings } from "./advanced.ts";
-import { applyModel, type ModelSettings } from "./model.ts";
+import { applyDescriber, applyModel, type ModelFiles, type ModelSettings } from "./model.ts";
import { OBJECT_PICTURE, OBJECT_VIDEO, pruneFit, pruneObject, type ObjectSettings, type PlacementKeyframe } from "./object.ts";
import { FACE_PICTURE, FACE_VIDEO, pruneFace, type FaceSettings } from "./face.ts";
import { COLOR_VIDEO, pruneColor, type ColorSettings } from "./color.ts";
@@ -234,9 +234,10 @@ export async function submitMontage(video: StoredFile, section: Section, picture
return submit(comfy, workflow);
}
-export async function submitPeople(video: StoredFile, section: Section, roles: string[], resolution: Resolution) {
+export async function submitPeople(video: StoredFile, section: Section, roles: string[], resolution: Resolution, describer?: string) {
const comfy = client();
const graph = await loadGraph("people");
+ applyDescriber(graph, describer);
graph[PEOPLE_NODES.crops].inputs.people = peopleRoles(roles);
if (typeof resolution === "object") cropSource(graph, PEOPLE_NODES.video, resolution);
setSection(graph, PEOPLE_NODES.video, section);
@@ -256,15 +257,18 @@ export async function comfyUi(path: string, timeout: number) {
export const MODELS_UNAVAILABLE = "Could not read the model lists from ComfyUI. Make sure it is running and COMFYUI_URL points to it, then try again.";
// The pickers read ComfyUI's own node info; when that fails, the page falls back to typed file names.
-export async function listModels(): Promise<{ models: string[]; loras: string[] }> {
+export async function listModels(): Promise<ModelFiles> {
const options = async (node: string, input: string) => {
const names = (await comfyUi(`/object_info/${node}`, 5000))?.[node]?.input?.required?.[input]?.[0];
if (!Array.isArray(names) || names.some((name) => typeof name !== "string")) throw new Error(`ComfyUI sent no ${input} list.`);
return names as string[];
};
try {
- const [models, loras] = await Promise.all([options("UNETLoader", "unet_name"), options("LoraLoaderModelOnly", "lora_name")]);
- return { models, loras };
+ const [models, loras, textEncoders, vaes] = await Promise.all([
+ options("UNETLoader", "unet_name"), options("LoraLoaderModelOnly", "lora_name"),
+ options("CLIPLoader", "clip_name"), options("VAELoader", "vae_name"),
+ ]);
+ return { models, loras, textEncoders, vaes };
} catch (error) {
console.warn(`${MODELS_UNAVAILABLE} ${error instanceof Error ? error.message : ""}`.trim());
throw new HttpError(502, MODELS_UNAVAILABLE);
diff --git a/lib/model.ts b/lib/model.ts
index 1ad35c8..ea221e8 100644
--- a/lib/model.ts
+++ b/lib/model.ts
@@ -1,23 +1,58 @@
// Base model, LoRAs and steps, shared by every swap and edit workflow. Each export has one "H3 Diffusion Model" UNETLoader
// feeding one "DMAD LoRA" LoraLoaderModelOnly; the LoRA list replaces that node with a chain (or removes it).
import { nodeByTitle } from "./advanced.ts";
-import { isLink, type ApiGraph } from "./simple.ts";
+import { isLink, suffixRunName, type ApiGraph } from "./simple.ts";
-export type Lora = { name: string; strength: number };
-export type ModelSettings = { model: string; loras: Lora[]; steps: number };
+export type Lora = { name: string; strength: number; speed?: boolean; enabled?: boolean };
+export const ACCELERATIONS = ["none", "spectrum"] as const;
+export type Acceleration = (typeof ACCELERATIONS)[number];
+export type ModelSettings = {
+ model: string; loras: Lora[]; steps: number;
+ describer?: string; textEncoder?: string; videoVae?: string; audioVae?: string; acceleration?: Acceleration;
+};
+export type ModelFiles = { models: string[]; loras: string[]; textEncoders: string[]; vaes: string[] };
+
+export const DEFAULT_DESCRIBER = "qwen3vl_8b_int8_convrot.safetensors";
-export const DEFAULT_MODEL: ModelSettings = {
+export const DEFAULT_MODEL = {
model: "minimax_h3_ref2va_pruned_int8_convrot.safetensors",
loras: [{ name: "minimax_h3_DMAD_4step_full_lora_avg_rank_39_bf16.safetensors", strength: 1 }],
steps: 6,
-};
+ textEncoder: "qwen3vl_32b_minimax_h3_int4_convrot.safetensors",
+ videoVae: "minimax_h3_video_vae_int8_convrot.safetensors",
+ audioVae: "minimax_h3_audio_vae_fp32.safetensors",
+ acceleration: "none",
+} satisfies ModelSettings;
export const MAX_LORAS = 4;
export const STEPS = { min: 1, max: 100 };
export const STRENGTH = { min: -4, max: 4 };
-// Mutates graph: the steps (on the Swap Plan, or the Schedule in Fix faces, which has no plan), the chosen diffusion model,
-// then the LoRAs in order into whatever read the old LoRA node.
+export function isSpeedLora(lora: Lora) {
+ return lora.speed === true || /dmad|light[ _-]?x2v|turbo|(?:^|[\/ _-])(?:[12468][ _-]?steps?|lightning)(?:[_. -]|$)/i.test(lora.name.replaceAll("\\", "/"));
+}
+
+export function hasSpeedLora(loras: Lora[]) {
+ return loras.some((lora) => lora.enabled !== false && lora.strength !== 0 && isSpeedLora(lora));
+}
+
+export function checkAcceleration(settings: ModelSettings) {
+ if (!ACCELERATIONS.includes(settings.acceleration ?? "none")) throw new Error("Choose a supported acceleration option.");
+ if (settings.acceleration === "spectrum" && hasSpeedLora(settings.loras)) throw new Error("Turn off Spectrum or remove the speed LoRA.");
+}
+
+export function applyDescriber(graph: ApiGraph, name = DEFAULT_DESCRIBER) {
+ graph[nodeByTitle(graph, "Describer: Qwen3-VL 8B")].inputs.clip_name = name;
+}
+
+// Mutates graph: the steps, model components and LoRA chain.
export function applyModel(graph: ApiGraph, settings: ModelSettings) {
+ checkAcceleration(settings);
+ applyDescriber(graph, settings.describer);
+ for (const [title, input, value] of [
+ ["H3 Text Encoder", "clip_name", settings.textEncoder ?? DEFAULT_MODEL.textEncoder],
+ ["Video VAE", "vae_name", settings.videoVae ?? DEFAULT_MODEL.videoVae],
+ ["Audio VAE", "vae_name", settings.audioVae ?? DEFAULT_MODEL.audioVae],
+ ]) graph[nodeByTitle(graph, title)].inputs[input] = value;
const plans = Object.values(graph).filter((node) => ["H3OneClickSwapPlan", "H3AdvancedSwapPlan", "H3MontagePlan", "H3ObjectSwapPlan"].includes(node.class_type));
if (plans.length > 1) throw new Error(`Expected one Swap Plan node in the workflow, found ${plans.length}.`);
(plans[0] ?? graph[nodeByTitle(graph, "Schedule")]).inputs.steps = settings.steps;
@@ -28,7 +63,7 @@ export function applyModel(graph: ApiGraph, settings: ModelSettings) {
const template = graph[lora];
delete graph[lora];
let last: [string, number] = [unet, 0];
- settings.loras.forEach((l, i) => {
+ settings.loras.filter((lora) => lora.enabled !== false).forEach((l, i) => {
const id = i === 0 ? lora : `${lora}_lora${i + 1}`;
graph[id] = { ...template, inputs: { ...template.inputs, lora_name: l.name, strength_model: l.strength, model: last }, _meta: { title: `LoRA ${i + 1}` } };
last = [id, 0];
@@ -37,4 +72,43 @@ export function applyModel(graph: ApiGraph, settings: ModelSettings) {
if (id === lora || id.startsWith(`${lora}_lora`)) continue;
for (const [name, value] of Object.entries(node.inputs)) if (isLink(value) && value[0] === lora) node.inputs[name] = last;
}
+
+ // Separate saved clips when model components change; keep existing default runs resumable.
+ const componentKey = (value: ModelSettings) => JSON.stringify([
+ value.model, value.loras.filter((lora) => lora.enabled !== false && lora.strength !== 0).map(({ name, strength }) => [name, strength]),
+ value.textEncoder ?? DEFAULT_MODEL.textEncoder, value.videoVae ?? DEFAULT_MODEL.videoVae,
+ value.audioVae ?? DEFAULT_MODEL.audioVae, value.acceleration ?? "none",
+ ...(value.describer && value.describer !== DEFAULT_DESCRIBER ? [value.describer] : []),
+ ]);
+ const key = componentKey(settings);
+ if (key !== componentKey(DEFAULT_MODEL) && Object.values(graph).some((node) => node.class_type === "MiniMaxH3ChainPlanModern")) {
+ let hash = 14695981039346656037n;
+ for (const char of key) hash = BigInt.asUintN(64, (hash ^ BigInt(char.codePointAt(0)!)) * 1099511628211n);
+ suffixRunName(graph, "model_run_name", `_model${hash.toString(16)}`, "Run name for these model components");
+ }
+
+ if (settings.acceleration === "spectrum") {
+ const patched = new Map<string, string>();
+ for (const node of Object.values(graph)) {
+ if (node.class_type !== "BasicGuider" && node.class_type !== "CFGGuider") continue;
+ const model = node.inputs.model as [string, number];
+ const key = JSON.stringify(model);
+ let id = patched.get(key);
+ if (!id) {
+ id = `${model[0]}_spectrum`;
+ graph[id] = {
+ class_type: "SpectrumApplyMiniMaxH3",
+ inputs: {
+ model, enabled: true, blend_weight: 0.5, degree: 1, ridge_lambda: 0.1,
+ window_size: 2, flex_window: 0.75, warmup_steps: 1, tail_actual_steps: 1,
+ max_history: 8, debug: false, history_storage: "system_ram",
+ audio_blend_weight: 0, offline_smoothing_replay: true,
+ },
+ _meta: { title: "Spectrum acceleration" },
+ };
+ patched.set(key, id);
+ }
+ node.inputs.model = [id, 0];
+ }
+ }
}
diff --git a/lib/setup.ts b/lib/setup.ts
index bf354d4..4e39c50 100644
--- a/lib/setup.ts
+++ b/lib/setup.ts
@@ -2,7 +2,7 @@ import { pruneAdvanced, type AdvancedSettings } from "./advanced.ts";
import { comfyUi } from "./comfy.ts";
import { pruneColor, type ColorSettings } from "./color.ts";
import { pruneFace, type FaceSettings } from "./face.ts";
-import { applyModel, type ModelSettings } from "./model.ts";
+import { applyDescriber, applyModel, type ModelSettings } from "./model.ts";
import { PEOPLE_NODES, pruneMontage, type Review } from "./montage.ts";
import { pruneObject, type ObjectSettings } from "./object.ts";
import { cropSource, pruneMask, pruneSimple, type ApiGraph, type Margin, type Resolution, type SimpleSettings } from "./simple.ts";
@@ -14,7 +14,7 @@ export type SetupRequest =
| { kind: "face"; settings: FaceSettings; model: ModelSettings }
| { kind: "color"; settings: ColorSettings }
| { kind: "mask"; hatFix: boolean; margin: Margin; target: string }
- | { kind: "people"; resolution: Resolution }
+ | { kind: "people"; resolution: Resolution; describer?: string }
| { kind: "fit"; resolution: Resolution }
| { kind: "montage"; settings: AdvancedSettings; pictures: number; review: Review | null; model: ModelSettings };
@@ -29,6 +29,7 @@ type NodeInfo = { input?: { required?: Record<string, unknown[]>; optional?: Rec
export type NodeRegistry = Record<string, NodeInfo>;
const PACKS = [
+ { name: "ComfyUI-Spectrum-MiniMax-H3", url: "https://github.com/xmarre/ComfyUI-Spectrum-MiniMax-H3", nodes: ["SpectrumApplyMiniMaxH3"] },
{ name: "ComfyUI-MiniMaxH3-Context-Loop (0.7.3+)", url: "https://github.com/ethanfel/ComfyUI-MiniMaxH3-Context-Loop", nodes: ["MiniMaxH3GenerationProfile", "MiniMaxH3SourceTimeline", "MiniMaxH3ChainPlanModern", "MiniMaxH3ChainLoopStart", "MiniMaxH3ChainCurrent", "MiniMaxH3ChainContext", "MiniMaxH3ChainSegmentSave", "MiniMaxH3ChainReview", "MiniMaxH3ChainLoopEnd", "MiniMaxH3ChainAssemble", "MiniMaxH3ContexLoopSourceSlice", "MiniMaxH3ContexLoopMaskSlice", "MiniMaxH3ContexMaskedTarget", "MiniMaxH3ContexMaskGridPreview", "MiniMaxH3LoopTrim"] },
{ name: "comfyui-h3-oneclick-swap", url: "https://github.com/D3voz/comfyui-h3-oneclick-swap", nodes: ["H3OneClickSwapPlan", "H3AdvancedSwapPlan", "H3ObjectSwapPlan", "H3ObjectPlacementMask", "H3AddFitCheck", "H3AddMovingArea", "H3PaintedEditArea", "H3SoundtrackOrSilence", "H3PeopleMask", "H3GreyMannequins", "H3ClipShots", "H3FillShots", "H3TrackCrops", "H3TrackRoles", "H3RoleMask", "H3SubjectPrompt", "H3MontagePeople", "H3MontageTracks", "H3MontagePicks", "H3MontagePlan", "H3MontagePass", "H3FaceChunks", "H3FaceJoin"] },
{ name: "ComfyUI-Fantastic-MiniMaxH3-PromptBuilder", url: "https://github.com/Adudeguyman/ComfyUI-Fantastic-MiniMaxH3-PromptBuilder", nodes: ["MiniMaxH3FantasticVideoEditLatent"] },
@@ -64,6 +65,7 @@ export function setupGraph(source: ApiGraph, selection: SetupRequest): ApiGraph
if (typeof selection.resolution === "object") cropSource(graph, PEOPLE_NODES.video, selection.resolution);
} else graph = pruneAdvanced(source, selection.pictures, selection.settings);
if ("model" in selection) applyModel(graph, selection.model);
+ else if (selection.kind === "people") applyDescriber(graph, selection.describer);
return graph;
}
diff --git a/test/jobs.test.ts b/test/jobs.test.ts
index 12f0259..af43b2e 100644
--- a/test/jobs.test.ts
+++ b/test/jobs.test.ts
@@ -143,7 +143,7 @@ test("outputs are served only for their own job, as video, image or JSON, with n
});
test("COMFYUI_URL may end in a slash, and a failed model list is reported instead of skipping the check", async () => {
- assert.deepEqual(await (await getModels(new Request("http://127.0.0.1:3000/api/models"))).json(), { models: ["base.safetensors"], loras: ["style.safetensors"] });
+ assert.deepEqual(await (await getModels(new Request("http://127.0.0.1:3000/api/models"))).json(), { models: ["base.safetensors"], loras: ["style.safetensors", "minimax_h3_DMAD.safetensors"], textEncoders: ["encoder.safetensors"], vaes: ["video.safetensors", "audio.safetensors"] });
let response = await post({ ...SIMPLE, model: "other.safetensors", video: mp4(), picture: png() });
assert.equal((await response.json()).error, "Choose a base model ComfyUI has.");
@@ -152,7 +152,7 @@ test("COMFYUI_URL may end in a slash, and a failed model list is reported instea
try {
response = await getModels(new Request("http://127.0.0.1:3000/api/models"));
assert.equal(response.status, 502);
- assert.deepEqual({ ...(await response.json()), error: undefined }, { models: [], loras: [], error: undefined });
+ assert.deepEqual({ ...(await response.json()), error: undefined }, { models: [], loras: [], textEncoders: [], vaes: [], error: undefined });
response = await post({ ...SIMPLE, video: mp4(), picture: png() });
assert.equal(response.status, 502);
assert.match((await response.json()).error, /COMFYUI_URL/);
@@ -175,3 +175,49 @@ test("three uploads can arrive at once, and a fourth is asked to wait", async ()
assert.equal((await post({ mode: "mask", video: mp4() })).status, 202);
assert.deepEqual(await leftovers(), []);
});
+
+test("encoder and VAE selections are validated against ComfyUI before uploads", async () => {
+ const uploads = proxy.uploads.length;
+ for (const field of ["text_encoder", "video_vae", "audio_vae"]) {
+ const response = await post({ ...SIMPLE, [field]: "missing.safetensors", video: mp4(), picture: png() });
+ assert.equal(response.status, 400);
+ assert.match((await response.json()).error, /ComfyUI has/);
+ }
+ assert.equal(proxy.uploads.length, uploads);
+ const response = await post({ ...SIMPLE, text_encoder: "encoder.safetensors", video_vae: "video.safetensors", audio_vae: "audio.safetensors", acceleration: "spectrum", video: mp4(), picture: png() });
+ assert.equal(response.status, 202, JSON.stringify(await response.clone().json()));
+});
+
+test("the submission API rejects Spectrum with known or manually marked speed LoRAs", async () => {
+ const uploads = proxy.uploads.length;
+ for (const fields of [
+ { lora: "minimax_h3_DMAD.safetensors", lora_speed: "false" },
+ { lora: "style.safetensors", lora_speed: "true" },
+ ]) {
+ const response = await post({ ...SIMPLE, ...fields, lora_strength: "1", acceleration: "spectrum", video: mp4(), picture: png() });
+ assert.equal(response.status, 400);
+ assert.match((await response.json()).error, /speed LoRA/);
+ }
+ const invalid = await post({ ...SIMPLE, acceleration: "unknown", video: mp4(), picture: png() });
+ assert.equal(invalid.status, 400);
+ assert.equal(proxy.uploads.length, uploads);
+ const response = await post({ ...SIMPLE, lora: "style.safetensors", lora_strength: "1", acceleration: "spectrum", video: mp4(), picture: png() });
+ assert.equal(response.status, 202);
+});
+
+
+test("visual describers are validated before upload and reach swaps and Find people", async () => {
+ for (const mode of ["simple", "people"]) {
+ const uploads = proxy.uploads.length;
+ const invalid = await post({ ...SIMPLE, mode, role: "the dancer - white polo, jeans", describer: "../missing.safetensors", video: mp4(), picture: png() });
+ assert.equal(invalid.status, 400);
+ assert.match((await invalid.json()).error, /visual describer/);
+ assert.equal(proxy.uploads.length, uploads);
+ const response = await post({ ...SIMPLE, mode, role: "the dancer - white polo, jeans", describer: "encoder.safetensors", video: mp4(), picture: png() });
+ assert.equal(response.status, 202, JSON.stringify(await response.clone().json()));
+ const job = await response.json();
+ const workflow = JSON.stringify(proxy.jobs.get(job.id)!.workflow);
+ assert.match(workflow, /encoder\.safetensors/);
+ assert.doesNotMatch(workflow, /qwen3vl_8b_int8_convrot/);
+ }
+});
diff --git a/test/model.test.ts b/test/model.test.ts
index e7c4e26..03c0334 100644
--- a/test/model.test.ts
+++ b/test/model.test.ts
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { nodeByTitle } from "../lib/advanced.ts";
-import { DEFAULT_MODEL, applyModel } from "../lib/model.ts";
+import { DEFAULT_MODEL, applyModel, hasSpeedLora } from "../lib/model.ts";
import { isLink, type ApiGraph } from "../lib/simple.ts";
const load = (name: string): ApiGraph => JSON.parse(readFileSync(new URL(`../workflows/${name}.api.json`, import.meta.url), "utf8"));
@@ -56,3 +56,109 @@ test("no LoRAs feed the base model straight to the sampler", () => {
for (const [id, input] of readers) assert.deepEqual(g[id].inputs[input], [unet, 0], name);
}
});
+
+const generationWorkflows = ["simple", "advanced", "advanced_maxq", "object", "face", "montage"];
+
+test("H3 encoder and both VAE choices reach all generation workflows without changing the describer", () => {
+ for (const name of generationWorkflows) {
+ const graph = load(name);
+ const describer = structuredClone(graph[nodeByTitle(graph, "Describer: Qwen3-VL 8B")]);
+ applyModel(graph, { ...DEFAULT_MODEL, textEncoder: "qwen32b_int8.safetensors", videoVae: "video_bf16.safetensors", audioVae: "audio_bf16.safetensors" });
+ assert.equal(graph[nodeByTitle(graph, "H3 Text Encoder")].inputs.clip_name, "qwen32b_int8.safetensors", name);
+ assert.equal(graph[nodeByTitle(graph, "H3 Text Encoder")].inputs.type, "minimax", name);
+ assert.equal(graph[nodeByTitle(graph, "Video VAE")].inputs.vae_name, "video_bf16.safetensors", name);
+ assert.equal(graph[nodeByTitle(graph, "Audio VAE")].inputs.vae_name, "audio_bf16.safetensors", name);
+ assert.deepEqual(graph[nodeByTitle(graph, "Describer: Qwen3-VL 8B")], describer, name);
+ assert.deepEqual(dangling(graph), [], name);
+ }
+});
+
+test("Spectrum is placed after the model patches and feeds every guider, including both Advanced passes", () => {
+ for (const name of generationWorkflows) {
+ const graph = load(name);
+ const guiders = Object.values(graph).filter((node) => node.class_type === "BasicGuider");
+ const upstream = guiders.map((node) => node.inputs.model);
+ applyModel(graph, { ...DEFAULT_MODEL, loras: [], steps: 20, acceleration: "spectrum" });
+ const spectrum = Object.entries(graph).filter(([, node]) => node.class_type === "SpectrumApplyMiniMaxH3");
+ assert.equal(spectrum.length, 1, name);
+ assert.deepEqual(spectrum[0][1].inputs.model, upstream[0], name);
+ for (const guider of guiders) assert.deepEqual(guider.inputs.model, [spectrum[0][0], 0], name);
+ assert.deepEqual(dangling(graph), [], name);
+ assert.equal(loras(graph).length, 0, name);
+ }
+});
+
+test("Spectrum stays absent by default and rejects speed LoRAs before changing the graph", () => {
+ const graph = load("simple");
+ applyModel(graph, DEFAULT_MODEL);
+ assert.ok(Object.values(graph).every((node) => node.class_type !== "SpectrumApplyMiniMaxH3"));
+ for (const lora of [DEFAULT_MODEL.loras[0], { name: "renamed.safetensors", strength: 1, speed: true }]) {
+ const graph = load("simple");
+ const before = structuredClone(graph);
+ assert.throws(() => applyModel(graph, { ...DEFAULT_MODEL, loras: [lora], acceleration: "spectrum" }), /speed LoRA/);
+ assert.deepEqual(graph, before);
+ }
+ assert.equal(hasSpeedLora([{ ...DEFAULT_MODEL.loras[0], strength: 0 }]), false);
+ assert.equal(hasSpeedLora([{ name: "style.safetensors", strength: 1 }]), false);
+ for (const name of ["h3_LightX2V.safetensors", "h3_turbo.safetensors", "h3_4step.safetensors", "packs\\4step.safetensors"]) {
+ assert.equal(hasSpeedLora([{ name, strength: 1 }]), true, name);
+ }
+});
+
+test("component changes get distinct saved runs, while defaults and speed labels preserve the same run", () => {
+ const run = (settings: Parameters<typeof applyModel>[1]) => {
+ const graph = load("simple");
+ applyModel(graph, settings);
+ return graph.model_run_name?.inputs.string_b;
+ };
+ assert.equal(run(DEFAULT_MODEL), undefined);
+ assert.equal(run({ ...DEFAULT_MODEL, loras: DEFAULT_MODEL.loras.map((lora) => ({ ...lora, speed: true })) }), undefined);
+ const variants = [
+ { ...DEFAULT_MODEL, loras: [] },
+ { ...DEFAULT_MODEL, textEncoder: "other.safetensors" },
+ { ...DEFAULT_MODEL, videoVae: "other.safetensors" },
+ { ...DEFAULT_MODEL, audioVae: "other.safetensors" },
+ { ...DEFAULT_MODEL, loras: [], acceleration: "spectrum" as const },
+ ];
+ const names = variants.map(run);
+ assert.ok(names.every((name) => typeof name === "string" && /^_model[0-9a-f]+$/.test(name)));
+ assert.equal(new Set(names).size, variants.length);
+ assert.equal(run(variants[1]), run(variants[1]));
+});
+
+test("a disabled speed LoRA is bypassed while style LoRAs and Spectrum remain active", () => {
+ const selected = [
+ { ...DEFAULT_MODEL.loras[0], enabled: false },
+ { name: "style.safetensors", strength: 0.8 },
+ ];
+ assert.equal(hasSpeedLora(selected), false);
+ for (const name of generationWorkflows) {
+ const graph = load(name);
+ applyModel(graph, { ...DEFAULT_MODEL, loras: selected, steps: 20, acceleration: "spectrum" });
+ assert.deepEqual(loras(graph).map(([, node]) => node.inputs.lora_name), ["style.safetensors"], name);
+ assert.equal(Object.values(graph).filter((node) => node.class_type === "SpectrumApplyMiniMaxH3").length, 1, name);
+ assert.deepEqual(dangling(graph), [], name);
+ }
+ const disabled = load("simple");
+ const removed = load("simple");
+ applyModel(disabled, { ...DEFAULT_MODEL, loras: [{ ...DEFAULT_MODEL.loras[0], enabled: false }], acceleration: "spectrum" });
+ applyModel(removed, { ...DEFAULT_MODEL, loras: [], acceleration: "spectrum" });
+ assert.deepEqual(disabled, removed, "disabling and removing the speed LoRA use the same workflow and saved-run identity");
+});
+
+
+test("changing the visual describer preserves H3 encoding and separates saved clips", () => {
+ for (const name of ["simple", "advanced", "advanced_maxq", "object", "face", "montage"]) {
+ const original = load(name);
+ const graph = load(name);
+ applyModel(original, DEFAULT_MODEL);
+ applyModel(graph, { ...DEFAULT_MODEL, describer: "gemma4_e2b_it_int8_convrot.safetensors" });
+ assert.equal(graph[nodeByTitle(graph, "Describer: Qwen3-VL 8B")].inputs.clip_name, "gemma4_e2b_it_int8_convrot.safetensors", name);
+ assert.equal(graph[nodeByTitle(graph, "H3 Text Encoder")].inputs.clip_name, DEFAULT_MODEL.textEncoder, name);
+ assert.deepEqual(dangling(graph), [], name);
+ if (Object.values(graph).some((node) => node.class_type === "MiniMaxH3ChainPlanModern")) {
+ assert.equal(original.model_run_name, undefined, name);
+ assert.match(String(graph.model_run_name.inputs.string_b), /^_model[0-9a-f]+$/, name);
+ }
+ }
+});
diff --git a/test/proxy.ts b/test/proxy.ts
index 84fc5e9..ddf39cf 100644
--- a/test/proxy.ts
+++ b/test/proxy.ts
@@ -5,14 +5,17 @@ import type { AddressInfo } from "node:net";
// Just enough of comfy-api-proxy 0.1.6 for the upload, job, output and delete paths. Like the proxy, identical bytes
// map to one asset id, and uploads are counted rather than kept.
type FakeAsset = { id: string; hash: string; size: number; contentType: string; filePath: string; jobId?: string; body?: string };
-type FakeJob = { id: string; status: string; inputs: string[]; outputs: FakeAsset[] };
+type FakeJob = { workflow: unknown; id: string; status: string; inputs: string[]; outputs: FakeAsset[] };
export async function fakeProxy() {
const assets = new Map<string, FakeAsset>();
const jobs = new Map<string, FakeJob>();
const deleted: string[] = [];
const uploads: FakeAsset[] = [];
- const models = { UNETLoader: ["base.safetensors"], LoraLoaderModelOnly: ["style.safetensors"] };
+ const models = {
+ UNETLoader: ["base.safetensors"], LoraLoaderModelOnly: ["style.safetensors", "minimax_h3_DMAD.safetensors"],
+ CLIPLoader: ["encoder.safetensors"], VAELoader: ["video.safetensors", "audio.safetensors"],
+ };
const state = { rejectJobs: false };
let base = "";
@@ -56,7 +59,7 @@ export async function fakeProxy() {
let match: RegExpMatchArray | null;
if ((match = path.match(/^\/object_info\/(\w+)$/))) {
const node = match[1] as keyof typeof models;
- const input = node === "UNETLoader" ? "unet_name" : "lora_name";
+ const input = { UNETLoader: "unet_name", LoraLoaderModelOnly: "lora_name", CLIPLoader: "clip_name", VAELoader: "vae_name" }[node];
return models[node] ? json(response, 200, { [node]: { input: { required: { [input]: [models[node]] } } } }) : missing(response);
}
if (request.method === "HEAD" && (match = path.match(/^\/api\/v2\/assets\/by-hash\/(.+)$/))) {
@@ -90,7 +93,7 @@ export async function fakeProxy() {
const refs = [...JSON.stringify(workflow).matchAll(/"__type":"core\/ASSET","info":\{"id":"([^"]+)"/g)].map((ref) => ref[1]);
if (state.rejectJobs) return json(response, 422, { error: { code: "invalid_workflow", message: "Workflow rejected." } });
if (refs.some((id) => !assets.has(id))) return json(response, 422, { error: { code: "missing_asset", message: "Unresolvable core/ASSET reference(s)." } });
- const job = { id: randomUUID(), status: "queued", inputs: refs, outputs: [] };
+ const job = { workflow, id: randomUUID(), status: "queued", inputs: refs, outputs: [] };
jobs.set(job.id, job);
return json(response, 201, jobJson(job));
}
diff --git a/test/setup.test.ts b/test/setup.test.ts
index b93cc64..6a48151 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -188,3 +188,31 @@ test("painted Change checks the paint and loop-mask nodes only when needed", ()
assert.ok(missing.packs.some((p) => p.url === "https://github.com/D3voz/comfyui-h3-oneclick-swap" && p.nodes.includes("H3PaintedEditArea")));
assert.ok(missing.packs.some((p) => p.nodes.includes("MiniMaxH3ContexLoopMaskSlice")));
});
+
+test("selected encoder, VAEs and Spectrum participate in the setup check", () => {
+ const graph = setupGraph(load("simple"), { ...simple, model: {
+ ...DEFAULT_MODEL, loras: [], textEncoder: "encoder.safetensors", videoVae: "video.safetensors", audioVae: "audio.safetensors", acceleration: "spectrum",
+ } });
+ const registry = registryFor(graph);
+ assert.equal(inspectSetup(graph, registry).ok, true);
+ delete registry.SpectrumApplyMiniMaxH3;
+ registry.CLIPLoader.input!.required!.clip_name = [["qwen3vl_8b_int8_convrot.safetensors"]];
+ registry.VAELoader.input!.required!.vae_name = [[]];
+ const missing = inspectSetup(graph, registry);
+ assert.equal(missing.packs[0].url, "https://github.com/xmarre/ComfyUI-Spectrum-MiniMax-H3");
+ assert.deepEqual(missing.models, [
+ { name: "encoder.safetensors", folder: "text_encoders" },
+ { name: "video.safetensors", folder: "vae" },
+ { name: "audio.safetensors", folder: "vae" },
+ ]);
+});
+
+
+test("Find people checks the selected visual describer", () => {
+ const graph = setupGraph(load("people"), { kind: "people", resolution: "480p", describer: "gemma.safetensors" });
+ const registry = registryFor(graph);
+ registry.CLIPLoader.input!.required!.clip_name = [["qwen.safetensors"]];
+ assert.deepEqual(inspectSetup(graph, registry).models, [{ name: "gemma.safetensors", folder: "text_encoders" }]);
+ registry.CLIPLoader.input!.required!.clip_name = [["gemma.safetensors"]];
+ assert.equal(inspectSetup(graph, registry).ok, true);
+});