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
Layers: Keep transparency follows the layer's own pixels, not its place in the stack
Claude3ca7d8dc323b
diff --git a/src/components/layers/keep-alpha.ts b/src/components/layers/keep-alpha.tsnew file mode 100644index 00000000..4de66046--- /dev/null+++ b/src/components/layers/keep-alpha.ts@@ -0,0 +1,37 @@+"use client";++import { useEffect, useState } from "react";+import type { LayerNode } from "@/lib/layers";+import { hasSeeThrough } from "./render";++/**+ * “Keep transparency” for a run on a layer: on when the layer's own pixels are see-through (a cut-out,+ * a decomposition's layer), off for full-frame pictures. Whole-image Inpaint and Enhancer results land+ * on top as opaque layers; a cut-out there would only strip their background (and bill for it). The+ * switch wins once flipped, for that layer's picture.+ */+export function useKeepAlpha(node?: LayerNode): [boolean, (on: boolean) => void] {+ const src = node?.src;+ const crop = node?.crop;+ const natural = node?.natural;+ const key = node ? `${node.id}|${node.src}|${node.crop?.join(",") ?? ""}` : "";+ const [measured, setMeasured] = useState<{ key: string; clear: boolean } | null>(null);+ const [picked, setPicked] = useState<{ key: string; on: boolean } | null>(null);+ useEffect(() => {+ if (!src) return;+ let gone = false;+ hasSeeThrough({ src, crop: crop ?? null, natural }).then(+ (clear) => {+ if (!gone) setMeasured({ key, clear });+ },+ () => {+ // Unknown (the picture didn't load): stays off.+ },+ );+ return () => {+ gone = true;+ };+ }, [key, src, crop, natural]);+ const on = !!node && (picked?.key === key ? picked.on : measured?.key === key && measured.clear);+ return [on, (v) => setPicked({ key, on: v })];+}diff --git a/src/components/layers/layers-panel.tsx b/src/components/layers/layers-panel.tsxindex 5eb333fa..878f82d3 100644--- a/src/components/layers/layers-panel.tsx+++ b/src/components/layers/layers-panel.tsx@@ -64,6 +64,7 @@ import {import { cn } from "@/lib/utils";import { Field } from "./bits";import { costLabel, modelsFor, TOOL_FOR_JOB, useEditor } from "./editor-context";+import { useKeepAlpha } from "./keep-alpha";import { downloadLayer, loadImage, sizeOf } from "./render";import { SaveElementDialog } from "./save-element";@@ -496,8 +497,8 @@ function SelectedLayer({ node }: { node: LayerNode }) {const options = modelsFor(models, TOOL_MODELS.regenerate[engine]);const [modelId, setModelId] = useState<string | undefined>();const model = options.find((m) => m.id === modelId) ?? options[0];- // Layers cut out of a picture keep their transparency; the bottom layer is usually a full picture.- const [keepAlpha, setKeepAlpha] = useState(node.z > 0);+ // Layers cut out of a picture keep their transparency; full pictures (the bottom layer, a whole-image result) don't.+ const [keepAlpha, setKeepAlpha] = useKeepAlpha(node);const [starting, setStarting] = useState(false);const running = busyJob(node.id);// The newest failed run on this layer, whichever tool started it (its form can try again).diff --git a/src/components/layers/render.ts b/src/components/layers/render.tsindex 52e21485..acb85737 100644--- a/src/components/layers/render.ts+++ b/src/components/layers/render.ts@@ -11,6 +11,7 @@ import {exportScale,layerExportScale,nativeSize,+ seeThrough,slugify,sourceBoxOf,sourceRect,@@ -67,7 +68,7 @@ export function sizeOf(img: HTMLImageElement): [number, number] {}/** A layer's source rectangle in the loaded image's own pixels (the stored crop may be in other units for SVGs). */-function srcRectFor(node: LayerNode, img: HTMLImageElement): Box {+function srcRectFor(node: Pick<LayerNode, "crop" | "natural">, img: HTMLImageElement): Box {const [iw, ih] = sizeOf(img);const r = sourceRect(node);if (!r) return [0, 0, iw, ih];@@ -261,6 +262,25 @@ export async function uploadDerived(blob: Blob, name: string): Promise<string> {return body.url;}+/**+ * Whether a layer's own pixels (its crop of the image, before its mask and soft edge, which a new+ * version keeps anyway) are see-through: a cut-out or a decomposition's layer, not a full-frame+ * picture. Measured on a copy at most 256 px wide.+ */+export async function hasSeeThrough(node: Pick<LayerNode, "src" | "crop" | "natural">): Promise<boolean> {+ const img = await loadImage(node.src);+ const [sx, sy, sw, sh] = srcRectFor(node, img);+ const k = Math.min(1, 256 / Math.max(sw, sh, 1));+ const w = Math.max(1, Math.round(sw * k));+ const h = Math.max(1, Math.round(sh * k));+ const c = document.createElement("canvas");+ c.width = w;+ c.height = h;+ const ctx = c.getContext("2d", { willReadFrequently: true })!;+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, w, h);+ return seeThrough(ctx.getImageData(0, 0, w, h).data);+}+/** The alpha box of an image in its own pixels (measured on a copy at most 1024 px wide). */export function alphaBox(img: HTMLImageElement): Box | null {const [nw, nh] = sizeOf(img);diff --git a/src/components/layers/tools.tsx b/src/components/layers/tools.tsxindex ac7f13c0..68c504fe 100644--- a/src/components/layers/tools.tsx+++ b/src/components/layers/tools.tsx@@ -79,6 +79,7 @@ import { cn } from "@/lib/utils";import { Field, Segmented } from "./bits";import { costLabel, isFailed, isRunning, latestJob, modelsFor, useEditor, type Target, type ToolId } from "./editor-context";import { LayerGrader } from "./grade-gl";+import { useKeepAlpha } from "./keep-alpha";import { LayerThumb } from "./layers-panel";import { loadImage, ratioOf, renderDoc, renderNative, sizeOf, uploadRender } from "./render";@@ -674,9 +675,9 @@ function RelightTool() {const [light, setLight] = useState(RELIGHT_LIGHTS[0][0]);const [direction, setDirection] = useState(RELIGHT_DIRECTIONS[0][0]);const [extra, setExtra] = useState("");- const [keepAlpha, setKeepAlpha] = useState(!!selected && selected.z > 0);+ const [keepAlpha, setKeepAlpha] = useKeepAlpha(selected);return (- <SimpleTool tool="relight" verb="Relight" failedTitle="Couldn't relight it" settings={{ light, direction, keepAlpha: !!selected && keepAlpha }} prompt={extra.trim() || undefined}>+ <SimpleTool tool="relight" verb="Relight" failedTitle="Couldn't relight it" settings={{ light, direction, keepAlpha }} prompt={extra.trim() || undefined}><Field label="Lighting"><Chips label="Lighting" value={light} options={RELIGHT_LIGHTS.map(([l]) => l)} onChange={setLight} /></Field>@@ -699,11 +700,10 @@ function AnglesTool() {const [tilt, setTilt] = useState(0);const [zoom, setZoom] = useState(5);const [angle, setAngle] = useState(ANGLES[0][0]);- const [keepAlpha, setKeepAlpha] = useState(!!selected && selected.z > 0);+ const [keepAlpha, setKeepAlpha] = useKeepAlpha(selected);const sliders = picker.modelId === "qwen-multiple-angles";- const keep = !!selected && keepAlpha;return (- <SimpleTool tool="angles" verb="New angle" failedTitle="Couldn't make the new angle" picker={picker} settings={sliders ? { rotate, tilt, zoom, keepAlpha: keep } : { angle, keepAlpha: keep }}>+ <SimpleTool tool="angles" verb="New angle" failedTitle="Couldn't make the new angle" picker={picker} settings={sliders ? { rotate, tilt, zoom, keepAlpha } : { angle, keepAlpha }}>{sliders ? (<><Field label="Rotate" hint={`${rotate}°`}>@@ -892,7 +892,7 @@ function InpaintTool() {const { target, node } = useTarget();const { modelId, model, setModelId } = useToolModel("inpaint");const [prompt, setPrompt] = useState("");- const [keepAlpha, setKeepAlpha] = useState(!!node && node.z > 0);+ const [keepAlpha, setKeepAlpha] = useKeepAlpha(node);const [painted, setPainted] = useState<Box | null>(null);const { busy, go } = useRun();const [preparing, setPreparing] = useState(false);@@ -952,7 +952,7 @@ function InpaintTool() {sk.drawImage(tint, 0, 0);const name = node?.name ?? "image";const [image, maskUrl, sketchUrl] = await Promise.all([uploadRender(picture, `inpaint-${name}`), uploadRender(mask, `inpaint-mask-${name}`), uploadRender(sketch, `inpaint-marked-${name}`)]);- await go({ tool: "inpaint", target, image, mask: maskUrl, sketch: sketchUrl, modelId, prompt: prompt.trim(), settings: { keepAlpha: !!node && keepAlpha }, label: "Inpaint" });+ await go({ tool: "inpaint", target, image, mask: maskUrl, sketch: sketchUrl, modelId, prompt: prompt.trim(), settings: { keepAlpha }, label: "Inpaint" });} catch (e) {toast.error((e as Error).message || "Couldn't prepare the painted area");} finally {@@ -1026,11 +1026,11 @@ function EnhanceTool() {const info = ENHANCE_LOOKS.find((l) => l.id === look)!;const { modelId, model, setModelId } = useToolModel("enhance", enhanceModels(look, engine));const [extra, setExtra] = useState("");- const [keepAlpha, setKeepAlpha] = useState(!!node && node.z > 0);+ const [keepAlpha, setKeepAlpha] = useKeepAlpha(node);const { busy, go } = useRun();const job = latestJob(jobs, ["enhance"], node?.id ?? null);const detail = look === "detail";- const run = () => void go({ tool: "enhance", target, modelId, prompt: detail ? undefined : extra.trim() || undefined, settings: { look, keepAlpha: !detail && !!node && keepAlpha }, label: info.verb });+ const run = () => void go({ tool: "enhance", target, modelId, prompt: detail ? undefined : extra.trim() || undefined, settings: { look, keepAlpha: !detail && keepAlpha }, label: info.verb });return (<div className="space-y-4"><Scope node={node} />diff --git a/src/lib/layers.ts b/src/lib/layers.tsindex 99b69a4d..5d12b70e 100644--- a/src/lib/layers.ts+++ b/src/lib/layers.ts@@ -519,6 +519,17 @@ export function bboxFromAlpha(data: ArrayLike<number>, width: number, height: nureturn maxX < 0 ? null : [minX, minY, maxX - minX + 1, maxY - minY + 1];}+/**+ * Whether RGBA pixels are a cut-out rather than a full-frame picture: at least `share` of them mostly+ * clear (a decomposition's layer, a removed background). A few soft edge pixels don't count.+ */+export function seeThrough(rgba: ArrayLike<number>, share = 0.005): boolean {+ const n = Math.floor(rgba.length / 4);+ let clear = 0;+ for (let i = 3; i < rgba.length; i += 4) if (rgba[i] < 128) clear++;+ return n > 0 && clear / n >= share;+}+/** Where a document point falls inside a (rotated) layer: [u, v] in 0–1, or null when outside. */export function toLocal(node: Pick<LayerNode, "x" | "y" | "w" | "h" | "rotation">, px: number, py: number): [number, number] | null {const cx = node.x + node.w / 2;@@ -1047,10 +1058,14 @@ export const INPAINT_TINT = "rgba(255, 59, 48, 0.55)";/** Inpaint models with no mask input: they're shown the painted area tinted red instead. */export const INPAINT_SEES_TINT = new Set(["nano-banana-pro"]);-/** The instruction an Inpaint run sends: what goes in the painted area, and that nothing else changes. */-export function inpaintPrompt(prompt: string, keepAlpha = false): string {+/**+ * The instruction an Inpaint run sends: what goes in the painted area, blended in. Nothing about the+ * background, even on a see-through layer: only the painted area changes, and the cut-out step that+ * follows restores the transparency.+ */+export function inpaintPrompt(prompt: string): string {const p = prompt.trim().replace(/[.\s]+$/, "");- return `${p}. Blend it into the surroundings with matching light, perspective and grain.${keepAlpha ? " Keep the subject on a plain, even background." : ""}`;+ return `${p}. Blend it into the surroundings with matching light, perspective and grain.`;}// ---------------------------------------------------------------------------diff --git a/src/server/layers.ts b/src/server/layers.tsindex c2b71d49..060fcd8b 100644--- a/src/server/layers.ts+++ b/src/server/layers.ts@@ -338,7 +338,7 @@ export function jobSteps(input: LayerJobInput, opts: { batchTitle?: string } = {if (!prompt) throw new LayersError("Say what should fill the painted area", 400);const model = toolModel(tool, engine, input.modelId);// Mask models take the mask; edit models are shown the painted area tinted red (applySketch picks).- add("inpaint", base(model, { op: "inpaint", prompt: inpaintPrompt(prompt, s.keepAlpha), inputs: { images: [needImage()], mask: input.mask, ...(input.sketch ? { sketch: input.sketch } : {}) }, params: aspectFor(model) }));+ add("inpaint", base(model, { op: "inpaint", prompt: inpaintPrompt(prompt), inputs: { images: [needImage()], mask: input.mask, ...(input.sketch ? { sketch: input.sketch } : {}) }, params: aspectFor(model) }));if (s.keepAlpha) cutout("inpaint");break;}diff --git a/tests/layers-api.test.ts b/tests/layers-api.test.tsindex 76825ed7..47b63b41 100644--- a/tests/layers-api.test.ts+++ b/tests/layers-api.test.ts@@ -162,7 +162,8 @@ describe("job steps", () => {["inpaint", "oss-flux-fill", "inpaint"],["cutout", "oss-rmbg", "bg-remove"],]);- expect(open[0].request.prompt).toMatch(/Keep the subject on a plain, even background\.$/);+ // Only the painted area changes: no plain-background ask, the cut-out restores the transparency.+ expect(open[0].request.prompt).toBe("a vase of tulips. Blend it into the surroundings with matching light, perspective and grain.");expect(open[1]).toMatchObject({ after: "inpaint", chain: [{ slot: "images" }] });expect(() => steps({ ...paint, mask: undefined })).toThrow(/Paint over the area/);expect(() => steps({ ...paint, prompt: " " })).toThrow(/fill the painted area/);diff --git a/tests/layers.test.ts b/tests/layers.test.tsindex 15d096fa..fee42c35 100644--- a/tests/layers.test.ts+++ b/tests/layers.test.ts@@ -51,6 +51,7 @@ import {needsDetectedSize,placeTextBlocks,readableBackdrop,+ seeThrough,coverage,defaultLayers,exportScale,@@ -469,6 +470,20 @@ describe("edit text", () => {expect(readableBackdrop(px([0, 0, 0, 0]))).toBe("#ffffff");});+ it("keeps transparency by default only for see-through layers, not full-frame pictures", () => {+ const pixels = (n: number, clear: number) => Array.from({ length: n }, (_, i) => [200, 120, 90, i < clear ? 0 : 255]).flat();+ // A whole-image Inpaint or Enhancer result: opaque everywhere.+ expect(seeThrough(pixels(1000, 0))).toBe(false);+ // A soft edge pixel or two doesn't make a cut-out.+ expect(seeThrough(pixels(1000, 2))).toBe(false);+ // A decomposition's layer or a removed background.+ expect(seeThrough(pixels(1000, 400))).toBe(true);+ expect(seeThrough(pixels(1000, 5))).toBe(true);+ // Half-clear pixels count as clear below 128.+ expect(seeThrough([0, 0, 0, 127, 0, 0, 0, 255])).toBe(true);+ expect(seeThrough([])).toBe(false);+ });+it("lays detected lines out in the frame the detector read, like the cloud route's blocks", () => {const rows = placeTextBlocks([@@ -489,7 +504,6 @@ describe("edit text", () => {describe("inpaint and Save as element", () => {it("asks for the painted area only", () => {expect(inpaintPrompt(" a red scarf. ")).toBe("a red scarf. Blend it into the surroundings with matching light, perspective and grain.");- expect(inpaintPrompt("a hat", true)).toMatch(/grain\. Keep the subject on a plain, even background\.$/);});it("names a layer's element and guesses its kind", () => {