Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (codex): orient+alpha-preserve original in ignore-zone composite, cap mask decode, fix Clear race (#1763)

[._.]/ Adam Eivy96e9f37e26ef
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsx
index bdc575366c..207d409777 100644
--- a/client/src/pages/ImageClean.jsx
+++ b/client/src/pages/ImageClean.jsx
@@ -51,7 +51,11 @@ export default function ImageClean() {
if (resultUrlRef.current) URL.revokeObjectURL(resultUrlRef.current);
}, []);
- const runClean = useCallback(async (file, selectedSteps) => {
+ // `skipMask` lets a caller (e.g. Clear) force a mask-free re-clean without
+ // depending on the painter ref having flushed its React state yet — clear()
+ // only schedules state, so reading painterRef.hasMask in the same tick would
+ // still see the stale mask. The Clear path passes skipMask:true explicitly.
+ const runClean = useCallback(async (file, selectedSteps, { skipMask = false } = {}) => {
if (!file) return;
const myRequestId = ++requestIdRef.current;
setBusy(true);
@@ -71,7 +75,7 @@ export default function ImageClean() {
// Ignore-zone mask only matters when a diffusion pass runs — export the
// painted preserve-region as a PNG Blob and ride it in the request envelope
// so the server composites original pixels back into the masked regions.
- if (selectedSteps.diffusion && painterRef.current?.hasMask) {
+ if (!skipMask && selectedSteps.diffusion && painterRef.current?.hasMask) {
const maskBlob = await painterRef.current.exportMaskBlob();
if (maskBlob) {
payload.mask = maskBlob;
@@ -327,7 +331,7 @@ export default function ImageClean() {
<Undo2 size={12} /> Undo
</button>
<button
- onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps); }}
+ onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps, { skipMask: true }); }}
className="px-2 py-1 rounded text-xs flex items-center gap-1 border border-port-border text-gray-400 hover:text-white transition-colors"
>
<X size={12} /> Clear
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
index 714846401f..398e101bcb 100644
--- a/server/lib/imageClean.js
+++ b/server/lib/imageClean.js
@@ -237,7 +237,11 @@ const IGNORE_ZONE_FEATHER_MAX = 50;
*/
export async function compositeIgnoreZone(base, original, mask, { feather = IGNORE_ZONE_FEATHER_DEFAULT, sharpImpl = sharp } = {}) {
if (!Buffer.isBuffer(base) || !Buffer.isBuffer(original) || !Buffer.isBuffer(mask)) return null;
- const meta = await sharpImpl(base).metadata().catch(() => null);
+ // Cap every decode at MAX_PIXELS — the mask (and, via the length-framed
+ // envelope, the original) can be independently sized, so the decompression-
+ // bomb guard the main cleaner enforces must extend to this pass too.
+ const opts = { limitInputPixels: MAX_PIXELS };
+ const meta = await sharpImpl(base, opts).metadata().catch(() => null);
const w = Math.round(Number(meta?.width));
const h = Math.round(Number(meta?.height));
if (!(w > 0) || !(h > 0)) return null;
@@ -250,29 +254,36 @@ export async function compositeIgnoreZone(base, original, mask, { feather = IGNO
const run = async () => {
// Greyscale + resize the mask to the base dims so the client can paint at any
// resolution; blur the edge for a soft boundary when feathering is on.
- let maskPipeline = sharpImpl(mask)
+ let maskPipeline = sharpImpl(mask, opts)
.resize(w, h, { fit: 'fill', kernel: 'cubic' })
.greyscale();
if (sigma >= 0.3) maskPipeline = maskPipeline.blur(sigma);
const alpha = await maskPipeline.toColourspace('b-w').raw().toBuffer();
- // Resize the original to the base dims too (defensive against an orientation
- // bake that swapped W/H upstream), strip any existing alpha, then attach the
- // feathered mask AS the alpha channel so WHITE = fully-preserved original.
- const originalRgba = await sharpImpl(original)
+ // The user paints the mask on the browser preview, which honours EXIF
+ // orientation — and the diffused `base` is already in that orientation. Bake
+ // the same orientation into the ORIGINAL (`.rotate()`) before sampling its
+ // pixels, or an oriented JPEG/PNG would restore rotated/wrong pixels into
+ // the masked regions. `.ensureAlpha()` (NOT removeAlpha) keeps the original's
+ // own transparency; the mask is then MULTIPLIED into that alpha below so a
+ // transparent source region stays transparent instead of turning opaque.
+ const originalRgba = await sharpImpl(original, opts)
+ .rotate()
.resize(w, h, { fit: 'fill', kernel: 'cubic' })
- .removeAlpha()
.ensureAlpha()
.raw()
.toBuffer();
- // Overwrite the (opaque) alpha channel with the mask so compositing honours it.
- for (let i = 0; i < w * h; i += 1) originalRgba[i * 4 + 3] = alpha[i];
+ // Fold the feathered mask into the original's alpha: preserved (white) keeps
+ // the source alpha, unmasked (black) → 0 so `base` shows through.
+ for (let i = 0; i < w * h; i += 1) {
+ originalRgba[i * 4 + 3] = Math.round((originalRgba[i * 4 + 3] * alpha[i]) / 255);
+ }
const overlay = await sharpImpl(originalRgba, { raw: { width: w, height: h, channels: 4 } })
.png()
.toBuffer();
- const data = await sharpImpl(base)
+ const data = await sharpImpl(base, opts)
.png()
.composite([{ input: overlay, blend: 'over' }])
.png({ compressionLevel: 6 })
diff --git a/server/lib/imageClean.test.js b/server/lib/imageClean.test.js
index d0c4a26c83..ae5d1b3b43 100644
--- a/server/lib/imageClean.test.js
+++ b/server/lib/imageClean.test.js
@@ -475,4 +475,20 @@ describe('compositeIgnoreZone', () => {
expect(await compositeIgnoreZone(null, redOriginal, halfMask)).toBeNull();
expect(await compositeIgnoreZone(blueBase, redOriginal, Buffer.from('not an image'))).toBeNull();
});
+
+ it('preserves the original alpha channel in masked regions (transparent source stays transparent)', async () => {
+ // A fully-transparent original: even inside the white mask, the composite
+ // must keep the base showing through (mask alpha × source alpha = 0), not
+ // paint opaque black/undefined pixels over it.
+ const transparent = await sharp({
+ create: { width: W, height: H, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 0 } },
+ }).png().toBuffer();
+ const out = await compositeIgnoreZone(blueBase, transparent, halfMask, { feather: 0 });
+ expect(out).toBeTruthy();
+ // Left (masked) core: the original is transparent, so the diffused blue base
+ // still shows — the source did NOT become opaque red.
+ const left = await pixelAt(out.data, 2, 8);
+ expect(left.b).toBeGreaterThan(200);
+ expect(left.r).toBeLessThan(60);
+ });
});