The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Remove object: every object you name, VOID and LTX pieces on exact frames, the hand-off mask only where a window waits for it
Claude8a27fabca67c
diff --git a/scripts/comfy/library.spec.mjs b/scripts/comfy/library.spec.mjsindex 6098be33..fd04101b 100644--- a/scripts/comfy/library.spec.mjs+++ b/scripts/comfy/library.spec.mjs@@ -2567,6 +2567,7 @@ export const SPEC = ['paste-back into the original frames, the window\'s sound kept. ' +'For a window after the first, the mask must be painted on (or tracked to) that window\'s first frame: the second output (node 77, role "mask", added by the remove-object package) ' +'is the tracked mask of the window\'s LAST frame (SAM3_TrackToMask before GrowMask, at the work size, white = the object), which Fuobe feeds to the next window as its mask, so the object is followed across windows. ' ++ 'The provider keeps node 77 only when params.extra.handOffMask is true (a window another one waits on); otherwise it is dropped, so a single or last window saves just the video. ' +'Validated by /prompt only (no GPU here).',},{diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.tsindex a2185229..11568156 100644--- a/src/lib/catalog/models.ts+++ b/src/lib/catalog/models.ts@@ -538,15 +538,16 @@ const open: ModelDef[] = [options: { colormaps: ["grayscale", "inferno"], sideBySide: true },}),// Remove object (Video tools → Remove object; docs/research/comfyui-oss-4.md §b). The prompt names what to remove- // (the provider sends it to SAM 3.1 as maskPrompt; the scene the gap is filled with is params.extra.prompt or a- // neutral default). One window per job: src/lib/catalog/remove-object.ts tiles longer clips and joins them.+ // (the provider sends the objects in it to SAM 3.1 as maskPrompt; the scene the gap is filled with is+ // params.extra.prompt or a neutral default). One window per job: src/lib/catalog/remove-object.ts tiles longer clips+ // and joins them; run on its own (a Canvas node) a job does the first window only, which the taglines say.o({id: "oss-vace-remove",name: "Wan 2.1 VACE Remove",vendor: "Alibaba Wan",family: "wan",kind: "video",- tagline: "Name what to remove: SAM 3.1 follows it, VACE fills the gap, every other pixel stays the original · 24 GB GPU · Apache-2.0",+ tagline: "Name what to remove: SAM 3.1 follows it, VACE fills the gap, every other pixel stays the original · 81 frames a run (Video tools → Remove object does whole clips) · 24 GB GPU · Apache-2.0",badges: ["new"],routes: [comfy("remove-object", "video-inpaint-wan-vace", "SAM 3.1 text track + Wan 2.1 VACE 14B with the lightx2v 4-step LoRA; up to 81 frames per window")],options: { seed: true, negativePrompt: true },@@ -557,7 +558,7 @@ const open: ModelDef[] = [vendor: "Alibaba Wan",family: "wan",kind: "video",- tagline: "Paint what to remove on the first frame: SAM 3.1 follows it, VACE fills the gap · 24 GB GPU · Apache-2.0",+ tagline: "Paint what to remove on the first frame: SAM 3.1 follows it, VACE fills the gap · 81 frames a run (Video tools → Remove object does whole clips) · 24 GB GPU · Apache-2.0",badges: ["new"],routes: [comfy("remove-object", "video-inpaint-wan-vace-painted", "first-frame mask (white = remove) tracked by SAM 3.1; the last frame's mask starts the next window")],options: { seed: true, negativePrompt: true, requires: { mask: true, msg: "Paint what to remove on the first frame" } },@@ -568,7 +569,7 @@ const open: ModelDef[] = [vendor: "Netflix",family: "void",kind: "video",- tagline: "Removes the object and what it causes — shadows, reflections, things it moves · 24–40 GB GPU (unverified) · CogVideoX License: commercial use needs registration",+ tagline: "Removes the object and what it causes — shadows, reflections, things it moves · 197 frames a run (Video tools → Remove object does whole clips) · 24–40 GB GPU (unverified) · CogVideoX License: commercial use needs registration",badges: ["new"],routes: [comfy("remove-object", "video-erase-void", "SAM 3.1 text track + VOID (CogVideoX-5B fine-tune), two passes; up to 197 frames per window")],options: { seed: true, negativePrompt: true },diff --git a/src/lib/catalog/remove-object.ts b/src/lib/catalog/remove-object.tsindex ecfd433e..0e3ba7fb 100644--- a/src/lib/catalog/remove-object.ts+++ b/src/lib/catalog/remove-object.ts@@ -27,6 +27,8 @@ export const REMOVE = {/** Seconds the mask preview looks at. */previewSeconds: 2,maxPoints: 12,+ /** What you type: Kling O3 edit takes prompts of up to 2500 characters, and klingPrompt() adds up to 52. */+ maxPromptChars: 2400,accept: "video/mp4,video/quicktime,video/webm,.mp4,.mov,.m4v,.webm",} as const;@@ -62,12 +64,16 @@ export interface Eraser {note: string;/** Cloud: the longest piece one call takes, in seconds (longer clips are cut, erased and joined). */maxSeconds?: number;- /** Cloud: the longest piece in frames at the clip's own rate (VOID: 197). */- maxFrames?: number;/** The shortest clip it takes, in seconds. */minSeconds?: number;- /** Open: one job per window of frames: at most `cap`, `step`·n + `base` frames (VACE 4n+1 ≤ 81, VOID 8n+5 ≤ 197). */+ /**+ * Routes that count frames: one job per window of whole frames, at most `cap`, `step`·n + `base` frames. Open: the+ * graph reads its own window (VACE 4n+1 ≤ 81, VOID 8n+5 ≤ 197); cloud: the clip is cut on those frames and the route+ * is told exactly that many (fal's VOID snaps num_frames to 69, 77 … 197; LTX renders 8n+1).+ */window?: FrameWindow;+ /** The highest frame rate it renders at (LTX Clean Plate: 60). */+ maxFps?: number;/** The result carries the piece's own sound (otherwise the clip's sound is put back). */keepsSound: boolean;/** Also removes what the object causes: shadows, reflections, things it moves. */@@ -86,6 +92,8 @@ export interface FrameWindow {cap: number;step: number;base: number;+ /** The fewest frames a window may have (fal's VOID: 69); `base` when unset. */+ min?: number;overlap?: number;}@@ -96,6 +104,13 @@ const VACE_WINDOW: FrameWindow = { cap: 81, step: 4, base: 1 };*/const VACE_PAINTED_WINDOW: FrameWindow = { ...VACE_WINDOW, overlap: 1 };const VOID_WINDOW: FrameWindow = { cap: 197, step: 8, base: 5 };+/** fal's VOID snaps num_frames to the nearest of 69, 77 … 197 (paid-model-apis-4.json): pieces are exactly one of them. */+const VOID_CLOUD_WINDOW: FrameWindow = { cap: 197, step: 8, base: 5, min: 69 };+/**+ * LTX 2.3 renders 8n+1 frames (9–481), and at 720p its IC-LoRA budget ("w × h × frames") is "roughly 6 s" at the+ * route's 24 fps, about 144 frames, above which it answers 422: pieces of up to 137 frames stay under it at any rate.+ */+const LTX_WINDOW: FrameWindow = { cap: 137, step: 8, base: 1, min: 9 };/** Bria's erasers take clips "shorter than 5 s": pieces stay a little under. */const BRIA_PIECE = 4.8;@@ -129,8 +144,8 @@ export const ERASERS: Eraser[] = [engine: "cloud",modes: ["type"],label: "VOID",- note: "Also removes its shadows and reflections · up to 197 frames per piece",- maxFrames: 197,+ note: "Also removes its shadows and reflections · 69–197 frames per piece",+ window: VOID_CLOUD_WINDOW,keepsSound: false,effects: true,},@@ -139,9 +154,9 @@ export const ERASERS: Eraser[] = [engine: "cloud",modes: ["type"],label: "LTX 2.3 Clean Plate",- note: "Removes every person — no words needed · up to 6 s per piece",- maxSeconds: 6,- minSeconds: 0.5,+ note: "Removes every person — no words needed · up to 137 frames per piece at 720p",+ window: LTX_WINDOW,+ maxFps: 60,keepsSound: false,everyone: true,},@@ -200,6 +215,12 @@ export const REMOVE_SCENE = "The same shot with nothing there: the background coexport const CLICK_OPEN_PROBLEM = "Clicking works on the cloud engine. On your ComfyUI, type what to remove or paint over it";+/**+ * params.extra key: this painted window hands its last tracked mask on to the next one, so the comfyui provider keeps+ * the graph's mask output (role "mask"); without it that output isn't saved.+ */+export const HAND_OFF = "handOffMask";+/** The erasers you can pick for this engine and way of pointing (the effects one only when typing). */export function erasersFor(engine: Engine, mode: RemoveMode): Eraser[] {return ERASERS.filter((e) => e.engine === engine && e.modes.includes(mode));@@ -221,15 +242,50 @@ export function chooseEraser(o: { engine: Engine; mode: RemoveMode; effects?: boconst VERB = /^\s*(?:please\s+)?(?:remove|erase|delete|get rid of|take out|cut out|clean up|wipe out|wipe)\s+/i;+/** Where the objects end and the instructions start: a sentence break, a dash, or a clause such as "… so she…". */+const LIST_END = /[.;:!?—–(]|\s-\s|\s+(?:so|then|while|but|keep|keeping|leaving|to make|make)\s+/i;+/** Between two objects: commas, "and", "plus", "including"… */+const LIST_SPLIT = /\s*,\s*(?:and\s+|plus\s+|also\s+)?|\s+(?:and|plus|&|as well as|along with|together with|including)\s+/i;+/** A part that starts with one of these is an instruction ("…and fix her fingers"), not another object. */+const INSTRUCTION = /^(?:keep|make|fix|fill|leave|replace|put|add|let|change|turn|show|restore|blur|paint|extend|move|have|ensure|don't|do|use|give|repair|smooth|cover|continue|preserve|retain|maintain|adjust|clean|reconstruct|inpaint)\b/i;+/** A part that starts like this describes the object before it ("the man in red, on the left"). */+const CONTINUES = /^(?:on|at|in|near|behind|under|above|below|beside|next to|by|with|without|inside|outside|over|across|along|around|who|which|that|wearing|holding|carrying|sitting|standing|walking|running)\b/i;+/** Two colours joined by "and" are one object's look ("the black and white dog"), not two objects. */+const COLOUR = "black|white|red|green|blue|yellow|orange|purple|pink|brown|grey|gray|silver|gold|golden|beige|dark|light|navy|teal";+const COLOUR_PAIR = new RegExp(`\\b(${COLOUR})\\s+and\\s+(${COLOUR})\\b`, "gi");+const JOINED = "\u0001";+const TARGET_MAX = 160;+/**- * The object alone, for a segmenter or an eraser that finds things by name (SAM 3.1, Bria, VOID's mask- * prompt): "Remove the coffee cup from her hands and fix her fingers…" → "the coffee cup".+ * What to remove, for a segmenter or an eraser that finds things by name (SAM 3.1, Bria, VOID's mask prompt):+ * the objects alone, comma-separated, which SAM 3.1 (fal) and ComfyUI's SAM 3 text encoder each track as their own+ * prompt. "Remove the coffee cup from her hands and fix her fingers…" → "the coffee cup"; "the logo and the+ * watermark" → "the logo, the watermark". Applying it again changes nothing.*/export function targetPhrase(text: string): string {- const t = text.trim().replace(VERB, "");- const stop = t.search(/\s+(?:from|in)\s+@video\d*|\s+from\s+|[,.;:!?—–(]|\s-\s|\s+(?:and|so|then|while|but|keep|keeping|leaving|to make|make)\s+/i);- const out = (stop > 0 ? t.slice(0, stop) : t).replace(/\s+(?:from|in|out of)\s+(?:the\s+)?(?:video|clip|shot|footage|frame)$/i, "").trim();- return (out || text.trim()).slice(0, 160);+ const t = text.trim().replace(VERB, "").replace(COLOUR_PAIR, `$1${JOINED}$2`);+ const end = t.search(LIST_END);+ const phrases: string[] = [];+ const list = (end > 0 ? t.slice(0, end) : t).replace(/(?:\s*,|\s+(?:and|plus|also|&))+\s*$/i, "");+ for (const raw of list.split(LIST_SPLIT)) {+ let part = raw.replaceAll(JOINED, " and ").trim().replace(/^(?:and|plus|also|including)\s+/i, "").replace(VERB, "");+ if (!part) continue;+ if (INSTRUCTION.test(part)) break;+ // The object, not where it is in the clip ("the cup from her hands", "the logo from the video").+ const from = part.search(/(?:^|\s+)(?:from|out of)\s+|(?:^|\s+)in\s+@video\d*/i);+ if (from >= 0) part = part.slice(0, from);+ part = part.replace(/\s+(?:from|in|out of)\s+(?:the\s+)?(?:video|clip|shot|footage|frame)$/i, "").trim();+ if (!part) continue;+ if (CONTINUES.test(part) && phrases.length) phrases[phrases.length - 1] += ` ${part}`;+ else if (!phrases.some((p) => p.toLowerCase() === part.toLowerCase())) phrases.push(part);+ }+ let out = "";+ for (const p of phrases) {+ const next = out ? `${out}, ${p}` : p;+ if (next.length > TARGET_MAX) break;+ out = next;+ }+ return (out || phrases[0] || text.trim()).slice(0, TARGET_MAX);}/**@@ -284,7 +340,7 @@ const r6 = (n: number) => Math.round(n * 1e6) / 1e6;* overlap, each window after the first also reads the last `overlap` frames of the one before.*/export function frameWindows(total: number, w: FrameWindow): number[] {- if (total < w.base) return [];+ if (total < (w.min ?? w.base)) return [];const o = w.overlap ?? 0;const k = Math.max(1, Math.ceil((total - o) / (w.cap - o)));const units = Math.floor((total + (k - 1) * o - k * w.base) / w.step);@@ -316,6 +372,21 @@ export function planWindows(range: RemoveRange, fps: number, w: FrameWindow): Pi});}+/**+ * Cloud routes that count frames (VOID, LTX Clean Plate): cuts on whole frames, back to back, each exactly one+ * window long, so the route is told the piece's own frame count (nothing for it to snap, pad or drop) and the+ * joined clip has exactly the range's frames (less fewer than `step` at the end).+ */+export function planFrameCuts(range: RemoveRange, fps: number, w: FrameWindow): Piece[] {+ const total = Math.floor((range.end - range.start) * fps + 1e-6);+ let at = Math.round(range.start * fps);+ return frameWindows(total, w).map((frames, index) => {+ const piece: Piece = { index, start: r6(at / fps), end: r6((at + frames) / fps), frames };+ at += frames;+ return piece;+ });+}+/*** Cloud: equal pieces of at most `max` seconds (on whole frames when the rate is known), so no piece is* a sliver (14 s for Bria → three 4.67 s pieces, not two of 4.8 s and one of 4.4 s… or a 0.4 s one).@@ -333,7 +404,7 @@ export function planCloudPieces(range: RemoveRange, max: number, fps?: number):/** The longest piece a cloud eraser takes for this clip. */export function pieceSeconds(e: Eraser, fps?: number): number {- const byFrames = e.maxFrames ? e.maxFrames / (fps && fps > 0 ? fps : 24) : Infinity;+ const byFrames = e.window ? e.window.cap / (fps && fps > 0 ? fps : 24) : Infinity;return Math.min(e.maxSeconds ?? Infinity, byFrames);}@@ -371,14 +442,19 @@ export function removalProblem(e: Eraser, source: RemoveSource, range: RemoveRan}if (e.window) {if (!source.fps) return "Couldn't read this clip's frame rate — save it as an MP4 (H.264) and try again";- if (Math.floor(len * source.fps + 1e-6) < e.window.base) return "Select a little more of the clip";+ const min = e.window.min ?? e.window.base;+ if (Math.floor(len * source.fps + 1e-6) < min) {+ if (min === e.window.base) return "Select a little more of the clip";+ return `${name} needs at least ${min} frames (${(Math.ceil((min / source.fps) * 10) / 10).toFixed(1)} s of this clip) — select more${e.effects ? ", or turn off Shadows and reflections" : ""}`;+ }}+ if (e.maxFps && source.fps && source.fps > e.maxFps + 0.01) return `${name} renders up to ${e.maxFps} fps (this clip is ${Math.round(source.fps)} fps) — pick another eraser`;return null;}/** The pieces a clip is erased in: windows on the open engine, equal cuts on the cloud. */export function planPieces(e: Eraser, source: RemoveSource, range: RemoveRange): Piece[] {- if (e.window) return source.fps ? planWindows(range, source.fps, e.window) : [];+ if (e.window) return !source.fps ? [] : e.engine === "open" ? planWindows(range, source.fps, e.window) : planFrameCuts(range, source.fps, e.window);return planCloudPieces(range, pieceSeconds(e, source.fps), source.fps);}@@ -498,10 +574,13 @@ function eraseRequest(input: RemovalPlanInput, p: Piece): Partial<GenerationRequparams: { startTime: p.startTime, endTime: p.endTime, ...seed },};}- // Seconds price per-second models; frame-count routes (VOID, LTX) read the piece's length and the clip's rate.- const len = { duration: seconds(p), sourceDuration: seconds(p), ...fps };+ // Seconds price per-second models; frame-count routes (VOID, LTX) read the piece's length and the clip's rate,+ // which give exactly its own frame count.+ const secs = p.frames && input.source.fps ? r6(p.frames / input.source.fps) : seconds(p);+ const len = { duration: secs, sourceDuration: secs, ...fps };if (e.id === "kling-o3" || e.id === "kling-o3-4k-edit") return { prompt: klingPrompt(input.prompt ?? ""), params: { ...len, ...seed } };- if (e.everyone) return { params: { ...len, generateAudio: false, ...seed } };+ // LTX's frame budget (LTX_WINDOW) is the 720p one.+ if (e.everyone) return { params: { ...len, resolution: "720p", generateAudio: false, ...seed } };if (e.modes.includes("type")) return { prompt: targetPhrase(input.prompt ?? ""), params: { ...len, ...seed } };// Bria's clicked eraser reads the points itself; the masked one gets SAM 3.1's track.return { params: { ...len, ...(e.id === "bria-video-erase-points" ? { points: input.points } : {}), ...seed } };@@ -536,6 +615,8 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {pieces.forEach((p, i) => {const own = eraseRequest(input, p);const painted = e.modes.includes("paint");+ // Only a window another one waits on saves its last tracked mask (else it would show up as a second result).+ const handOff = painted && i < n - 1;steps.push({key: `erase${i}`,request: {@@ -543,6 +624,7 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {modelId: e.id,op,...own,+ ...(handOff ? { params: { ...own.params, extra: { [HAND_OFF]: true } } } : {}),inputs: { video: input.source.url, ...(painted && i === 0 && input.mask ? { mask: input.mask } : {}) },step: pieceLabel(p, n, "erase"),},@@ -582,7 +664,10 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {});}pieces.forEach((p, i) => {- const one = n === 1 && whole;+ // One piece that is the whole upload: read as it is (a frame-count route's piece only when it is every frame,+ // else it is cut to its frames, so the route gets exactly what it is told whether it reads num_frames as the+ // length or as its window).+ const one = n === 1 && whole && (!p.frames || p.end >= (input.source.duration ?? 0) - 0.05);const own = eraseRequest(input, p);const after: string[] = [];const chain: ChainSlot[] = [];@@ -646,13 +731,16 @@ export function planRemoval(input: RemovalPlanInput): RemovalPlan {const picture = level[0];if (!sound) return { steps, final: picture, pieces, sound, tracked };- // The clip's own sound under the erased picture: the upload (whole clip), or the range cut out of it.+ // The clip's own sound under the erased picture: the upload (whole clip), or the range cut out of it. Erasers that+ // work in whole frames leave out the last few (fewer than a step): the sound is cut to the picture's end, except on+ // the open engine, whose mux trims the sound to the picture itself.const after = [picture];const chain: ChainSlot[] = [{ slot: "video" }];const inputs: GenerationRequest["inputs"] = {};- if (whole) inputs.audio = input.source.url;+ const end = e.window && e.engine === "cloud" ? pieces[n - 1].end : input.range.end;+ if (whole && end >= (input.source.duration ?? 0) - 0.05) inputs.audio = input.source.url;else {- steps.push({ key: "sound", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: input.range.end }, step: { label: "Original sound", index: 1100, of: 1000 } } });+ steps.push({ key: "sound", request: { ...helper, modelId: t.cut, op: "trim", inputs: { video: input.source.url }, params: { startTime: input.range.start, endTime: end }, step: { label: "Original sound", index: 1100, of: 1000 } } });after.push("sound");chain.push({ slot: "audio" });}@@ -684,6 +772,15 @@ export interface PreviewPlanInput {points?: PixelPoint[];}+/**+ * Whether the mask preview shows the mask the eraser itself works from (SAM tracks the object for it: the open+ * graphs, fal's VOID from its mask prompt, a SAM 3.1 track of clicks or paint), or only how SAM 3.1 reads the words+ * or clicks (Kling O3 edit and Bria find the object themselves, so their result can differ).+ */+export function previewIsEraserMask(e: Eraser, tracked: boolean): boolean {+ return e.engine === "open" || !!e.effects || tracked;+}+/*** A cheap look at the mask before paying for the removal: the first seconds of the range, segmented by* SAM 3.1 (cloud: a mask video of what you named, clicked or painted, about $0.02; open: the SAM 3 mattediff --git a/src/server/providers/comfyui.ts b/src/server/providers/comfyui.tsindex b07a1a09..01e69e43 100644--- a/src/server/providers/comfyui.ts+++ b/src/server/providers/comfyui.ts@@ -30,7 +30,7 @@ import {} from "@/lib/comfy";import { expandTimelineWorkflow, readTimeline } from "@/lib/av/timeline";import { guessKind } from "@/lib/catalog/payload";-import { CLICK_OPEN_PROBLEM, REMOVE_SCENE } from "@/lib/catalog/remove-object";+import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE, targetPhrase } from "@/lib/catalog/remove-object";import type { GenInput, MediaKind, Operation } from "@/lib/catalog/types";import { probeMedia, type MediaInfo } from "@/lib/media-probe";import { getSetting } from "../settings";@@ -572,13 +572,17 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,values[key] = def.replaceAll("{columns}", String(columns)).replaceAll("{rows}", String(rows)).replaceAll("{count}", String(columns * rows)).replaceAll("{language}", languageName(input.targetLanguage));}- // Remove object: the words name what SAM 3.1 follows (maskPrompt) and the gap is filled with the scene without it- // (params.extra.prompt, else a neutral default). No graph takes clicked points.+ // Remove object: the words name what SAM 3.1 follows (maskPrompt: the objects alone, comma-separated, each its own+ // SAM 3 prompt, so "Remove the red car from the shot" run straight from a Canvas works too) and the gap is filled+ // with the scene without it (params.extra.prompt, else a neutral default). No graph takes clicked points.+ // The painted eraser's last tracked mask (role "mask") is saved only for a window another one waits on.+ const handOff = ctx.op === "remove-object" && extra[HAND_OFF] === true;+ delete extra[HAND_OFF];if (ctx.op === "remove-object") {const words = input.prompt?.trim();if (b.maskPrompt) {if (!words && typeof extra.maskPrompt !== "string") throw new ProviderError(input.points?.length ? CLICK_OPEN_PROBLEM : "Say what to remove, e.g. “the coffee cup in her hand”");- values.maskPrompt = words;+ if (words) values.maskPrompt = targetPhrase(words);}if (b.prompt) values.prompt = REMOVE_SCENE;}@@ -659,6 +663,7 @@ export async function prepareWorkflow(endpointTemplate: string, input: GenInput,if (input.loras?.length) wf = injectLoras(wf, input.loras);// The output not asked for isn't saved (nor encoded: ComfyUI runs only what an output node needs).if (keepRole && manifest.outputs.some((o) => o.role === keepRole)) for (const o of manifest.outputs) if (o.role && o.role !== keepRole) delete wf[o.node];+ if (ctx.op === "remove-object" && !handOff) for (const o of manifest.outputs) if (o.role === "mask") delete wf[o.node];const metaBatch = Object.values(wf).some((n) => n.class_type === "VHS_BatchManager");return {manifest,diff --git a/src/server/providers/mock.ts b/src/server/providers/mock.tsindex 2b096c98..81ad2145 100644--- a/src/server/providers/mock.ts+++ b/src/server/providers/mock.ts@@ -1,6 +1,7 @@import "server-only";import { nanoid } from "nanoid";import { cueText, parseCues, type Cue } from "@/lib/cues";+import { HAND_OFF } from "@/lib/catalog/remove-object";import { OPERATION_OUTPUT, type MediaKind, type Operation } from "@/lib/catalog/types";import type { ProviderAdapter, RemoteOutput } from "./types";import { textOutput } from "./llm";@@ -353,8 +354,9 @@ export const mockProvider: ProviderAdapter = {clips: input.audios?.length,// Remove background: which file the demo stands for (the cut-out or its alpha mask).matteOutput: route.op === "bg-remove-video" ? (input.matteOutput ?? model.options.matteOutputs?.[0] ?? "cutout") : undefined,- // The painted eraser's second output: the window's last tracked mask (video-inpaint-wan-vace-painted).- lastMask: route.provider === "comfyui" && route.endpoint === "video-inpaint-wan-vace-painted",+ // The painted eraser's second output: the window's last tracked mask (video-inpaint-wan-vace-painted), saved+ // only for a window the next one waits on (as the comfyui provider does).+ lastMask: route.provider === "comfyui" && route.endpoint === "video-inpaint-wan-vace-painted" && input.extra?.[HAND_OFF] === true,// Workflows whose second output is the cut's first frame (video-segment-resample).firstFrame: route.provider === "comfyui" && route.endpoint === "video-segment-resample",// A stem split that also transcribes (ComfyUI's dub-prepare-separate-transcribe).diff --git a/src/server/remove-object.ts b/src/server/remove-object.tsindex de664108..60ccdcd5 100644--- a/src/server/remove-object.ts+++ b/src/server/remove-object.ts@@ -8,6 +8,7 @@ import {planPieces,planMaskPreview,planRemoval,+ previewIsEraserMask,rangeProblem,REMOVE,removalProblem,@@ -21,7 +22,7 @@ import {type RemoveSource,} from "@/lib/catalog/remove-object";import type { PlanStep } from "@/lib/catalog/shorts";-import type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";+import type { Engine, GenParams, Generation, PixelPoint } from "@/lib/catalog/types";import { createPipeline } from "./chains";import { previewChained } from "./generations";import { decodePng } from "./png";@@ -68,6 +69,7 @@ export const RemovalBodySchema = z.object({mode: z.enum(["type", "click", "paint"]),modelId: z.string().max(80).optional(),effects: z.boolean().optional(),+ // The page stops at REMOVE.maxPromptChars; longer is refused in words by planInput.prompt: z.string().max(2500).optional(),points: z.array(point).max(REMOVE.maxPoints).optional(),frame: z.object({ width: z.number().int().positive().max(20000), height: z.number().int().positive().max(20000) }).optional(),@@ -99,6 +101,20 @@ export const RemovalEstimateSchema = RemovalBodySchema.extend({*/const EDIT_USD_PER_SECOND: Record<string, number> = { "kling-o3": 0.168 };+/**+ * LTX 2.3 Clean Plate is billed per megapixel of the video it makes ($0.0024075 × width × height × frames, rounded up;+ * paid-model-apis-4.md §3), not the catalog's flat $0.27 (121 frames at 1280×720): at 720p the source's shape with a+ * 720 px short side, for the piece's own frames.+ */+const MEGAPIXEL_USD: Record<string, number> = { "ltx-2-3-clean-plate": 0.0024075 };++function megapixels(params: GenParams | undefined, source: Pick<RemoveSource, "width" | "height">): number {+ const frames = Math.round((params?.sourceDuration ?? params?.duration ?? 0) * (params?.fps ?? 24));+ const { width: w, height: h } = source;+ const [ow, oh] = w && h ? (w >= h ? [Math.round((720 * w) / h), 720] : [720, Math.round((720 * h) / w)]) : [1280, 720];+ return Math.ceil((ow * oh * frames) / 1e6);+}+const mustMatchMode = (engine: Engine) => {const mode = engineMode();if (mode !== "both" && mode !== engine) {@@ -151,6 +167,8 @@ async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: bolet points: PixelPoint[] | undefined;if (body.mode === "type" && !eraser.everyone && !body.prompt?.trim()) throw new ShortsError("Say what to remove, e.g. “the coffee cup in her hand”");+ // Kling O3 edit takes 2500 characters, its template included: refused here, not after the cuts have run.+ if ((body.prompt?.trim().length ?? 0) > REMOVE.maxPromptChars) throw new ShortsError(`Say what to remove in up to ${REMOVE.maxPromptChars} characters`, 422);if (body.mode === "click") {const given = (body.points ?? []).slice(0, REMOVE.maxPoints);if (!given.some((p) => p.label !== "negative")) throw new ShortsError("Click what to remove on the first frame");@@ -165,19 +183,28 @@ async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: boconst notes: string[] = [];const len = range.end - range.start;const model = getModel(eraser.id);- if (eraser.window) {- const fps = source.fps ?? 30;- const per = eraser.window.cap / fps;- const windows = source.fps ? planPieces(eraser, source, range).length : Math.ceil((len * fps) / eraser.window.cap);- if (windows > 1) {- notes.push(`${model?.name ?? eraser.label} works on ${eraser.window.cap} frames at a time (${per.toFixed(1)} s of this clip): the clip runs as ${windows} windows, joined with its own sound. Seams between windows aren't tested on a GPU yet`);+ const eraserName = model?.name ?? eraser.label;+ const fps = source.fps ?? 30;+ // The pieces (cloud) or windows (open) the selection is erased in.+ const pieces = eraser.window && !source.fps ? [] : planPieces(eraser, source, range);+ const count = eraser.window && !source.fps ? Math.ceil((len * fps) / eraser.window.cap) : pieces.length;+ // Frame-count erasers work in steps of frames: what's left at the end of the selection isn't erased (or kept).+ const dropped = eraser.window && pieces.length ? Math.round((len - (pieces[pieces.length - 1].end - range.start)) * fps) : 0;+ if (dropped > 0) {+ notes.push(`${eraserName} works in steps of ${eraser.window!.step} frames: the selection's last ${dropped === 1 ? "frame" : `${dropped} frames`} (${(dropped / fps).toFixed(2)} s) ${dropped === 1 ? "is" : "are"} left out`);+ }+ if (eraser.engine === "open") {+ const per = (eraser.window?.cap ?? 81) / fps;+ if (count > 1) {+ notes.push(`${eraserName} works on ${eraser.window?.cap} frames at a time (${per.toFixed(1)} s of this clip): the clip runs as ${count} windows, joined with its own sound. Seams between windows aren't tested on a GPU yet`);if (eraser.modes.includes("paint")) notes.push("SAM 3.1 hands what you painted on from window to window (each starts on the last frame of the one before), so the windows run one after another");}notes.push(eraser.effects ? "VOID needs a 24–40 GB GPU (unverified). Its CogVideoX base is licensed for commercial use only after registering, up to 1 million visits a month" : "Wan 2.1 VACE 14B needs a 24 GB GPU · Apache-2.0 (SAM 3.1: Meta's SAM License)");} else {const max = pieceSeconds(eraser, source.fps);- if (len > max + 0.01) notes.push(`${model?.name ?? eraser.label} takes ${max < 5 ? "clips under 5 s" : `up to ${Math.floor(max)} s`}: the clip is cut into ${Math.ceil(len / max - 1e-9)} pieces, erased one by one and joined, with its own sound put back. Seams between pieces aren't tested yet`);- if (body.mode !== "type" && (body.mode === "paint" || len > max + 0.01)) notes.push("SAM 3.1 first follows what you " + (body.mode === "paint" ? "painted" : "clicked") + " through the whole selection; Bria then erases that mask");+ const limit = eraser.window ? `up to ${eraser.window.cap} frames (${max.toFixed(1)} s of this clip)` : max < 5 ? "clips under 5 s" : `up to ${Math.floor(max)} s`;+ if (count > 1) notes.push(`${eraserName} takes ${limit}: the clip is cut into ${count} pieces, erased one by one and joined, with its own sound put back. Seams between pieces aren't tested yet`);+ if (body.mode !== "type" && (body.mode === "paint" || count > 1)) notes.push("SAM 3.1 first follows what you " + (body.mode === "paint" ? "painted" : "clicked") + " through the whole selection; Bria then erases that mask");if (eraser.everyone) notes.push("LTX Clean Plate removes every person in the shot — it doesn't take a target");}if (!wholeClip(range, source.duration)) notes.push("Only the selected part comes out (the rest of the clip isn't kept)");@@ -205,7 +232,7 @@ async function planInput(body: RemovalBody, opts: { probe: boolean; preview?: boconst withChain = (s: PlanStep) => ({ ...s.request, ...(s.chain ? { chain: s.chain } : {}) });/** What the steps cost together (null when a price is unknown) and whether they would run as a demo. */-function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {+function price(steps: PlanStep[], source: RemoveSource): { costUsd: number | null; demo: boolean } {let cost: number | null = 0;let demo = false;for (const s of steps) {@@ -217,7 +244,9 @@ function price(steps: PlanStep[]): { costUsd: number | null; demo: boolean } {}demo ||= p.demo;const edit = EDIT_USD_PER_SECOND[s.request.modelId];- const usd = p.costUsd ?? (edit !== undefined ? edit * (s.request.params?.duration ?? 0) : null);+ const perMp = MEGAPIXEL_USD[s.request.modelId];+ const usd =+ !p.demo && perMp !== undefined ? perMp * megapixels(s.request.params, source) : (p.costUsd ?? (edit !== undefined ? edit * (s.request.params?.duration ?? 0) : null));cost = cost === null || usd === null ? null : cost + usd;}return { costUsd: cost === null ? null : Math.round(cost * 10000) / 10000, demo };@@ -236,6 +265,11 @@ export interface RemovalEstimate {notes: string[];/** The mask preview's price, or null when this engine and mode have none. */previewUsd: number | null;+ /**+ * Whether the preview is the mask the eraser works from; false: only how SAM 3.1 reads the words or clicks+ * (Kling O3 edit and Bria find the object themselves).+ */+ previewExact: boolean;}export async function estimateRemoval(body: RemovalBody): Promise<RemovalEstimate> {@@ -243,14 +277,15 @@ export async function estimateRemoval(body: RemovalBody): Promise<RemovalEstimatconst plan = planRemoval(input);const preview = planMaskPreview({ ...input, prompt: input.prompt, points: input.points });return {- ...price(plan.steps),+ ...price(plan.steps, input.source),modelId: eraser.id,modelName: getModel(eraser.id)?.name ?? eraser.label,pieces: plan.pieces.length,seconds: Math.round((input.range.end - input.range.start) * 100) / 100,steps: plan.steps.length,notes,- previewUsd: preview ? price(preview).costUsd : null,+ previewUsd: preview ? price(preview, input.source).costUsd : null,+ previewExact: !!preview && previewIsEraserMask(eraser, plan.tracked),};}diff --git a/tests/remove-object-api.test.ts b/tests/remove-object-api.test.tsindex 624c7f22..bcabe386 100644--- a/tests/remove-object-api.test.ts+++ b/tests/remove-object-api.test.ts@@ -96,6 +96,38 @@ describe("Remove object: estimates", () => {expect(e.costUsd).toBeLessThan(1.7);expect(e.notes.join(" ")).toMatch(/cut into 3 pieces/);expect(e.previewUsd).toBeGreaterThan(0);+ // Bria finds the object by name itself: the preview is only SAM 3.1's reading of the words.+ expect(e.previewExact).toBe(false);+ });++ it("says whether the mask preview is what the eraser works from", async () => {+ const src = { url: clip, duration: 12, fps: 16, width: 1280, height: 720, hasAudio: true };+ const kling = await (await estimateRoute.POST(json(body({ source: { ...src, duration: 10 } })))).json();+ expect(kling).toMatchObject({ modelId: "kling-o3", previewExact: false });+ const voidE = await (await estimateRoute.POST(json(body({ effects: true, source: src, range: { start: 0, end: 8 } })))).json();+ expect(voidE).toMatchObject({ modelId: "void-video-inpainting", previewExact: true });+ const paint = await (await estimateRoute.POST(json(body({ mode: "paint", mask: "/api/files/m.png", source: src })))).json();+ expect(paint).toMatchObject({ modelId: "bria-video-erase-mask", previewExact: true });+ const open = await (await estimateRoute.POST(json(body({ engine: "open", source: src })))).json();+ expect(open).toMatchObject({ modelId: "oss-vace-remove", previewExact: true });+ });++ it("prices LTX Clean Plate per megapixel of each 720p piece, and VOID per piece of exact frames", async () => {+ const src = { url: clip, duration: 12, fps: 30, width: 1920, height: 1080, hasAudio: true };+ const ltx = await (await estimateRoute.POST(json(body({ modelId: "ltx-2-3-clean-plate", prompt: undefined, source: src })))).json();+ // 360 frames → pieces of 121, 121 and 113 frames at 1280×720: 112 + 112 + 105 MP at $0.0024075 (rounded up per piece).+ expect(ltx).toMatchObject({ modelId: "ltx-2-3-clean-plate", pieces: 3 });+ const erase = (112 + 112 + 105) * 0.0024075;+ expect(ltx.costUsd).toBeGreaterThanOrEqual(erase);+ expect(ltx.costUsd).toBeLessThan(erase + 0.05);+ expect(ltx.notes.join(" ")).toMatch(/up to 137 frames/);+ const voidE = await (await estimateRoute.POST(json(body({ effects: true, source: { ...src, duration: 10 } })))).json();+ expect(voidE).toMatchObject({ modelId: "void-video-inpainting", pieces: 2 });+ // The last 2 frames of 300 don't fit VOID's 8-frame steps: said, not hidden.+ expect(voidE.notes.join(" ")).toMatch(/last 2 frames \(0\.07 s\) are left out/);+ const short = await estimateRoute.POST(json(body({ effects: true, source: { ...src, duration: 2 } })));+ expect(short.status).toBe(422);+ expect((await short.json()).error).toMatch(/at least 69 frames/);});it("prices Kling O3 edit at its edit price, and refuses clips it can't take", async () => {@@ -131,6 +163,10 @@ describe("Remove object: estimates", () => {expect((await words.json()).error).toMatch(/Say what to remove/);const points = await estimateRoute.POST(json(body({ mode: "click", points: [{ x: 3, y: 3, label: "negative" }], source: { url: clip, duration: 12, fps: 16 } })));expect((await points.json()).error).toMatch(/Click what to remove/);+ // Kling O3 edit's 2500 characters include its template: longer words are refused before anything runs.+ const long = await estimateRoute.POST(json(body({ prompt: "the cup ".repeat(301), source: { url: clip, duration: 10, fps: 24, width: 1280, height: 720 } })));+ expect(long.status).toBe(422);+ expect((await long.json()).error).toMatch(new RegExp(`up to ${REMOVE.maxPromptChars} characters`));setSetting("engineMode", "open");const cloud = await estimateRoute.POST(json(body({ source: { url: clip, duration: 12, fps: 16 } })));expect((await cloud.json()).error).toMatch(/open-source models only/);@@ -207,6 +243,16 @@ describe("Remove object: runs", () => {expect(second.request.inputs?.mask).toMatch(/\.svg$/);});+ it("open engine, Paint it, one window: the result is the video alone (no hand-off mask)", async () => {+ const res = await createRoute.POST(json(body({ engine: "open", mode: "paint", prompt: undefined, mask, range: { start: 0, end: 3 } })));+ const { final, items } = (await res.json()) as { final: Generation; items: Generation[] };+ expect(items).toHaveLength(1);+ expect(final).toMatchObject({ modelId: "oss-vace-remove-painted", feature: REMOVE.feature });+ const done = await settle(final.id);+ expect(done.status).toBe("succeeded");+ expect(done.outputs.map((o) => o.kind)).toEqual(["video"]);+ });+it("open engine, Type it, one window: the eraser's own result is the video", async () => {const res = await createRoute.POST(json(body({ engine: "open", range: { start: 0, end: 3 } })));const { final, items } = (await res.json()) as { final: Generation; items: Generation[] };diff --git a/tests/remove-object-comfy.test.ts b/tests/remove-object-comfy.test.tsindex 1d1252b3..e8c4a4b8 100644--- a/tests/remove-object-comfy.test.ts+++ b/tests/remove-object-comfy.test.ts@@ -4,7 +4,7 @@ import path from "node:path";import { afterAll, describe, expect, it } from "vitest";import type { GenInput, Operation, OutputFile } from "@/lib/catalog/types";import type { MediaInfo } from "@/lib/media-probe";-import { CLICK_OPEN_PROBLEM, REMOVE_SCENE } from "@/lib/catalog/remove-object";+import { CLICK_OPEN_PROBLEM, HAND_OFF, REMOVE_SCENE } from "@/lib/catalog/remove-object";// The comfyui provider driving the remove-object graphs (SAM 3.1 + VACE / VOID), the matte graphs' two outputs and// the depth graphs' colour map and side-by-side switch, bound for real on the library graphs.@@ -32,6 +32,13 @@ describe("remove-object graphs through the provider", () => {expect([at(wf, "87", "value"), at(wf, "88", "value")]).toEqual([832, 480]);});+ it("a whole sentence (a Canvas node runs the model directly) becomes the objects alone, each its own SAM prompt", async () => {+ const { workflow: wf } = await prepare("video-inpaint-wan-vace", { prompt: "Remove the logo and the watermark from the video, keep everything else the same" });+ expect(at(wf, "8", "text")).toBe("the logo, the watermark");+ const v = await prepare("video-erase-void", { prompt: "the red car and its shadow" });+ expect(at(v.workflow, "8", "text")).toBe("the red car, its shadow");+ });+it("a described scene (params.extra.prompt) fills the gap instead", async () => {const { workflow: wf } = await prepare("video-inpaint-wan-vace", { prompt: "the man", extra: { prompt: "An empty beach at sunset" } });expect(at(wf, "8", "text")).toBe("the man");@@ -44,7 +51,7 @@ describe("remove-object graphs through the provider", () => {});it("painted VACE: the first-frame mask is uploaded into its loader, the scene prompt is the default", async () => {- const { workflow: wf, manifest } = await prepare("video-inpaint-wan-vace-painted", { mask: "mask.png", startTime: 0, endTime: 2.7 });+ const { workflow: wf, manifest } = await prepare("video-inpaint-wan-vace-painted", { mask: "mask.png", startTime: 0, endTime: 2.7, extra: { [HAND_OFF]: true } });expect(at(wf, "70", "image")).toBe("mask.png");expect(at(wf, "16", "text")).toBe(REMOVE_SCENE);// Its second output is the last frame's tracked mask, which starts the next window.@@ -55,6 +62,14 @@ describe("remove-object graphs through the provider", () => {expect(at(wf, "77", "filename_prefix")).toBe("fuobe/g1");expect(wf["76"].inputs).toMatchObject({ image: ["74", 0], batch_index: ["75", 1], length: 1 });expect(wf["74"].inputs).toEqual({ mask: ["10", 0] });+ // The flag isn't bound to anything.+ expect(JSON.stringify(wf)).not.toContain(HAND_OFF);+ });++ it("painted VACE: a window nothing waits on (one window, or the last) saves only the video", async () => {+ const { workflow: wf } = await prepare("video-inpaint-wan-vace-painted", { mask: "mask.png", startTime: 0, endTime: 2.7 });+ expect(wf["77"]).toBeUndefined();+ expect(wf["38"].class_type).toBe("SaveVideo");});it("VOID: maskPrompt, the scene, and pass 2 can be skipped", async () => {diff --git a/tests/remove-object.test.ts b/tests/remove-object.test.tsindex 2f58d29d..40e3249d 100644--- a/tests/remove-object.test.ts+++ b/tests/remove-object.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";-import { getModel } from "@/lib/catalog";-import { promptOptional, routesFor } from "@/lib/catalog/plan";+import { getModel, getPreset } from "@/lib/catalog";+import { buildPayload } from "@/lib/catalog/payload";+import { planGeneration, promptOptional, routesFor } from "@/lib/catalog/plan";import {chooseEraser,CLICK_OPEN_PROBLEM,@@ -8,16 +9,20 @@ import {erasersFor,frameWindows,getEraser,+ HAND_OFF,klingPrompt,MASK_TRACKER,paintedPoints,pieceSeconds,planCloudPieces,+ planFrameCuts,planMaskPreview,planRemoval,planWindows,+ previewIsEraserMask,REMOVE,REMOVE_EXAMPLES,+ REMOVE_SCENE,REMOVE_TOOLS,removalProblem,removalTitle,@@ -27,6 +32,7 @@ import {type RemovalPlanInput,} from "@/lib/catalog/remove-object";import type { PlanStep } from "@/lib/catalog/shorts";+import type { GenerationRequest, GenInput } from "@/lib/catalog/types";const src = { url: "/api/files/uploads/clip.mp4", duration: 12, fps: 30, width: 1280, height: 720, hasAudio: true };const input = (over: Partial<RemovalPlanInput> & { eraserId?: string } = {}): RemovalPlanInput => {@@ -44,6 +50,17 @@ const input = (over: Partial<RemovalPlanInput> & { eraserId?: string } = {}): Re};const keys = (steps: PlanStep[]) => steps.map((s) => s.key);const step = (steps: PlanStep[], key: string) => steps.find((s) => s.key === key)!;+/**+ * What a step sends to its API, as the server does: planned (model defaults, checks), then mapped by the route's+ * FieldMap. Chained inputs (a cut piece, a tracked mask) get stand-ins.+ */+const payloadOf = (s: PlanStep) => {+ const chained = Object.fromEntries((s.chain ?? []).map((c) => [c.slot, `/api/files/${c.slot}-from-before.mp4`]));+ const req = { ...s.request, inputs: { ...chained, ...s.request.inputs } } as GenerationRequest;+ const p = planGeneration(req, getModel, getPreset);+ const input = { ...p.params, prompt: p.prompt, video: req.inputs?.video, mask: req.inputs?.mask } as GenInput;+ return buildPayload(routesFor(p.model, p.op)[0].map!, input);+};describe("Remove object: erasers", () => {it("points at real catalog models, with the routes and inputs each way of pointing needs", () => {@@ -92,12 +109,37 @@ describe("Remove object: erasers", () => {describe("Remove object: words", () => {it("cuts the object out of an instruction for SAM 3.1, Bria and VOID", () => {expect(targetPhrase(REMOVE_EXAMPLES[0].prompt)).toBe("the coffee cup");- expect(targetPhrase(REMOVE_EXAMPLES[1].prompt)).toBe("the pogo stick the guy is bouncing on");+ // Higgsfield's pogo example names four things to remove; the instruction after the dash isn't one.+ expect(targetPhrase(REMOVE_EXAMPLES[1].prompt)).toBe("the pogo stick the guy is bouncing on, the black handle grips in his hands, the platform under his feet, its shadow on the ground");expect(targetPhrase("the people walking in the background")).toBe("the people walking in the background");expect(targetPhrase("Erase the logo from the video.")).toBe("the logo");expect(targetPhrase("get rid of the red car and keep the trees")).toBe("the red car");});+ it("names every object a prompt lists, comma-separated (SAM 3.1 and ComfyUI's SAM 3 track each)", () => {+ expect(targetPhrase("the logo and the watermark")).toBe("the logo, the watermark");+ expect(targetPhrase("wires and cables")).toBe("wires, cables");+ expect(targetPhrase("the cup, the spoon and the plate")).toBe("the cup, the spoon, the plate");+ expect(targetPhrase("Remove the cup, the spoon, and the plate.")).toBe("the cup, the spoon, the plate");+ expect(targetPhrase("Remove the cup and remove the plate")).toBe("the cup, the plate");+ expect(targetPhrase("Remove the dog in @Video1 and the cat")).toBe("the dog, the cat");+ expect(targetPhrase("the watermark plus the timestamp")).toBe("the watermark, the timestamp");+ // One object described with "and", or a detail after a comma, stays one.+ expect(targetPhrase("the black and white dog")).toBe("the black and white dog");+ expect(targetPhrase("the man in the red jacket, on the left")).toBe("the man in the red jacket on the left");+ // An instruction after the objects ends the list.+ expect(targetPhrase("the logo and the watermark, and fill the corner with the sky")).toBe("the logo, the watermark");+ // Whole objects up to 160 characters.+ const long = targetPhrase(Array.from({ length: 30 }, (_, i) => `the sticker number ${i + 1}`).join(", "));+ expect(long.length).toBeLessThanOrEqual(160);+ expect(long.endsWith("the sticker number 7")).toBe(true);+ // The provider applies it again to what the planner sent: nothing changes.+ for (const t of [...REMOVE_EXAMPLES.map((x) => x.prompt), "the logo and the watermark", "the black and white dog", "the man in the red jacket, on the left"]) {+ expect(targetPhrase(targetPhrase(t))).toBe(targetPhrase(t));+ }+ expect(removalTitle({ mode: "type", prompt: "the logo and the watermark" })).toBe("Remove · the logo, the watermark");+ });+it("writes Kling's edit prompt the way Higgsfield does", () => {expect(klingPrompt("the coffee cup")).toBe("Remove the coffee cup from @Video1, keep everything else the same.");expect(klingPrompt(REMOVE_EXAMPLES[0].prompt)).toBe(`In @Video1: ${REMOVE_EXAMPLES[0].prompt}`);@@ -178,6 +220,27 @@ describe("Remove object: windows and pieces", () => {expect(pieceSeconds(getEraser("kling-o3")!)).toBe(15);});+ it("cuts frame-count routes (VOID, LTX) on whole frames into counts the route takes as they are", () => {+ const voidCloud = getEraser("void-video-inpainting")!.window!;+ // fal's VOID snaps num_frames to 69, 77 … 197 (8n+5 from 69): every piece is one of those.+ for (const total of [69, 70, 150, 197, 198, 300, 600, 1799]) {+ const got = frameWindows(total, voidCloud);+ expect(got.every((n) => n >= 69 && n <= 197 && (n - 5) % 8 === 0), `${total}: ${got}`).toBe(true);+ expect(total - got.reduce((a, b) => a + b, 0)).toBeLessThan(8);+ }+ expect(frameWindows(68, voidCloud)).toEqual([]);+ // 10 s at 30 fps: two 149-frame pieces, back to back on frame boundaries (the last 2 frames are left out).+ const p = planFrameCuts({ start: 0, end: 10 }, 30, voidCloud);+ expect(p).toEqual([+ { index: 0, start: 0, end: 4.966667, frames: 149 },+ { index: 1, start: 4.966667, end: 9.933333, frames: 149 },+ ]);+ // LTX renders 8n+1 frames and stays under its 720p budget (about 144 frames).+ const ltx = getEraser("ltx-2-3-clean-plate")!.window!;+ for (const total of [9, 120, 145, 360, 1800]) expect(frameWindows(total, ltx).every((n) => n >= 9 && n <= 137 && (n - 1) % 8 === 0)).toBe(true);+ expect(planFrameCuts({ start: 1, end: 13 }, 30, ltx).map((x) => x.frames)).toEqual([121, 121, 113]);+ });+it("says why an eraser can't take a clip", () => {const kling = getEraser("kling-o3")!;expect(removalProblem(kling, src, { start: 0, end: 2 })).toMatch(/at least 3 s — Bria/);@@ -187,6 +250,11 @@ describe("Remove object: windows and pieces", () => {expect(removalProblem(getEraser("oss-vace-remove")!, { ...src, fps: undefined }, { start: 0, end: 5 })).toMatch(/frame rate/);expect(removalProblem(kling, src, { start: 0, end: 13 })).toMatch(/past the end/);expect(removalProblem(kling, { ...src, duration: 90 }, { start: 0, end: 90 })).toMatch(/up to 60 s/);+ // VOID on the cloud takes at least 69 frames; LTX renders at most 60 fps; both need the clip's rate.+ expect(removalProblem(getEraser("void-video-inpainting")!, src, { start: 0, end: 2 })).toMatch(/at least 69 frames \(2\.3 s of this clip\).*Shadows and reflections/);+ expect(removalProblem(getEraser("void-video-inpainting")!, src, { start: 0, end: 2.3 })).toBeNull();+ expect(removalProblem(getEraser("void-video-inpainting")!, { ...src, fps: undefined }, { start: 0, end: 5 })).toMatch(/frame rate/);+ expect(removalProblem(getEraser("ltx-2-3-clean-plate")!, { ...src, fps: 120 }, { start: 0, end: 5 })).toMatch(/up to 60 fps/);expect(tierFor({ width: 1920, height: 1080 })).toBe("1080p");expect(tierFor({ width: 720, height: 1280 })).toBe("720p");expect(tierFor({ width: 640, height: 360 })).toBe("480p");@@ -249,19 +317,49 @@ describe("Remove object: cloud pipelines", () => {expect(step(plan.steps, "final")).toMatchObject({ after: ["join", "sound"], chain: [{ slot: "video" }, { slot: "audio" }] });});- it("VOID (shadows too): its frame count from the piece, the sound put back after", () => {+ it("VOID (shadows too): told the piece's exact frame count, the sound cut to the picture and put back", () => {const six = { ...src, duration: 6 };const plan = planRemoval(input({ eraser: getEraser("void-video-inpainting")!, source: six, range: { start: 0, end: 6 } }));- expect(keys(plan.steps)).toEqual(["erase0", "final"]);- expect(step(plan.steps, "erase0").request).toMatchObject({ prompt: "the coffee cup", params: { sourceDuration: 6, fps: 30 } });+ // 180 frames: one 173-frame piece, cut to exactly those frames; the last 7 are left out, and the sound is cut to match.+ expect(keys(plan.steps)).toEqual(["cut0", "erase0", "sound", "final"]);+ expect(plan.pieces).toEqual([{ index: 0, start: 0, end: 5.766667, frames: 173 }]);+ expect(step(plan.steps, "cut0").request.params).toEqual({ startTime: 0, endTime: 5.766667 });+ expect(step(plan.steps, "erase0")).toMatchObject({ after: ["cut0"], request: { prompt: "the coffee cup", params: { sourceDuration: 5.766667, fps: 30 } } });+ expect(payloadOf(step(plan.steps, "erase0"))).toMatchObject({ video_url: "/api/files/video-from-before.mp4", mask_prompt: "the coffee cup", prompt: REMOVE_SCENE, num_frames: 173 });+ expect(step(plan.steps, "sound").request.params).toEqual({ startTime: 0, endTime: 5.766667 });// No sound in the clip: nothing to put back.- expect(keys(planRemoval(input({ eraser: getEraser("void-video-inpainting")!, range: { start: 0, end: 6 }, source: { ...six, hasAudio: false } })).steps)).toEqual(["erase0"]);+ expect(keys(planRemoval(input({ eraser: getEraser("void-video-inpainting")!, range: { start: 0, end: 6 }, source: { ...six, hasAudio: false } })).steps)).toEqual(["cut0", "erase0"]);+ // A clip of exactly 197 frames is read as it is.+ const exact = planRemoval(input({ eraser: getEraser("void-video-inpainting")!, range: { start: 0, end: 197 / 30 }, source: { ...src, duration: 197 / 30, hasAudio: false } }));+ expect(keys(exact.steps)).toEqual(["erase0"]);+ expect(step(exact.steps, "erase0").request.inputs).toEqual({ video: src.url });+ // 10 s: two cuts of 149 frames, each told 149 (nothing for fal to snap), joined.+ const ten = planRemoval(input({ eraser: getEraser("void-video-inpainting")!, prompt: "the logo and the watermark", source: { ...src, duration: 10 }, range: { start: 0, end: 10 } }));+ expect(keys(ten.steps)).toEqual(["cut0", "erase0", "cut1", "erase1", "join", "sound", "final"]);+ expect(step(ten.steps, "cut1").request.params).toEqual({ startTime: 4.966667, endTime: 9.933333 });+ for (const k of ["erase0", "erase1"]) expect(payloadOf(step(ten.steps, k))).toMatchObject({ mask_prompt: "the logo, the watermark", num_frames: 149 });});- it("LTX Clean Plate removes every person without words or its own soundtrack", () => {- const plan = planRemoval(input({ eraser: getEraser("ltx-2-3-clean-plate")!, prompt: undefined, range: { start: 0, end: 5 } }));- expect(step(plan.steps, "erase0").request).toMatchObject({ params: { generateAudio: false } });+ it("LTX Clean Plate removes every person without words or its own soundtrack, in 8n+1-frame pieces at 720p", () => {+ const plan = planRemoval(input({ eraser: getEraser("ltx-2-3-clean-plate")!, prompt: undefined, range: { start: 0, end: 5 }, source: { ...src, duration: 5 } }));+ expect(step(plan.steps, "erase0").request).toMatchObject({ params: { generateAudio: false, resolution: "720p" } });expect(step(plan.steps, "erase0").request.prompt).toBeUndefined();+ // 150 frames: two pieces of 73 (the budget is about 144 frames at 720p).+ expect(plan.pieces.map((p) => p.frames)).toEqual([73, 73]);+ expect(payloadOf(step(plan.steps, "erase1"))).toMatchObject({ video_url: "/api/files/video-from-before.mp4", num_frames: 73, frames_per_second: 30, resolution: "720p", generate_audio: false });+ });++ it("each cloud eraser's API gets the words, the clip, the clicks or the mask in its own fields", () => {+ const kling = planRemoval(input({ range: { start: 0, end: 12 } }));+ expect(payloadOf(step(kling.steps, "erase0"))).toMatchObject({ video_url: src.url, prompt: "Remove the coffee cup from @Video1, keep everything else the same." });+ const bria = planRemoval(input({ eraser: getEraser("bria-video-erase")!, prompt: "Remove the logo and the watermark" }));+ expect(payloadOf(step(bria.steps, "erase1"))).toMatchObject({ video_url: "/api/files/video-from-before.mp4", prompt: "the logo, the watermark" });+ const points = [{ x: 400, y: 300, label: "positive" as const }, { x: 10, y: 20, label: "negative" as const }];+ const short = planRemoval(input({ mode: "click", eraser: getEraser("bria-video-erase-points")!, points, source: { ...src, duration: 4 }, range: { start: 0, end: 4 } }));+ expect(payloadOf(step(short.steps, "erase0"))).toMatchObject({ video_url: src.url, keypoints: ["{'x':400, 'y':300, 'type':'positive'}", "{'x':10, 'y':20, 'type':'negative'}"] });+ const long = planRemoval(input({ mode: "click", eraser: getEraser("bria-video-erase-points")!, points }));+ expect(payloadOf(step(long.steps, "track"))).toMatchObject({ video_url: src.url, apply_mask: false, point_prompts: [{ x: 400, y: 300, label: 1 }, { x: 10, y: 20, label: 0 }] });+ expect(payloadOf(step(long.steps, "erase0"))).toMatchObject({ video_url: "/api/files/video-from-before.mp4", mask_video_url: "/api/files/mask-from-before.mp4" });});it("Click it, short clip: Bria's clicked eraser reads the points itself", () => {@@ -329,6 +427,13 @@ describe("Remove object: open pipelines", () => {expect(step(plan.steps, "erase2")).toMatchObject({ after: ["erase1"], chain: [{ slot: "mask" }] });// Each later window starts on the frame its mask was tracked on, and loses that frame before the join.expect(step(plan.steps, "erase1").request.params).toMatchObject({ startTime: 2.658333, endTime: 5.358333 });+ // Only the windows a later one waits on save their last tracked mask.+ expect(step(plan.steps, "erase0").request.params?.extra).toEqual({ [HAND_OFF]: true });+ expect(step(plan.steps, "erase1").request.params?.extra).toEqual({ [HAND_OFF]: true });+ expect(step(plan.steps, "erase2").request.params?.extra).toBeUndefined();+ const one = planRemoval(open({ mode: "paint", eraser: getEraser("oss-vace-remove-painted")!, prompt: undefined, mask: "/api/files/uploads/mask.png", range: { start: 0, end: 2 } }));+ expect(keys(one.steps)).toEqual(["erase0"]);+ expect(step(one.steps, "erase0").request.params?.extra).toBeUndefined();expect(step(plan.steps, "keep1")).toMatchObject({ after: ["erase1"], chain: [{ slot: "video" }], request: { modelId: "oss-trim", op: "trim", params: { startTime: 0.025 } } });expect(step(plan.steps, "keep0")).toBeUndefined();expect(step(plan.steps, "join").after).toEqual(["erase0", "keep1", "keep2"]);@@ -350,6 +455,16 @@ describe("Remove object: mask previews", () => {expect(step(clicks, "preview").request).toMatchObject({ params: { points: [{ x: 1, y: 2 }], duration: 1 } });});+ it("says when the preview is the eraser's own mask, and when only SAM 3.1's reading of the words or clicks", () => {+ expect(previewIsEraserMask(getEraser("kling-o3")!, false)).toBe(false);+ expect(previewIsEraserMask(getEraser("bria-video-erase")!, false)).toBe(false);+ expect(previewIsEraserMask(getEraser("bria-video-erase-points")!, false)).toBe(false);+ // SAM 3.1's track is what Bria erases; fal builds VOID's mask with SAM 3; the open graphs track with SAM 3.1.+ expect(previewIsEraserMask(getEraser("bria-video-erase-points")!, true)).toBe(true);+ expect(previewIsEraserMask(getEraser("void-video-inpainting")!, false)).toBe(true);+ expect(previewIsEraserMask(getEraser("oss-vace-remove")!, false)).toBe(true);+ });+it("open: the SAM 3 cut-out of what you typed; no preview for paint or clicks", () => {const steps = planMaskPreview({ engine: "open", mode: "type", title: "t", source: src, range: { start: 0, end: 12 }, prompt: "the dog" })!;expect(step(steps, "preview").request).toMatchObject({ modelId: "oss-video-matte-sam3", prompt: "the dog" });diff --git a/workflows/comfyui/manifest.json b/workflows/comfyui/manifest.jsonindex a5001c9c..18f596b7 100644--- a/workflows/comfyui/manifest.json+++ b/workflows/comfyui/manifest.json@@ -11951,7 +11951,7 @@"vramGb": 24,"license": "Apache-2.0 (Wan 2.1 VACE 14B, lightx2v T2V LoRA, umT5, Wan VAE); SAM 3.1 under Meta's SAM License (commercial use allowed under its terms); GrowMaskWithBlur from ComfyUI-KJNodes (GPL-3.0 code)","validated": true,- "notes": "mask = a PNG of the window's FIRST frame, read from the red channel: white = the object to remove, black = keep (in the clip's shape). SAM3_VideoTrack takes it as initial_mask and tracks the object through the window. Changed from the research graph: the mask is read from the red channel (Fuobe's mask convention, as flux1-fill-inpaint) instead of alpha. The mask is scaled to the work size like the frames (not cropped), so any PNG size lines up. Everything else as video-inpaint-wan-vace: windows in seconds (startTime, duration; at most 81 frames, the largest 4n+1 decoded), width x height = the work-size budget in the clip's shape, paste-back into the original frames, the window's sound kept. For a window after the first, the mask must be painted on (or tracked to) that window's first frame: the second output (node 77, role \"mask\", added by the remove-object package) is the tracked mask of the window's LAST frame (SAM3_TrackToMask before GrowMask, at the work size, white = the object), which Fuobe feeds to the next window as its mask, so the object is followed across windows. Validated by /prompt only (no GPU here)."+ "notes": "mask = a PNG of the window's FIRST frame, read from the red channel: white = the object to remove, black = keep (in the clip's shape). SAM3_VideoTrack takes it as initial_mask and tracks the object through the window. Changed from the research graph: the mask is read from the red channel (Fuobe's mask convention, as flux1-fill-inpaint) instead of alpha. The mask is scaled to the work size like the frames (not cropped), so any PNG size lines up. Everything else as video-inpaint-wan-vace: windows in seconds (startTime, duration; at most 81 frames, the largest 4n+1 decoded), width x height = the work-size budget in the clip's shape, paste-back into the original frames, the window's sound kept. For a window after the first, the mask must be painted on (or tracked to) that window's first frame: the second output (node 77, role \"mask\", added by the remove-object package) is the tracked mask of the window's LAST frame (SAM3_TrackToMask before GrowMask, at the work size, white = the object), which Fuobe feeds to the next window as its mask, so the object is followed across windows. The provider keeps node 77 only when params.extra.handOffMask is true (a window another one waits on); otherwise it is dropped, so a single or last window saves just the video. Validated by /prompt only (no GPU here)."},{"id": "video-erase-void",