Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create): wire local RMBG background-removal cutout

purple6763220a978b
diff --git a/src/api/__tests__/dynamic-workflow-removebg.test.ts b/src/api/__tests__/dynamic-workflow-removebg.test.ts
new file mode 100644
index 00000000..83143705
--- /dev/null
+++ b/src/api/__tests__/dynamic-workflow-removebg.test.ts
@@ -0,0 +1,85 @@
+/**
+ * Local background removal (David 2026-07-04): buildDynamicWorkflow must emit a
+ * self-contained LoadImage → RMBG → SaveImage cutout graph instead of letting a
+ * `removebg` request fall through to a diffusion pass. Every RMBG widget is
+ * defaulted from the node's LIVE object_info schema so we never hard-code an
+ * enum a future RMBG version would reject with a ComfyUI 400.
+ *
+ * Run: npx vitest run src/api/__tests__/dynamic-workflow-removebg.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mock only the live-fetch boundary; keep the real pure helpers.
+vi.mock('../comfyui-nodes', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../comfyui-nodes')>()
+ return { ...actual, getAllNodeInfo: vi.fn() }
+})
+
+import { buildDynamicWorkflow, WorkflowUnavailableError } from '../dynamic-workflow'
+import { getAllNodeInfo } from '../comfyui-nodes'
+
+// A realistic ComfyUI-RMBG "RMBG" node: one IMAGE connection (`image`) plus a
+// handful of widgets, including a `background` combo whose "Alpha" option yields
+// a transparent cutout.
+const RMBG_NODES = {
+ RMBG: {
+ input: {
+ required: {
+ image: ['IMAGE'],
+ model: [['RMBG-2.0', 'INSPYRENET', 'BEN2', 'BiRefNet-general'], { default: 'RMBG-2.0' }],
+ sensitivity: ['FLOAT', { default: 1.0, min: 0, max: 1, step: 0.01 }],
+ process_res: ['INT', { default: 1024, min: 256, max: 2048, step: 128 }],
+ mask_blur: ['INT', { default: 0, min: 0, max: 64 }],
+ background: [['Alpha', 'black', 'white', 'green'], { default: 'Alpha' }],
+ invert_output: ['BOOLEAN', { default: false }],
+ },
+ },
+ output: ['IMAGE', 'MASK'],
+ },
+ LoadImage: { input: { required: { image: [[]] } } },
+ SaveImage: { input: { required: {} } },
+}
+
+const removebgParams = {
+ model: 'sdxl.safetensors',
+ prompt: 'a portrait', negativePrompt: '',
+ width: 1024, height: 1024, steps: 20, cfgScale: 7, seed: 1, batchSize: 1,
+ removebg: true,
+ inputImage: 'photo.png',
+} as never
+
+describe('buildDynamicWorkflow — local background removal (RMBG cutout)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(getAllNodeInfo).mockResolvedValue(RMBG_NODES as never)
+ })
+
+ it('builds a self-contained LoadImage → RMBG → SaveImage graph', async () => {
+ const wf = await buildDynamicWorkflow(removebgParams)
+ const types = Object.values(wf).map((n: any) => n.class_type).sort()
+ expect(types).toEqual(['LoadImage', 'RMBG', 'SaveImage'])
+
+ const loadId = Object.keys(wf).find((k) => wf[k].class_type === 'LoadImage')!
+ const rmbgId = Object.keys(wf).find((k) => wf[k].class_type === 'RMBG')!
+ const load = wf[loadId] as any
+ const rmbg = wf[rmbgId] as any
+ const save = Object.values(wf).find((n: any) => n.class_type === 'SaveImage') as any
+
+ // Source image loaded; RMBG.image wired to it; all other widgets defaulted.
+ expect(load.inputs.image).toBe('photo.png')
+ expect(rmbg.inputs.image).toEqual([loadId, 0])
+ expect(rmbg.inputs.model).toBe('RMBG-2.0') // combo → declared default
+ expect(rmbg.inputs.sensitivity).toBe(1.0) // FLOAT default
+ expect(rmbg.inputs.process_res).toBe(1024) // INT default
+ expect(rmbg.inputs.invert_output).toBe(false) // BOOLEAN default
+ expect(rmbg.inputs.background).toBe('Alpha') // nudged to transparent
+ // SaveImage takes RMBG's IMAGE output (slot 0) → transparent PNG.
+ expect(save.inputs.images).toEqual([rmbgId, 0])
+ })
+
+ it('throws an actionable WorkflowUnavailableError when the RMBG node is missing', async () => {
+ vi.mocked(getAllNodeInfo).mockResolvedValue({ LoadImage: { input: { required: {} } } } as never)
+ await expect(buildDynamicWorkflow(removebgParams)).rejects.toBeInstanceOf(WorkflowUnavailableError)
+ await expect(buildDynamicWorkflow(removebgParams)).rejects.toThrow(/ComfyUI-RMBG|background-removal/i)
+ })
+})
diff --git a/src/api/comfyui.ts b/src/api/comfyui.ts
index 70679050..3b1d248f 100644
--- a/src/api/comfyui.ts
+++ b/src/api/comfyui.ts
@@ -36,6 +36,7 @@ export interface GenerateParams {
batchSize: number
inputImage?: string // I2I source image filename (uploaded to ComfyUI)
denoise?: number // I2I denoise strength (0.0–1.0, default 1.0 = full txt2img)
+ removebg?: boolean // Background removal: LoadImage → RMBG → SaveImage cutout (no diffusion)
// F2 (cinemazverev GH#4), extended for multi-LoRA (konata 2026-06-09:
// "agent cannot load multiple loras"): one filename or an ordered list.
// Multiple LoRAs are CHAINED — LoraLoader N feeds (model, clip) into
diff --git a/src/api/discover.ts b/src/api/discover.ts
index 3d75bb95..12842962 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -1269,6 +1269,16 @@ export const CUSTOM_NODE_REGISTRY: Record<string, { repo: string; name: string;
name: 'ComfyUI-VideoHelperSuite',
requiredNodes: ['VHS_VideoCombine', 'VHS_LoadVideo'],
},
+ // Background removal (Create → Remove Background). ComfyUI-RMBG registers the
+ // `RMBG` node — the exact class the capability probe + workflow builder look
+ // for — and auto-downloads its cutout model (BiRefNet / RMBG-2.0, ~300 MB)
+ // into ComfyUI/models/RMBG on first use. So the one-click action only needs to
+ // install the node; the model lands on the first cutout run.
+ 'rmbg': {
+ repo: 'https://github.com/1038lab/ComfyUI-RMBG',
+ name: 'ComfyUI-RMBG',
+ requiredNodes: ['RMBG'],
+ },
}
export interface ModelBundle {
diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.ts
index 6bc2554e..18c25798 100644
--- a/src/api/dynamic-workflow.ts
+++ b/src/api/dynamic-workflow.ts
@@ -360,6 +360,25 @@ export async function buildDynamicWorkflow(
const nodes = categorizeNodes(allNodes)
const models = detectAvailableModels(allNodes)
+ // ─── Background removal (RMBG cutout) ───
+ // A cutout needs no diffusion model, so branch out before strategy detection.
+ // ComfyUI-RMBG (node class "RMBG"): LoadImage → RMBG → SaveImage. We read the
+ // node's REAL input schema live and default every widget from it, so we never
+ // hard-code an enum spelling a future RMBG version could reject with a ComfyUI
+ // 400 ("Value not in list"). Gated upstream by caps.rmbg.
+ const gp = params as GenerateParams
+ if (!isVideo && gp.removebg && gp.inputImage) {
+ const rmbgMeta = allNodes['RMBG']
+ if (!rmbgMeta) {
+ throw new WorkflowUnavailableError(
+ 'The background-removal node (ComfyUI-RMBG) is not installed in ComfyUI. Install it from the Remove Background tab, then try again.',
+ 'unavailable',
+ { pack: 'ComfyUI-RMBG', url: 'https://github.com/1038lab/ComfyUI-RMBG' },
+ )
+ }
+ return buildRemoveBgWorkflow(gp, rmbgMeta)
+ }
+
const { strategy, reason, installHint } = determineStrategy(type, isVideo, nodes, models)
log.info(`[dynamic-workflow] Strategy: ${strategy} (${reason})`)
@@ -845,6 +864,54 @@ export async function buildDynamicWorkflow(
// ─── Wrapper Workflow Builders ───
+// Background removal (ComfyUI-RMBG). Self-contained LoadImage → RMBG → SaveImage
+// graph. Every RMBG widget is defaulted from the node's LIVE object_info schema
+// (`rmbgMeta`) so the graph stays valid across RMBG versions instead of pinning
+// input names/enums we'd have to guess. The `background` widget is nudged toward
+// a transparent/alpha option so the result is a real RGBA cutout, not a matte.
+function buildRemoveBgWorkflow(params: GenerateParams, rmbgMeta: any): Record<string, any> {
+ const workflow: Record<string, any> = {}
+ workflow['1'] = { class_type: 'LoadImage', inputs: { image: params.inputImage } }
+
+ const required: Record<string, any> = rmbgMeta?.input?.required ?? {}
+ const rmbgInputs: Record<string, any> = { image: ['1', 0] }
+ for (const [name, spec] of Object.entries(required)) {
+ if (name === 'image') continue
+ const d = rmbgWidgetDefault(name, spec)
+ if (d.set) rmbgInputs[name] = d.value
+ }
+ workflow['2'] = { class_type: 'RMBG', inputs: rmbgInputs }
+
+ // RMBG returns (IMAGE, MASK, …); slot 0 is the cut-out image. SaveImage writes
+ // the transparent PNG, picked up by extractComfyOutputFiles like any output.
+ workflow['3'] = {
+ class_type: 'SaveImage',
+ inputs: { images: ['2', 0], filename_prefix: promptFilenamePrefix(params.prompt, false) },
+ }
+ return workflow
+}
+
+// Resolve a default value for one RMBG widget input from its object_info spec.
+// Combo → prefer a transparent option for the background widget, else the
+// declared default / first entry. Primitives → their declared default. A
+// non-widget connection input (some other IMAGE/MASK) can't be auto-wired, so
+// skip it — ComfyUI surfaces a clear error rather than us guessing wrong.
+function rmbgWidgetDefault(name: string, spec: any): { set: boolean; value?: any } {
+ const t = Array.isArray(spec) ? spec[0] : spec
+ const cfg = Array.isArray(spec) ? spec[1] : undefined
+ if (Array.isArray(t)) {
+ if (/back\s*ground|(^|_)bg($|_)/i.test(name)) {
+ const alpha = t.find((o: any) => typeof o === 'string' && /alpha|transparent/i.test(o))
+ if (alpha) return { set: true, value: alpha }
+ }
+ return { set: true, value: cfg?.default ?? t[0] }
+ }
+ if (t === 'BOOLEAN') return { set: true, value: cfg?.default ?? false }
+ if (t === 'INT' || t === 'FLOAT') return { set: true, value: cfg?.default ?? 0 }
+ if (t === 'STRING') return { set: true, value: cfg?.default ?? '' }
+ return { set: false }
+}
+
function addVideoOutput(workflow: Record<string, any>, n: number, decodeId: string, fps: number, nodes: CategorizedNodes, prompt?: string): number {
const saveId = String(n++)
const prefix = promptFilenamePrefix(prompt, true)