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 a tracked edit-area brush to Change mode (#18)

mixbaged4c2925a666
diff --git a/README.md b/README.md
index 92240e6..9df2adf 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,7 @@ Advanced motion transfer has a **Montage** tab for edited clips where different
## Tips
+- **Paint an edit area:** under Object swap -> Change, expand **Paint edit area** and brush extra space around the tracked part. Use the eraser, brush size and keyframe controls to refine it. During generation the painting follows SAM's bounding box in position and scale; it switches off when the track is missing. The edit includes both SAM's mask and the paint, followed by the chosen mask margin. With no paint, Change is unchanged. Update `comfyui-h3-oneclick-swap` and restart ComfyUI for `H3PaintedEditArea`.
- **Add an object:** under Object swap, choose **Add**. Describe the object (for example `a chocolate cake on a plate`) and where it goes (`on the table`). Draw a box covering the whole object and its shadow in the placement editor. An optional reference picture controls its appearance. One box stays fixed on screen; for camera movement, scrub forward and draw more boxes to animate the placement. This uses manual placement keyframes, not SAM tracking. Changing the source video, selected section or resolution clears the boxes. Update `comfyui-h3-oneclick-swap` and restart ComfyUI to load the new `H3ObjectPlacementMask` node.
- Only the main person is regenerated; anyone else in the video stays as they are.
diff --git a/app/api/jobs/route.ts b/app/api/jobs/route.ts
index 291df17..c66f7ff 100644
--- a/app/api/jobs/route.ts
+++ b/app/api/jobs/route.ts
@@ -7,7 +7,7 @@ import { DEFAULT_TONE, DETAIL, TONE_MODES, TONE_RANGES, type ColorSettings, type
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 { EDIT_MODES, OBJECT_MARGINS, parsePlacement, type EditMode, type ObjectMargin, type ObjectSettings } from "../../../lib/object.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";
export const runtime = "nodejs";
@@ -84,6 +84,7 @@ function parseObject(form: FormData) {
const settings: ObjectSettings = {
mode: mode as EditMode, target, changeTo, biggestOnly: form.get("biggest_only") === "true", keepOutline: form.get("keep_outline") === "true",
margin: margin as ObjectMargin, ...parseRun(form),
+ ...(mode === "change" ? { paint: parsePaint(form.get("paint")) } : {}),
...(mode === "add" ? { placement: parsePlacement(form.get("placement")), action: String(form.get("action") ?? "").replace(/\s+/g, " ").trim().slice(0, 300) } : {}),
};
return { picture, settings };
diff --git a/components/object-placement.tsx b/components/object-placement.tsx
index 2feb29d..11212f0 100644
--- a/components/object-placement.tsx
+++ b/components/object-placement.tsx
@@ -1,23 +1,31 @@
"use client";
import { useCallback, useEffect, useRef, useState, type PointerEvent } from "react";
-import { placementAt, type PlacementKeyframe } from "../lib/object.ts";
+import { placementAt, type PaintKeyframe, type PlacementKeyframe } from "../lib/object.ts";
type Box = Omit<PlacementKeyframe, "frame">;
+type Props = { src: string; start: number; end: number; width: number; height: number } & (
+ | { mode?: "box"; points: PlacementKeyframe[]; onChange: (points: PlacementKeyframe[]) => void }
+ | { mode: "paint"; points: PaintKeyframe[]; onChange: (points: PaintKeyframe[]) => void }
+);
-export function ObjectPlacement({ src, start, end, width, height, points, onChange }: {
- src: string; start: number; end: number; width: number; height: number;
- points: PlacementKeyframe[]; onChange: (points: PlacementKeyframe[]) => void;
-}) {
+export function ObjectPlacement(props: Props) {
+ const { src, start, end, width, height, points } = props;
+ const painting = props.mode === "paint";
const video = useRef<HTMLVideoElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
+ const mask = useRef<HTMLCanvasElement | null>(null);
const origin = useRef<{ x: number; y: number } | null>(null);
const [time, setTime] = useState(start);
const [draft, setDraft] = useState<Box | null>(null);
+ const [eraser, setEraser] = useState(false);
+ const [brush, setBrush] = useState(32);
const frame = Math.round(time * 24);
const scale = Math.min(1, 1024 / Math.max(width, height));
const cw = Math.max(1, Math.round(width * scale));
const ch = Math.max(1, Math.round(height * scale));
+ const mw = Math.max(1, Math.round(cw * 256 / Math.max(cw, ch)));
+ const mh = Math.max(1, Math.round(ch * 256 / Math.max(cw, ch)));
const draw = useCallback(() => {
const v = video.current;
@@ -28,20 +36,45 @@ export function ObjectPlacement({ src, start, end, width, height, points, onChan
const cover = Math.max(c.width / v.videoWidth, c.height / v.videoHeight);
const sw = c.width / cover, sh = c.height / cover;
ctx.drawImage(v, (v.videoWidth - sw) / 2, (v.videoHeight - sh) / 2, sw, sh, 0, 0, c.width, c.height);
- const box = draft ?? placementAt(points, frame);
- if (box) {
- ctx.fillStyle = "rgba(214, 255, 63, 0.25)";
- ctx.strokeStyle = "#d6ff3f";
- ctx.lineWidth = Math.max(2, c.width / 300);
- ctx.fillRect(box.x * c.width, box.y * c.height, box.width * c.width, box.height * c.height);
- ctx.strokeRect(box.x * c.width, box.y * c.height, box.width * c.width, box.height * c.height);
+ if (props.mode === "paint") {
+ if (mask.current) {
+ ctx.globalAlpha = 0.5;
+ ctx.drawImage(mask.current, 0, 0, c.width, c.height);
+ ctx.globalAlpha = 1;
+ }
+ } else {
+ const box = draft ?? placementAt(props.points, frame);
+ if (box) {
+ ctx.fillStyle = "rgba(214, 255, 63, 0.25)";
+ ctx.strokeStyle = "#d6ff3f";
+ ctx.lineWidth = Math.max(2, c.width / 300);
+ ctx.fillRect(box.x * c.width, box.y * c.height, box.width * c.width, box.height * c.height);
+ ctx.strokeRect(box.x * c.width, box.y * c.height, box.width * c.width, box.height * c.height);
+ }
}
- }, [draft, points, frame]);
+ }, [draft, props.mode, points, frame]);
useEffect(() => { setTime(start); }, [start, src]);
+ useEffect(() => { if (video.current) video.current.currentTime = time; }, [time, src]);
useEffect(() => {
- if (video.current) video.current.currentTime = time;
- }, [time, src]);
+ if (props.mode !== "paint") return;
+ const c = document.createElement("canvas");
+ c.width = mw; c.height = mh;
+ const ctx = c.getContext("2d")!;
+ const p = props.points.find((p) => p.frame === frame);
+ if (p) {
+ const image = ctx.createImageData(p.width, p.height);
+ for (let i = 0; i < p.runs.length; i += 2) {
+ for (let j = p.runs[i]; j < p.runs[i] + p.runs[i + 1]; j++) image.data.set([214, 255, 63, 255], j * 4);
+ }
+ const stored = document.createElement("canvas");
+ stored.width = p.width; stored.height = p.height;
+ stored.getContext("2d")!.putImageData(image, 0, 0);
+ ctx.drawImage(stored, 0, 0, mw, mh);
+ }
+ mask.current = c;
+ draw();
+ }, [props.mode, points, frame, mw, mh, draw]);
useEffect(draw, [draw, cw, ch]);
function position(event: PointerEvent<HTMLCanvasElement>) {
@@ -57,39 +90,81 @@ export function ObjectPlacement({ src, start, end, width, height, points, onChan
width: Math.abs(point.x - origin.current.x), height: Math.abs(point.y - origin.current.y) };
}
+ function stroke(event: PointerEvent<HTMLCanvasElement>) {
+ const c = mask.current;
+ if (!origin.current || !c) return;
+ const p = position(event), ctx = c.getContext("2d")!;
+ ctx.globalCompositeOperation = eraser ? "destination-out" : "source-over";
+ ctx.strokeStyle = ctx.fillStyle = "#d6ff3f";
+ ctx.lineWidth = brush * mw / cw;
+ ctx.lineCap = ctx.lineJoin = "round";
+ ctx.beginPath(); ctx.moveTo(origin.current.x * mw, origin.current.y * mh); ctx.lineTo(p.x * mw, p.y * mh); ctx.stroke();
+ ctx.beginPath(); ctx.arc(p.x * mw, p.y * mh, ctx.lineWidth / 2, 0, Math.PI * 2); ctx.fill();
+ origin.current = p;
+ draw();
+ }
+
+ function savePaint() {
+ if (props.mode !== "paint" || !mask.current) return;
+ const data = mask.current.getContext("2d")!.getImageData(0, 0, mw, mh).data;
+ const runs: number[] = [];
+ for (let i = 0; i < mw * mh;) {
+ if (data[i * 4 + 3] < 128) { i++; continue; }
+ const start = i++;
+ while (i < mw * mh && data[i * 4 + 3] >= 128) i++;
+ runs.push(start, i - start);
+ }
+ const rest = props.points.filter((p) => p.frame !== frame);
+ props.onChange((runs.length ? [...rest, { frame, width: mw, height: mh, runs }] : rest).sort((a, b) => a.frame - b.frame));
+ }
+
+ function remove(all = false) {
+ if (props.mode === "paint") props.onChange(all ? [] : props.points.filter((p) => p.frame !== frame));
+ else props.onChange(all ? [] : props.points.filter((p) => p.frame !== frame));
+ }
+
return (
<div className="placement">
- <strong>Place the new object</strong>
- <p className="hint">Drag a box around the whole object&apos;s space, including its height above the surface and room for its shadow.</p>
+ <strong>{painting ? "Paint edit area" : "Place the new object"}</strong>
+ <p className="hint">{painting ? "Paint extra space around the part SAM tracks. The paint follows its position and size; the tracked area is also edited." : "Drag a box around the whole object's space, including its height above the surface and room for its shadow."}</p>
+ {painting && <>
+ <div className="segmented">
+ <button className={!eraser ? "on" : ""} aria-pressed={!eraser} onClick={() => setEraser(false)}>Brush</button>
+ <button className={eraser ? "on" : ""} aria-pressed={eraser} onClick={() => setEraser(true)}>Eraser</button>
+ </div>
+ <label>Brush size: {brush} px<input type="range" min={4} max={160} step={2} value={brush} onChange={(e) => setBrush(Number(e.target.value))} /></label>
+ </>}
<video ref={video} src={src} preload="auto" muted playsInline hidden
onLoadedMetadata={() => { if (video.current) video.current.currentTime = time; }} onLoadedData={draw} onSeeked={draw} />
- <canvas ref={canvas} width={cw} height={ch} aria-label="Draw the new object's placement box" role="img"
+ <canvas ref={canvas} width={cw} height={ch} aria-label={painting ? "Paint the edit area" : "Draw the new object's placement box"} role="img"
onPointerDown={(event) => {
- event.preventDefault();
- event.currentTarget.setPointerCapture(event.pointerId);
+ event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId);
origin.current = position(event);
- setDraft({ ...origin.current, width: 0, height: 0 });
+ if (painting) stroke(event);
+ else setDraft({ ...origin.current, width: 0, height: 0 });
}}
- onPointerMove={(event) => { const box = boxAt(event); if (box) setDraft(box); }}
+ onPointerMove={(event) => { if (painting) stroke(event); else { const box = boxAt(event); if (box) setDraft(box); } }}
onPointerUp={(event) => {
- const box = boxAt(event);
- origin.current = null;
- setDraft(null);
- if (box && box.width > 0 && box.height > 0) onChange([...points.filter((p) => p.frame !== frame), { frame, ...box }].sort((a, b) => a.frame - b.frame));
+ if (props.mode === "paint") { stroke(event); savePaint(); }
+ else {
+ const box = boxAt(event);
+ if (box && box.width > 0 && box.height > 0) props.onChange([...props.points.filter((p) => p.frame !== frame), { frame, ...box }].sort((a, b) => a.frame - b.frame));
+ }
+ origin.current = null; setDraft(null);
}}
- onPointerCancel={() => { origin.current = null; setDraft(null); }} />
- <label>Placement frame: {time.toFixed(2)} s
+ onPointerCancel={() => { if (painting) savePaint(); origin.current = null; setDraft(null); }} />
+ <label>{painting ? "Paint" : "Placement"} frame: {time.toFixed(2)} s
<input type="range" min={start} max={Math.max(start, end - 1 / 24)} step={1 / 24} value={time}
onChange={(event) => setTime(Number(event.target.value))} />
</label>
<div className="row">
- <button className="secondary" disabled={!points.some((p) => p.frame === frame)} onClick={() => onChange(points.filter((p) => p.frame !== frame))}>Remove this keyframe</button>
- <button className="secondary" disabled={!points.length} onClick={() => onChange([])}>Clear placement</button>
+ <button className="secondary" disabled={!points.some((p) => p.frame === frame)} onClick={() => remove()}>Remove this keyframe</button>
+ <button className="secondary" disabled={!points.length} onClick={() => remove(true)}>{painting ? "Clear paint" : "Clear placement"}</button>
</div>
{points.length > 0 && <div className="placement-keys">{points.map((p) => (
<button key={p.frame} className={p.frame === frame ? "on" : ""} onClick={() => setTime(Math.max(start, Math.min(end - 1 / 24, p.frame / 24)))}>{(p.frame / 24).toFixed(2)} s</button>
))}</div>}
- <p className="hint">One box stays fixed on screen. If the camera moves, scrub forward and draw more boxes; placement moves between them. This is manual placement, not automatic tracking. Changing the video, section or resolution clears the boxes.</p>
+ <p className="hint">{painting ? "Scrub to paint another keyframe. Paint follows SAM during generation and turns off when tracking is lost. This editor shows paint on its painted frames. Changing the tracked part, video, section or resolution clears paint." : "One box stays fixed on screen. If the camera moves, scrub forward and draw more boxes; placement moves between them. This is manual placement, not automatic tracking. Changing the video, section or resolution clears the boxes."}</p>
</div>
);
}
diff --git a/components/openjutsu.tsx b/components/openjutsu.tsx
index 6b9a60c..c5f3782 100644
--- a/components/openjutsu.tsx
+++ b/components/openjutsu.tsx
@@ -8,7 +8,7 @@ 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 type { EditMode, PlacementKeyframe } from "../lib/object.ts";
+import type { EditMode, PaintKeyframe, PlacementKeyframe } from "../lib/object.ts";
import { CONTROL_MAX_SECONDS } from "../lib/control.ts";
import { ObjectPlacement } from "./object-placement.tsx";
import { CHUNK_SECONDS, FACE_STYLES, faceChunkCount, type FaceStyle } from "../lib/face.ts";
@@ -256,6 +256,7 @@ export function Openjutsu() {
const [biggestOnly, setBiggestOnly] = useState(false);
const [keepOutline, setKeepOutline] = useState(true);
const [placement, setPlacement] = useState<PlacementKeyframe[]>([]);
+ const [paint, setPaint] = useState<PaintKeyframe[]>([]);
const [post, setPost] = useState<Post>("face");
const [detailOn, setDetailOn] = useState(true);
const [detail, setDetail] = useState(DETAIL.default);
@@ -446,7 +447,8 @@ export function Openjutsu() {
const canvas = typeof resolution === "object" ? [resolution.width, resolution.height] : video?.width ? canvasSize(video.width, video.height, resolution) : null;
const resolutionField = typeof resolution === "object" ? `${resolution.width}x${resolution.height}` : resolution;
- useEffect(() => setPlacement([]), [video?.url, resolutionField]);
+ useEffect(() => { setPlacement([]); setPaint([]); }, [video?.url, resolutionField, whole, part.start, part.length]);
+ useEffect(() => setPaint([]), [editTarget]);
// A montage render masks with the tracks Find people saved, so it must use the frames Find people saw.
const frames = video ? `${video.file.name}:${video.file.size} ${whole ? "whole" : `${part.start.toFixed(2)}+${part.length.toFixed(2)}`} ${typeof resolution === "object" ? resolutionField : ""}` : "";
// A job reopened from Recent jobs may have used another video, part or size than the one loaded now.
@@ -556,6 +558,7 @@ export function Openjutsu() {
if (look && editMode !== "remove") form.set("picture", look.file);
form.set("biggest_only", String(biggestOnly));
form.set("keep_outline", String(keepOutline));
+ if (editMode === "change" && paint.length) form.set("paint", JSON.stringify(paint.map((p) => ({ ...p, frame: p.frame - Math.round((whole ? 0 : part.start) * 24) }))));
if (editMode === "add") {
form.set("placement", JSON.stringify(placement.map((p) => ({ ...p, frame: p.frame - Math.round((whole ? 0 : part.start) * 24) }))));
form.set("action", action);
@@ -580,6 +583,7 @@ export function Openjutsu() {
else if (kind === "advanced" || kind === "advanced_maxq") selection = { kind, settings: { ...shared, roles: shown.map((c) => c.role) }, pictures: shown.length, model: selectedModel };
else if (kind === "montage") selection = { kind, settings: { ...shared, roles: shown.map((c) => c.role) }, pictures: shown.length, review: review ?? null, model: selectedModel };
else if (kind === "object") selection = { kind, settings: { ...shared, mode: editMode as EditMode, target: String(form.get("target")), changeTo, biggestOnly, keepOutline,
+ ...(editMode === "change" ? { paint: paint.map((p) => ({ ...p, frame: p.frame - Math.round((whole ? 0 : part.start) * 24) })) } : {}),
...(editMode === "add" ? { placement: placement.map((p) => ({ ...p, frame: p.frame - Math.round((whole ? 0 : part.start) * 24) })) } : {}) }, picture: !!look && editMode !== "remove", model: selectedModel };
else if (kind === "control") selection = { kind, settings: { target: String(form.get("target")), resolution, noLipSync, seed }, model: selectedModel };
else if (kind === "face") selection = { kind, settings: { style: faceStyle, seed, chunkSeconds }, model: selectedModel };
@@ -856,6 +860,12 @@ export function Openjutsu() {
{fromPicture && "The person in the video becomes the person in the picture: face, hair and outfit. The background, motion, camera and sound stay."}
{controlNet && `The person and the place both come from the picture. A depth map of the person in the video keeps their framing, camera and motion; the sound stays. Everyone else in the video is replaced by the picture's setting. Runs as one clip of up to ${CONTROL_MAX_SECONDS} s.`}
</p>
+ {editMode === "change" && video && canvas && <details>
+ <summary>Paint edit area (optional)</summary>
+ <ObjectPlacement key={`${video.url}:${resolutionField}:paint`} src={video.url}
+ start={whole ? 0 : part.start} end={whole ? video.duration : part.start + part.length}
+ width={canvas[0]} height={canvas[1]} mode="paint" points={paint} onChange={setPaint} />
+ </details>}
{editMode === "add" && video && canvas && <ObjectPlacement key={`${video.url}:${resolutionField}`} src={video.url}
start={whole ? 0 : part.start} end={whole ? video.duration : part.start + part.length} width={canvas[0]} height={canvas[1]} points={placement} onChange={setPlacement} />}
</div>
diff --git a/lib/object.ts b/lib/object.ts
index 3638c6c..a3b8cf1 100644
--- a/lib/object.ts
+++ b/lib/object.ts
@@ -22,6 +22,31 @@ export function parsePlacement(value: unknown): PlacementKeyframe[] {
return points.map(({ frame, x, y, width, height }) => ({ frame, x, y, width, height })).sort((a, b) => a.frame - b.frame);
}
+export type PaintKeyframe = { frame: number; width: number; height: number; runs: number[] };
+
+export function parsePaint(value: unknown): PaintKeyframe[] {
+ if (value === null || value === undefined || value === "") return [];
+ if (typeof value === "string" && value.length > 512 * 1024) throw new Error("Paint keyframes must total no more than 512 KB.");
+ const points = typeof value === "string" ? JSON.parse(value) : value;
+ if (!Array.isArray(points) || points.length > 64) throw new Error("Use at most 64 painted keyframes.");
+ const frames = new Set<number>();
+ const result = points.map((p): PaintKeyframe => {
+ if (!p || !Number.isInteger(p.frame) || p.frame < 0 || frames.has(p.frame)
+ || ![p.width, p.height].every((n) => Number.isInteger(n) && n >= 1 && n <= 256)
+ || !Array.isArray(p.runs) || p.runs.length % 2 || p.runs.length > p.width * p.height * 2) throw new Error("Invalid painted keyframe.");
+ let end = 0;
+ for (let i = 0; i < p.runs.length; i += 2) {
+ const [start, length] = p.runs.slice(i, i + 2);
+ if (!Number.isInteger(start) || !Number.isInteger(length) || start < end || length <= 0 || start + length > p.width * p.height) throw new Error("Paint runs must be ordered and inside the mask.");
+ end = start + length;
+ }
+ frames.add(p.frame);
+ return { frame: p.frame, width: p.width, height: p.height, runs: [...p.runs] };
+ });
+ if (JSON.stringify(result).length > 512 * 1024) throw new Error("Paint keyframes must total no more than 512 KB.");
+ return result.sort((a, b) => a.frame - b.frame);
+}
+
export function placementAt(points: PlacementKeyframe[], frame: number) {
if (!points.length) return null;
const next = points.findIndex((p) => p.frame > frame);
@@ -44,6 +69,7 @@ export type ObjectSettings = {
seed: number;
clipSeconds: number;
placement?: PlacementKeyframe[];
+ paint?: PaintKeyframe[];
action?: string; // add: what the new thing does over the clip; empty for a still object
};
@@ -111,6 +137,28 @@ export function pruneObject(source: ApiGraph, picture: boolean, settings: Object
seed: settings.seed,
clip_seconds: settings.clipSeconds,
});
+ if (settings.mode === "change" && settings.paint?.length) {
+ const paint = JSON.stringify(parsePaint(settings.paint));
+ plan.paint = paint;
+ // Track the full section once: later clips still need the bbox at each painted frame.
+ graph[id("SAM 3.1 track it")].inputs.images = [id("SAM video (1008 px, SAM's own size)"), 0];
+ graph[id("Tracked area")].inputs.hold_frames = 0;
+ graph.object_paint = { class_type: "H3PaintedEditArea", inputs: {
+ tracked: [id("Tracked area"), 0], paint, start_frame: 0,
+ width: [id("Object Swap Plan (what to change)"), 1], height: [id("Object Swap Plan (what to change)"), 2],
+ }, _meta: { title: "Painted edit area (follows tracked mask)" } };
+ const slice = (mask: [string, number]) => ({ class_type: "MiniMaxH3ContexLoopMaskSlice", inputs: {
+ mask, state: [id("Current Clip"), 0], source_fps: 24,
+ } });
+ graph.object_paint_clip = slice(["object_paint", 0]);
+ grow.mask = ["object_paint_clip", 0];
+ // The grey reference also consumes this clip's interval, rather than the full SAM timeline.
+ for (const [input, output] of [["mask", 0], ["size", 1]] as const) {
+ const key = `object_tight_${input}`;
+ graph[key] = slice([id("Tracked area, tight (for the grey shape)"), output]);
+ grey[input] = [key, 0];
+ }
+ }
if (settings.mode === "add") {
const placement = JSON.stringify(parsePlacement(settings.placement));
plan.placement = placement;
diff --git a/lib/setup.ts b/lib/setup.ts
index 506caf5..9fb6c51 100644
--- a/lib/setup.ts
+++ b/lib/setup.ts
@@ -30,8 +30,8 @@ type NodeInfo = { input?: { required?: Record<string, unknown[]>; optional?: Rec
export type NodeRegistry = Record<string, NodeInfo>;
const PACKS = [
- { 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", "MiniMaxH3ContexMaskedTarget", "MiniMaxH3ContexMaskGridPreview", "MiniMaxH3LoopTrim"] },
- { name: "comfyui-h3-oneclick-swap", url: "https://github.com/D3voz/comfyui-h3-oneclick-swap", nodes: ["H3OneClickSwapPlan", "H3AdvancedSwapPlan", "H3PictureSwapPlan", "H3ObjectSwapPlan", "H3ObjectPlacementMask", "H3PeopleMask", "H3GreyMannequins", "H3ClipShots", "H3FillShots", "H3TrackCrops", "H3TrackRoles", "H3RoleMask", "H3SubjectPrompt", "H3MontagePeople", "H3MontageTracks", "H3MontagePicks", "H3MontagePlan", "H3MontagePass", "H3FaceChunks", "H3FaceJoin"] },
+ { 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", "H3PictureSwapPlan", "H3ObjectSwapPlan", "H3ObjectPlacementMask", "H3PaintedEditArea", "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"] },
{ name: "ComfyUI-KJNodes", url: "https://github.com/kijai/ComfyUI-KJNodes", nodes: ["GrowMaskWithBlur", "ImageAndMaskPreview"] },
{ name: "ComfyUI-VideoHelperSuite", url: "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite", nodes: ["VHS_LoadVideo", "VHS_SelectEveryNthImage", "VHS_VideoCombine"] },
diff --git a/test/object.test.ts b/test/object.test.ts
index e6d3551..9327c25 100644
--- a/test/object.test.ts
+++ b/test/object.test.ts
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
import test from "node:test";
import { nodeByTitle } from "../lib/advanced.ts";
import { applyModel, DEFAULT_MODEL } from "../lib/model.ts";
-import { OBJECT_PICTURE, OBJECT_VIDEO, parsePlacement, placementAt, pruneObject, type ObjectSettings } from "../lib/object.ts";
+import { OBJECT_PICTURE, OBJECT_VIDEO, parsePaint, parsePlacement, placementAt, pruneObject, type ObjectSettings } from "../lib/object.ts";
import { isLink, type ApiGraph } from "../lib/simple.ts";
const graph: ApiGraph = JSON.parse(readFileSync(new URL("../workflows/object.api.json", import.meta.url), "utf8"));
@@ -134,3 +134,37 @@ test("placement validation rejects missing or invalid geometry and sorts valid k
assert.ok(Math.abs(middle.x - 0.4) < 1e-6 && Math.abs(middle.y - 0.3) < 1e-6);
assert.deepEqual(placementAt(sorted, 96), { x: 0.6, y: 0.2, width: 0.2, height: 0.2 });
});
+
+
+test("paint follows the full SAM timeline and is sliced per clip before growing", () => {
+ const paint = [{ frame: 0, width: 8, height: 8, runs: [18, 4, 26, 4] }];
+ for (const keepOutline of [false, true]) {
+ const pruned = pruneObject(graph, false, { ...settings("change"), keepOutline, paint });
+ assert.deepEqual(dangling(pruned), []);
+ assert.equal(pruned.object_paint.class_type, "H3PaintedEditArea");
+ assert.equal(pruned.object_paint.inputs.paint, JSON.stringify(paint));
+ assert.equal(node(pruned, "Object Swap Plan (what to change)").inputs.paint, JSON.stringify(paint));
+ assert.deepEqual(node(pruned, "SAM 3.1 track it").inputs.images, [nodeByTitle(pruned, "SAM video (1008 px, SAM's own size)"), 0]);
+ assert.equal(node(pruned, "Tracked area").inputs.hold_frames, 0);
+ assert.deepEqual(node(pruned, "Grow mask").inputs.mask, ["object_paint_clip", 0]);
+ assert.equal(pruned.object_paint_clip.class_type, "MiniMaxH3ContexLoopMaskSlice");
+ assert.equal(node(pruned, "Grow mask").inputs.expand, 40);
+ assert.deepEqual(node(pruned, "Turn it grey (shape and movement only)").inputs.mask, ["object_tight_mask", 0]);
+ }
+});
+
+test("empty paint leaves Change identical, and other modes ignore paint", () => {
+ const paint = [{ frame: 0, width: 8, height: 8, runs: [18, 4] }];
+ assert.deepEqual(pruneObject(graph, false, { ...settings("change"), paint: [] }), pruneObject(graph, false, settings("change")));
+ for (const mode of ["remove", "background"] as const) assert.deepEqual(pruneObject(graph, false, { ...settings(mode), paint }), pruneObject(graph, false, settings(mode)));
+});
+
+test("paint rejects malformed and oversized runs at the boundary", () => {
+ assert.deepEqual(parsePaint(null), []);
+ assert.deepEqual(parsePaint("[]"), []);
+ const valid = { frame: 24, width: 8, height: 8, runs: [10, 4, 20, 4] };
+ assert.deepEqual(parsePaint(JSON.stringify([valid, { ...valid, frame: 0 }])).map((p) => p.frame), [0, 24]);
+ for (const value of ["{", {}, [{ ...valid, frame: -1 }], [valid, valid], [{ ...valid, width: 257 }],
+ [{ ...valid, runs: [63, 2] }], [{ ...valid, runs: [-1, 2] }], [{ ...valid, runs: [10, 5, 12, 2] }],
+ [{ ...valid, runs: [10, 1.5] }], [{ ...valid, runs: [10] }], Array(65).fill(valid), " ".repeat(512 * 1024 + 1)]) assert.throws(() => parsePaint(value));
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 89f7378..5a93aa8 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -172,3 +172,19 @@ test("setup route returns missing packs for the chosen workflow without submitti
assert.equal(result.ok, false);
assert.equal(result.packs[0].name, "comfyui-h3-oneclick-swap");
});
+
+
+test("painted Change checks the paint and loop-mask nodes only when needed", () => {
+ const selection: SetupRequest = { kind: "object", picture: false, model: DEFAULT_MODEL, settings: {
+ mode: "change", target: "eyes", changeTo: "black sunglasses", biggestOnly: false, keepOutline: false,
+ resolution: "576p", motion: 512, margin: "loose", seed: 0, clipSeconds: 6,
+ paint: [{ frame: 0, width: 8, height: 8, runs: [18, 4] }],
+ } };
+ const graph = setupGraph(load("object"), selection);
+ const registry = registryFor(graph);
+ delete registry.H3PaintedEditArea;
+ delete registry.MiniMaxH3ContexLoopMaskSlice;
+ const missing = inspectSetup(graph, registry);
+ 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")));
+});