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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Image Cleaner: ignore-zone mask preserves text/faces through the diffusion pass (#1763)
[._.]/ Adam Eivybaf2ebd735e3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9b3525df44..e12478fa68 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -102,6 +102,7 @@## Dev Tools- **[issue-1763] The Image Cleaner gained a CPU "Diffusion pass" step that actually disrupts SynthID.** Building on the Phase 1 composable pipeline (metadata/C2PA + median/sharpen toggles, #1768), the `/devtools/image-clean` page now offers a third opt-in step: a CPU-only diffusion pass (default OFF, lossy) that runs the same spatial round-trip as the ImageGen lightbox regenerate — resize-squeeze + micro color/contrast nudge + high-frequency perturbation (`applyLightRegen`) — perturbing SynthID's resolution-dependent watermark carriers. It runs synchronously in-request after the metadata and denoise steps (pipeline order: metadata → median/sharpen → diffusion), always re-encodes to PNG, and reports a fidelity metric (pixel-delta % + PSNR) in the per-step report so the UI can honestly say it *disrupts* the watermark rather than *removes* it (never verified against Google's detector). Options ride in the query string (`?diffusion=light`). The higher-reliability GPU FLUX img2img round-trip — which needs a non-gallery render seam factored out of the lightbox `/regenerate` flow plus async media-job progress — is a tracked follow-up; requesting it (`?diffusion=gpu`) returns an actionable 501 for now. The ignore-zone mask painter and resolution-aware GPU options also remain in that follow-up. (`server/routes/imageClean.js`, `client/src/services/apiMedia.js`, `client/src/pages/ImageClean.jsx`)+- **[issue-1763] The Image Cleaner's diffusion step gained an ignore-zone mask so you can preserve text and faces.** Diffusion — even the low-strength CPU pass — redraws the whole frame and garbles comic dialog, faces, and fine text. When the diffusion step is on, the `/devtools/image-clean` page now shows a preserve-region painter (brush + rectangle, with undo/clear and adjustable brush size + feather) over the source: you mark the regions the pass must not alter, and after the diffusion runs the server composites the ORIGINAL pixels back into those regions with a feathered (Gaussian-blurred) edge — a pure `sharp` round-trip (`compositeIgnoreZone`), no runner/GPU needed. The mask rides in the request as a no-dependency length-framed envelope (`<uint32 maskLen><mask PNG><image bytes>`, `?mask=1&feather=<px>`), and the per-step report labels the tradeoff honestly: a preserved region keeps its original SynthID locally, so the mask is a deliberate per-region quality-vs-disruption choice. The higher-reliability GPU FLUX round-trip and its resolution-aware options are tracked separately (#2264); requesting `?diffusion=gpu` still returns an actionable 501. (`server/lib/imageClean.js`, `server/routes/imageClean.js`, `client/src/components/media/IgnoreZonePainter.jsx`, `client/src/pages/ImageClean.jsx`, `client/src/services/apiMedia.js`)- **The Usage page now shows your Claude Code subscription rate limits, not just PortOS's own token counts.** The `/devtools/usage` page previously only reported PortOS's internal AI-toolkit accounting (its own sessions/messages/tokens). It now leads with a **Claude Code Subscription** panel that surfaces the same numbers as the CLI's `/usage` command — current-session %, weekly % (all models and per-model, e.g. Fable), how much is left in each, and when each window resets — as color-coded meters that load on page open with a manual Refresh. Because there's no structured usage endpoint in the CLI, the server reads it the only way available: it runs `claude -p` with `/usage` on stdin (a read-only call that consumes zero tokens), parses the human-readable output into JSON, and caches it for 60s. Reset times render in the **machine's timezone** — resolved from the OS, not the server process's env — so a server running under PM2/systemd in UTC still shows the same reset times as an interactive `/usage`, instead of UTC-shifted ones. The numbers are a per-machine local approximation (they don't include other devices or claude.ai), and the panel says so. If the `claude` CLI isn't installed/signed-in, the panel shows a friendly note instead of erroring. (`server/services/claudeCodeUsage.js`, `server/routes/usage.js`, `client/src/pages/UsagePage.jsx`)## Fixeddiff --git a/client/src/components/media/IgnoreZonePainter.jsx b/client/src/components/media/IgnoreZonePainter.jsxnew file mode 100644index 0000000000..1c90197ae5--- /dev/null+++ b/client/src/components/media/IgnoreZonePainter.jsx@@ -0,0 +1,169 @@+import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';++// Ignore-zone (preserve-region) mask painter for the Image Cleaner diffusion+// step (issue #1763). The user paints WHITE regions over the source image to+// mark pixels the diffusion pass must NOT alter — comic dialog, faces, fine+// text that img2img garbles. The parent exports the painted mask as a 1-channel+// PNG Blob (white = preserve, black = diffuse) and sends it alongside the raw+// image bytes; the server composites the original pixels back into the white+// regions with a feathered edge.+//+// Two tools: freehand brush and rectangle. Clear wipes the mask; undo pops the+// last committed shape (brush stroke or rectangle) — the mask is a pure+// function of the committed shape list, so both are trivially correct via full+// redraw. Pointer events cover mouse, pen, and touch (touch-action: none so a+// drag doesn't scroll the page).+const IgnoreZonePainter = forwardRef(function IgnoreZonePainter(+ { imageSrc, tool = 'brush', brushSize = 40, onHasMaskChange },+ ref,+) {+ const canvasRef = useRef(null);+ const imgRef = useRef(null);+ const activePointerIdRef = useRef(null);+ const drawingRef = useRef(null); // in-progress shape (uncommitted)+ const [dims, setDims] = useState(null); // { w, h } natural pixels+ const [shapes, setShapes] = useState([]); // committed shapes+ const [inProgress, setInProgress] = useState(null);++ const handleImgLoad = useCallback(() => {+ const img = imgRef.current;+ if (!img) return;+ setDims({ w: img.naturalWidth || img.width || 1, h: img.naturalHeight || img.height || 1 });+ }, []);++ // Report whether any mask exists so the parent can gate the "apply mask" wiring+ // (an empty mask means "preserve nothing" — pointless to send).+ useEffect(() => {+ onHasMaskChange?.(shapes.length > 0);+ }, [shapes.length, onHasMaskChange]);++ // Full redraw from the committed shapes + the in-progress shape. The visible+ // canvas paints WHITE at 40% alpha over the image so the operator can see both+ // the preserved region AND the underlying pixels; the exported mask (below) is+ // opaque white-on-black so the server reads a clean binary mask.+ const paintShape = useCallback((ctx, shape, { alpha }) => {+ ctx.fillStyle = `rgba(255,255,255,${alpha})`;+ ctx.strokeStyle = `rgba(255,255,255,${alpha})`;+ if (shape.type === 'rect') {+ const x = Math.min(shape.x0, shape.x1);+ const y = Math.min(shape.y0, shape.y1);+ ctx.fillRect(x, y, Math.abs(shape.x1 - shape.x0), Math.abs(shape.y1 - shape.y0));+ } else {+ ctx.lineJoin = 'round';+ ctx.lineCap = 'round';+ ctx.lineWidth = shape.size;+ ctx.beginPath();+ shape.points.forEach((p, i) => (i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));+ // A single-point tap draws a dot.+ if (shape.points.length === 1) {+ ctx.arc(shape.points[0].x, shape.points[0].y, shape.size / 2, 0, Math.PI * 2);+ ctx.fill();+ } else {+ ctx.stroke();+ }+ }+ }, []);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || !dims) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ const all = inProgress ? [...shapes, inProgress] : shapes;+ all.forEach((s) => paintShape(ctx, s, { alpha: 0.4 }));+ }, [shapes, inProgress, dims, paintShape]);++ const toNatural = useCallback((e) => {+ const canvas = canvasRef.current;+ const rect = canvas.getBoundingClientRect();+ return {+ x: (e.clientX - rect.left) * (canvas.width / (rect.width || 1)),+ y: (e.clientY - rect.top) * (canvas.height / (rect.height || 1)),+ };+ }, []);++ const handlePointerDown = useCallback((e) => {+ if (!dims || activePointerIdRef.current !== null) return;+ e.preventDefault();+ activePointerIdRef.current = e.pointerId;+ canvasRef.current?.setPointerCapture?.(e.pointerId);+ const { x, y } = toNatural(e);+ const shape = tool === 'rect'+ ? { type: 'rect', x0: x, y0: y, x1: x, y1: y }+ : { type: 'brush', size: brushSize, points: [{ x, y }] };+ drawingRef.current = shape;+ setInProgress(shape);+ }, [dims, tool, brushSize, toNatural]);++ const handlePointerMove = useCallback((e) => {+ if (e.pointerId !== activePointerIdRef.current || !drawingRef.current) return;+ e.preventDefault();+ const { x, y } = toNatural(e);+ const cur = drawingRef.current;+ const next = cur.type === 'rect'+ ? { ...cur, x1: x, y1: y }+ : { ...cur, points: [...cur.points, { x, y }] };+ drawingRef.current = next;+ setInProgress(next);+ }, [toNatural]);++ const finishShape = useCallback((e) => {+ if (e && e.pointerId !== activePointerIdRef.current) return;+ activePointerIdRef.current = null;+ const shape = drawingRef.current;+ if (!shape) return;+ drawingRef.current = null;+ setInProgress(null);+ setShapes((prev) => [...prev, shape]);+ }, []);++ useImperativeHandle(ref, () => ({+ hasMask: shapes.length > 0,+ clear: () => setShapes([]),+ undo: () => setShapes((prev) => prev.slice(0, -1)),+ // Export the mask as an opaque 1-bit-ish PNG (white = preserve, black =+ // diffuse) at natural resolution. Returns a Promise<Blob|null>. The server+ // greyscales + resizes it to the cleaned image dims, so exact resolution+ // parity isn't required — but matching the source keeps the edge crisp.+ exportMaskBlob: () => new Promise((resolve) => {+ if (!dims || shapes.length === 0) return resolve(null);+ const out = document.createElement('canvas');+ out.width = dims.w;+ out.height = dims.h;+ const ctx = out.getContext('2d');+ if (!ctx) return resolve(null);+ ctx.fillStyle = '#000';+ ctx.fillRect(0, 0, dims.w, dims.h);+ shapes.forEach((s) => paintShape(ctx, s, { alpha: 1 }));+ out.toBlob((blob) => resolve(blob), 'image/png');+ }),+ }), [dims, shapes, paintShape]);++ return (+ <div className="relative inline-block max-w-full bg-port-bg rounded-lg overflow-hidden">+ <img+ ref={imgRef}+ src={imageSrc}+ onLoad={handleImgLoad}+ alt="Paint an ignore zone to preserve"+ className="block max-w-full h-auto select-none"+ draggable={false}+ />+ {dims && (+ <canvas+ ref={canvasRef}+ width={dims.w}+ height={dims.h}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={finishShape}+ onPointerCancel={finishShape}+ className="absolute inset-0 w-full h-full touch-none cursor-crosshair"+ />+ )}+ </div>+ );+});++export default IgnoreZonePainter;diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsxindex 91bf382152..bdc575366c 100644--- a/client/src/pages/ImageClean.jsx+++ b/client/src/pages/ImageClean.jsx@@ -1,7 +1,8 @@import { useState, useRef, useCallback, useEffect } from 'react';-import { Eraser, Upload, Download, ShieldCheck, Sparkles } from 'lucide-react';+import { Eraser, Upload, Download, ShieldCheck, Sparkles, Brush, Square, Undo2, X } from 'lucide-react';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';+import IgnoreZonePainter from '../components/media/IgnoreZonePainter';import * as api from '../services/api';import { formatBytes } from '../utils/formatters';@@ -31,6 +32,14 @@ export default function ImageClean() {// Opt-in pipeline steps. metadata defaults ON (lossless), denoise OFF (lossy),// diffusion OFF (lossy — CPU light pass, the only step that touches SynthID).const [steps, setSteps] = useState({ metadata: true, denoise: false, diffusion: false });+ // Ignore-zone (preserve-region) mask state — only relevant when the diffusion+ // step is on. `maskTool`/`brushSize`/`feather` drive the painter; `hasMask`+ // reflects whether any region is painted so the re-clean knows to send it.+ const [maskTool, setMaskTool] = useState('brush');+ const [brushSize, setBrushSize] = useState(40);+ const [feather, setFeather] = useState(3);+ const [hasMask, setHasMask] = useState(false);+ const painterRef = useRef(null);const fileInputRef = useRef(null);const requestIdRef = useRef(0);const previewUrlRef = useRef(null);@@ -59,6 +68,16 @@ export default function ImageClean() {denoise: selectedSteps.denoise,diffusion: selectedSteps.diffusion ? 'light' : 'off',};+ // 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) {+ const maskBlob = await painterRef.current.exportMaskBlob();+ if (maskBlob) {+ payload.mask = maskBlob;+ payload.feather = feather;+ }+ }const cleaned = await api.cleanImage(file, payload).catch((err) => {toast.error(err.message || 'Failed to clean image');return null;@@ -75,7 +94,7 @@ export default function ImageClean() {const report = cleaned.report || {};setResult({ ...report, mimeType: cleaned.mimeType, objectUrl });toast.success(report.c2paStripped ? 'C2PA chunk removed' : 'Image cleaned');- }, []);+ }, [feather]);const handleFile = async (file) => {if (!file) return;@@ -280,6 +299,93 @@ export default function ImageClean() {</div></div>+ {/* Ignore-zone (preserve-region) mask painter — only when diffusion is on */}+ {steps.diffusion && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">+ <div className="flex items-center gap-2">+ <Brush size={16} className="text-port-accent" />+ <span className="text-sm font-medium text-white">Ignore zone (preserve region)</span>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <button+ onClick={() => setMaskTool('brush')}+ className={`px-2 py-1 rounded text-xs flex items-center gap-1 border transition-colors ${maskTool === 'brush' ? 'border-port-accent text-port-accent bg-port-accent/10' : 'border-port-border text-gray-400 hover:text-white'}`}+ >+ <Brush size={12} /> Brush+ </button>+ <button+ onClick={() => setMaskTool('rect')}+ className={`px-2 py-1 rounded text-xs flex items-center gap-1 border transition-colors ${maskTool === 'rect' ? 'border-port-accent text-port-accent bg-port-accent/10' : 'border-port-border text-gray-400 hover:text-white'}`}+ >+ <Square size={12} /> Rectangle+ </button>+ <button+ onClick={() => { painterRef.current?.undo(); }}+ 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"+ >+ <Undo2 size={12} /> Undo+ </button>+ <button+ onClick={() => { painterRef.current?.clear(); if (original?.file) runClean(original.file, steps); }}+ 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+ </button>+ </div>+ </div>+ <p className="text-xs text-gray-500">+ Paint the regions the diffusion pass should NOT alter (comic dialog, faces, fine text).+ After the pass, the original pixels are composited back into these regions with a feathered edge.+ <span className="text-port-warning"> Heads up:</span> a preserved region keeps its original SynthID locally — a deliberate per-region quality-vs-disruption tradeoff.+ </p>+ <div className="flex items-center justify-center bg-port-bg/50 rounded p-2">+ <IgnoreZonePainter+ ref={painterRef}+ imageSrc={original.previewUrl}+ tool={maskTool}+ brushSize={brushSize}+ onHasMaskChange={setHasMask}+ />+ </div>+ <div className="flex flex-col sm:flex-row sm:items-center gap-4">+ <div className="flex items-center gap-2 flex-1">+ <label htmlFor="brush-size" className="text-xs text-gray-500 whitespace-nowrap">Brush size</label>+ <input+ id="brush-size"+ type="range"+ min="8"+ max="200"+ value={brushSize}+ onChange={(e) => setBrushSize(Number(e.target.value))}+ className="flex-1 accent-port-accent"+ />+ <span className="text-xs text-gray-400 w-10 text-right">{brushSize}px</span>+ </div>+ <div className="flex items-center gap-2 flex-1">+ <label htmlFor="feather" className="text-xs text-gray-500 whitespace-nowrap">Feather</label>+ <input+ id="feather"+ type="range"+ min="0"+ max="50"+ value={feather}+ onChange={(e) => setFeather(Number(e.target.value))}+ className="flex-1 accent-port-accent"+ />+ <span className="text-xs text-gray-400 w-10 text-right">{feather}px</span>+ </div>+ <button+ onClick={() => { if (original?.file) runClean(original.file, steps); }}+ disabled={busy || !hasMask}+ className="px-3 py-1.5 rounded text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-40 disabled:cursor-not-allowed text-white transition-colors whitespace-nowrap"+ >+ Apply mask+ </button>+ </div>+ </div>+ )}+<div className="grid grid-cols-1 md:grid-cols-2 gap-4"><div className="bg-port-card border border-port-border rounded-lg overflow-hidden"><div className="px-4 py-2 border-b border-port-border flex items-center justify-between">diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.jsindex 6e579b9c55..f9fca420dc 100644--- a/client/src/services/apiMedia.js+++ b/client/src/services/apiMedia.js@@ -34,15 +34,38 @@ export const deleteAllUploads = (options = {}) => request('/uploads?confirm=true// custom header. Returns `{ blob, mimeType, report }`. Throws on failure so the// page's own catch can toast (no silent flag needed — this never double-toasts).//-// `steps` is `{ metadata?: boolean, denoise?: boolean, diffusion?: 'off'|'light'|'gpu' }`.+// `steps` is `{ metadata?: boolean, denoise?: boolean, diffusion?: 'off'|'light'|'gpu',+// mask?: Blob, feather?: number }`.// metadata/denoise default on the server (metadata ON, denoise OFF); diffusion// defaults to 'off'. 'light' runs the CPU spatial SynthID-disruption pass;// 'gpu' (the FLUX round-trip) is not yet wired here and returns a 501.+//+// When a `mask` Blob (a painted preserve-region PNG) is supplied AND a diffusion+// step runs, the body is framed as an ignore-zone envelope+// `<uint32 BE maskLen><mask bytes><image bytes>` (no multipart dependency) and+// `?mask=1&feather=<px>` is added. The server composites the ORIGINAL pixels+// back into the masked regions (feathered edge) over the diffused result.export const cleanImage = async (file, steps = {}) => {const params = new URLSearchParams();if (typeof steps.metadata === 'boolean') params.set('metadata', steps.metadata ? '1' : '0');if (typeof steps.denoise === 'boolean') params.set('denoise', steps.denoise ? '1' : '0');if (typeof steps.diffusion === 'string' && steps.diffusion !== 'off') params.set('diffusion', steps.diffusion);++ // Build the request body. With a mask + a diffusion step, prefix the raw image+ // bytes with the length-framed mask; otherwise send the file directly.+ let body = file;+ const diffusionOn = typeof steps.diffusion === 'string' && steps.diffusion !== 'off';+ if (steps.mask && diffusionOn) {+ const [maskBytes, imageBytes] = await Promise.all([+ steps.mask.arrayBuffer(),+ file.arrayBuffer(),+ ]);+ const lenPrefix = new Uint8Array(4);+ new DataView(lenPrefix.buffer).setUint32(0, maskBytes.byteLength, false);+ body = new Blob([lenPrefix, maskBytes, imageBytes]);+ params.set('mask', '1');+ if (typeof steps.feather === 'number') params.set('feather', String(steps.feather));+ }const qs = params.toString();// Always send application/octet-stream rather than the browser's reported@@ -55,7 +78,7 @@ export const cleanImage = async (file, steps = {}) => {const response = await fetch(`${API_BASE}/image-clean${qs ? `?${qs}` : ''}`, {method: 'POST',headers: { 'Content-Type': 'application/octet-stream' },- body: file,+ body,}).catch(() => null);if (!response) throw new Error('Server unreachable — check your connection and try again');diff --git a/server/lib/README.md b/server/lib/README.mdindex a51513cf5d..a53798c903 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -120,7 +120,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |-| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |+| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). || `multipart.js` | Streaming multipart/form-data parser. |diff --git a/server/lib/imageClean.js b/server/lib/imageClean.jsindex 32650e6fb9..714846401f 100644--- a/server/lib/imageClean.js+++ b/server/lib/imageClean.js@@ -206,6 +206,83 @@ const MIME_TYPES = {webp: 'image/webp',};+// Feather (Gaussian blur sigma, px) applied to the preserve-region mask edge so+// the composited boundary is soft rather than a hard cut. Bounded: 0 disables+// feathering (hard edge); sharp rejects a sigma below ~0.3, and a huge sigma on+// a small mask just washes the whole mask grey — 50px is a generous ceiling.+export const IGNORE_ZONE_FEATHER_DEFAULT = 3;+const IGNORE_ZONE_FEATHER_MAX = 50;++/**+ * Ignore-zone (preserve-region) compositing — pure sharp round-trip, no runner+ * or GPU dependency. After a lossy SynthID-disruption pass (CPU light or GPU+ * FLUX) redraws the whole frame — garbling comic dialog, faces, and fine text —+ * this composites the ORIGINAL pixels back into the user-painted mask regions+ * with a feathered (Gaussian-blurred) edge so the boundary is soft.+ *+ * `base` is the diffused/disrupted buffer; `original` is the pre-diffusion image+ * whose pixels are preserved inside the mask; `mask` is an image where WHITE+ * (255) marks preserve-original regions and BLACK (0) keeps the diffused result.+ * The mask is greyscaled and resized (fit: fill) to the base's dimensions, so a+ * client can paint it at any convenient resolution.+ *+ * Honest tradeoff (surfaced in the UI): SynthID is spatially distributed, so a+ * region preserved verbatim keeps its ORIGINAL watermark locally — the mask is a+ * deliberate per-region quality-vs-disruption choice.+ *+ * Returns `{ data, width, height }` (always PNG, to carry the alpha-accurate+ * composite losslessly), or null on any decode failure so the caller can fall+ * back to the un-composited diffused buffer instead of failing the request.+ * `sharpImpl` is injectable for tests.+ */+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);+ const w = Math.round(Number(meta?.width));+ const h = Math.round(Number(meta?.height));+ if (!(w > 0) || !(h > 0)) return null;++ // Clamp the feather sigma into sharp's valid range. A 0 (or sub-threshold)+ // request means "hard edge" — skip the blur entirely rather than let sharp+ // throw on an out-of-range sigma.+ const sigma = Math.min(IGNORE_ZONE_FEATHER_MAX, Math.max(0, Number(feather) || 0));++ 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)+ .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)+ .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];++ const overlay = await sharpImpl(originalRgba, { raw: { width: w, height: h, channels: 4 } })+ .png()+ .toBuffer();++ const data = await sharpImpl(base)+ .png()+ .composite([{ input: overlay, blend: 'over' }])+ .png({ compressionLevel: 6 })+ .toBuffer();+ return { data, width: w, height: h };+ };++ return run().catch(() => null);+}+function applyDenoise(pipeline) {return pipeline.median(3).sharpen();}diff --git a/server/lib/imageClean.test.js b/server/lib/imageClean.test.jsindex b0422a8c8a..d0c4a26c83 100644--- a/server/lib/imageClean.test.js+++ b/server/lib/imageClean.test.js@@ -6,6 +6,7 @@ import { tmpdir } from 'os';import sharp from 'sharp';import {autoCleanGeneratedImage, stripPngC2PAChunk, stripPngMetadataChunks, cleanImageBuffer,+ compositeIgnoreZone,} from './imageClean.js';let sandbox;@@ -397,3 +398,81 @@ describe('cleanImageBuffer (composable steps)', () => {expect(result.width).toBe(32);});});++describe('compositeIgnoreZone', () => {+ // A solid-red 16×16 "original" and a solid-blue 16×16 "diffused" base, plus a+ // mask whose LEFT half is white (preserve original) and right half black (keep+ // diffused). After compositing, the left half should read red (original) and+ // the right half blue (diffused). Feather=0 gives a hard edge so the core of+ // each half is unambiguous.+ const W = 16;+ const H = 16;+ let redOriginal;+ let blueBase;+ let halfMask;++ beforeAll(async () => {+ redOriginal = await sharp({ create: { width: W, height: H, channels: 3, background: { r: 255, g: 0, b: 0 } } }).png().toBuffer();+ blueBase = await sharp({ create: { width: W, height: H, channels: 3, background: { r: 0, g: 0, b: 255 } } }).png().toBuffer();+ // Left half white (preserve), right half black (diffused).+ const maskRaw = Buffer.alloc(W * H, 0);+ for (let y = 0; y < H; y += 1) {+ for (let x = 0; x < W; x += 1) {+ if (x < W / 2) maskRaw[y * W + x] = 255;+ }+ }+ halfMask = await sharp(maskRaw, { raw: { width: W, height: H, channels: 1 } }).png().toBuffer();+ });++ const pixelAt = async (buf, x, y) => {+ const { data } = await sharp(buf).removeAlpha().raw().toBuffer({ resolveWithObject: true });+ const idx = (y * W + x) * 3;+ return { r: data[idx], g: data[idx + 1], b: data[idx + 2] };+ };++ it('restores original pixels inside the mask and keeps diffused pixels outside (hard edge)', async () => {+ const out = await compositeIgnoreZone(blueBase, redOriginal, halfMask, { feather: 0 });+ expect(out).toBeTruthy();+ expect(out.width).toBe(W);+ expect(out.height).toBe(H);+ // Masked (left) core → original red.+ const left = await pixelAt(out.data, 2, 8);+ expect(left.r).toBeGreaterThan(200);+ expect(left.b).toBeLessThan(60);+ // Unmasked (right) core → diffused blue.+ const right = await pixelAt(out.data, 14, 8);+ expect(right.b).toBeGreaterThan(200);+ expect(right.r).toBeLessThan(60);+ });++ it('feathers the boundary into a blended zone rather than a hard cut', async () => {+ const out = await compositeIgnoreZone(blueBase, redOriginal, halfMask, { feather: 4 });+ expect(out).toBeTruthy();+ // At the seam (x≈8) the feathered alpha blends red over blue → a purple-ish+ // pixel with BOTH channels present, unlike either solid core.+ const seam = await pixelAt(out.data, 8, 8);+ expect(seam.r).toBeGreaterThan(20);+ expect(seam.b).toBeGreaterThan(20);+ });++ it('accepts a mask painted at a different resolution than the base', async () => {+ // Paint the same left-half mask at 2× the base resolution — it must resize+ // (fit: fill) to the base dims, not throw.+ const bigMaskRaw = Buffer.alloc(W * 2 * H * 2, 0);+ for (let y = 0; y < H * 2; y += 1) {+ for (let x = 0; x < W * 2; x += 1) {+ if (x < W) bigMaskRaw[y * W * 2 + x] = 255;+ }+ }+ const bigMask = await sharp(bigMaskRaw, { raw: { width: W * 2, height: H * 2, channels: 1 } }).png().toBuffer();+ const out = await compositeIgnoreZone(blueBase, redOriginal, bigMask, { feather: 0 });+ expect(out).toBeTruthy();+ const left = await pixelAt(out.data, 2, 8);+ expect(left.r).toBeGreaterThan(200);+ });++ it('returns null on a non-buffer or undecodable input instead of throwing', async () => {+ expect(await compositeIgnoreZone(null, redOriginal, halfMask)).toBeNull();+ expect(await compositeIgnoreZone(blueBase, redOriginal, Buffer.from('not an image'))).toBeNull();+ });+});diff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex a6d3a9a4a0..5430fc7f12 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -12,7 +12,7 @@ import { Router, raw } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import { cleanImageBuffer, CLEAN_LEVELS } from '../lib/imageClean.js';+import { cleanImageBuffer, CLEAN_LEVELS, compositeIgnoreZone, IGNORE_ZONE_FEATHER_DEFAULT } from '../lib/imageClean.js';import { applyLightRegen, computePixelDelta } from '../services/imageGen/regen.js';const router = Router();@@ -53,12 +53,41 @@ const diffusionMode = z.preprocess();// Pipeline steps ride in the query string, not the body (the body is the image).+// `mask=1` signals an ignore-zone preserve-region envelope in the body (see the+// length-prefixed decode below); `feather` is the soft-boundary blur sigma (px)+// clamped in the lib. The mask only has any effect when a diffusion step runs —+// it composites the ORIGINAL pixels back over the diffused result.const cleanQuerySchema = z.object({metadata: queryFlag(true),denoise: queryFlag(false),diffusion: diffusionMode,+ mask: queryFlag(false),+ feather: z.preprocess(+ (v) => (v === undefined || v === '' ? IGNORE_ZONE_FEATHER_DEFAULT : Number(v)),+ z.number().min(0).max(50),+ ),});+// Decode the optional ignore-zone envelope. When `?mask=1`, the body is+// `<uint32 BE maskLen><mask PNG bytes><image bytes>` — a no-dependency framing+// that keeps the whole payload inside express.raw() without pulling in+// multer/busboy for a second multipart field. Returns `{ image, mask }` (mask+// null when absent/malformed — the pipeline just skips the composite, never+// 500s). The mask is small (a 1-channel PNG), so the 4-byte length prefix is+// plenty. Guards against a length that overruns the buffer.+function splitMaskEnvelope(body, hasMask) {+ if (!Buffer.isBuffer(body) || body.length === 0) return { image: null, mask: null };+ if (!hasMask) return { image: body, mask: null };+ if (body.length < 4) return { image: body, mask: null };+ const maskLen = body.readUInt32BE(0);+ const maskEnd = 4 + maskLen;+ // A length that doesn't leave any image bytes (or overruns) is malformed —+ // fall back to treating the whole body as the image so a bad frame degrades to+ // "no mask" rather than a hard failure.+ if (maskLen <= 0 || maskEnd >= body.length) return { image: body, mask: null };+ return { image: body.subarray(maskEnd), mask: body.subarray(4, maskEnd) };+}+// 256 MiB raw-byte ceiling — the transport is the only (generous) size bound now// that base64 inflation is gone. The decompression-bomb guard (MAX_PIXELS) in// the lib still protects the process regardless of byte size.@@ -73,7 +102,7 @@ router.post('/',raw({ type: RAW_TYPES, limit: RAW_LIMIT }),asyncHandler(async (req, res) => {- const { metadata, denoise, diffusion } = validateRequest(cleanQuerySchema, req.query);+ const { metadata, denoise, diffusion, mask: hasMask, feather } = validateRequest(cleanQuerySchema, req.query);// The GPU FLUX round-trip needs the non-gallery render seam factored out of// the lightbox `/regenerate` flow (async job queue + media-job progress),@@ -86,7 +115,8 @@ router.post(});}- const buffer = Buffer.isBuffer(req.body) ? req.body : null;+ const rawBody = Buffer.isBuffer(req.body) ? req.body : null;+ const { image: buffer, mask: maskBuffer } = splitMaskEnvelope(rawBody, hasMask);if (!buffer || buffer.length === 0) {throw new ServerError('Request body must be raw image bytes', {status: 400,@@ -94,6 +124,11 @@ router.post(});}+ // The original bytes are captured BEFORE any cleaning so the ignore-zone+ // composite can restore true source pixels into the preserved regions (the+ // whole point is to undo the diffusion inside the mask, not re-diffuse it).+ const originalBuffer = buffer;+const result = await cleanImageBuffer(buffer, { metadata, denoise });// Diffusion (CPU light pass) runs LAST in the pipeline order (metadata →@@ -139,6 +174,37 @@ router.post(: 'CPU light pass - best-effort SynthID disruption; does not guarantee removal',...(delta ? { pixelDeltaPct: delta.pixelDeltaPct, psnr: delta.psnr } : {}),});++ // Ignore-zone (preserve-region) compositing runs LAST, only after a+ // diffusion pass has actually redrawn the frame. It restores the ORIGINAL+ // pixels into the user-painted mask (feathered edge) so comic dialog /+ // faces / fine text the diffusion garbled are preserved — a deliberate+ // per-region quality-vs-disruption choice (those regions keep their local+ // SynthID). A missing/malformed mask or a decode failure degrades to the+ // un-composited diffused bytes rather than failing the request.+ if (maskBuffer) {+ const composited = await compositeIgnoreZone(outData, originalBuffer, maskBuffer, { feather });+ if (composited) {+ outData = composited.data;+ outFormat = 'png';+ outMime = 'image/png';+ outWidth = composited.width;+ outHeight = composited.height;+ steps.push({+ step: 'ignore-zone',+ status: 'applied',+ lossless: false,+ detail: `preserve-region composite (feather ${feather}px) - masked pixels keep their original SynthID`,+ });+ } else {+ steps.push({+ step: 'ignore-zone',+ status: 'noop',+ lossless: false,+ detail: 'mask could not be applied (decode failed) - returned the un-preserved diffused result',+ });+ }+ }}const report = {diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.jsindex 021ced6818..f703816310 100644--- a/server/routes/imageClean.test.js+++ b/server/routes/imageClean.test.js@@ -210,6 +210,62 @@ describe('POST /api/image-clean (raw transport)', () => {expect(res.body.code).toBe('VALIDATION_ERROR');});+ it('composites an ignore-zone mask over the diffused result when ?diffusion=light&mask=1', async () => {+ // Build a left-half-white mask sized to the large fixture, then frame the+ // body as <uint32 maskLen><mask><image>. The response should carry an+ // ignore-zone step and stay a PNG.+ const meta = await sharp(largePng).metadata();+ const mw = meta.width;+ const mh = meta.height;+ const maskRaw = Buffer.alloc(mw * mh, 0);+ for (let y = 0; y < mh; y += 1) {+ for (let x = 0; x < mw; x += 1) if (x < mw / 2) maskRaw[y * mw + x] = 255;+ }+ const maskPng = await sharp(maskRaw, { raw: { width: mw, height: mh, channels: 1 } }).png().toBuffer();+ const lenPrefix = Buffer.alloc(4);+ lenPrefix.writeUInt32BE(maskPng.length, 0);+ const envelope = Buffer.concat([lenPrefix, maskPng, largePng]);++ const res = await postImage('?diffusion=light&mask=1&feather=2', envelope);+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toBe('image/png');+ const report = reportOf(res);+ const zone = report.steps.find((s) => s.step === 'ignore-zone');+ expect(zone).toBeTruthy();+ expect(zone.status).toBe('applied');+ expect(report.steps.map((s) => s.step)).toContain('diffusion');+ });++ it('ignores the mask envelope when no diffusion step runs', async () => {+ // mask=1 but diffusion=off → the mask is decoded off the body but never+ // composited (nothing to preserve against). The image half of the envelope+ // must still clean cleanly.+ const maskRaw = Buffer.alloc(4 * 4, 255);+ const maskPng = await sharp(maskRaw, { raw: { width: 4, height: 4, channels: 1 } }).png().toBuffer();+ const lenPrefix = Buffer.alloc(4);+ lenPrefix.writeUInt32BE(maskPng.length, 0);+ const envelope = Buffer.concat([lenPrefix, maskPng, pngFixture]);++ const res = await postImage('?mask=1', envelope);+ expect(res.status).toBe(200);+ const report = reportOf(res);+ expect(report.steps.some((s) => s.step === 'ignore-zone')).toBe(false);+ expect(report.format).toBe('png');+ expect(report.width).toBe(4);+ });++ it('degrades to no-mask when the envelope length prefix is malformed', async () => {+ // A length that overruns the buffer → splitMaskEnvelope treats the whole+ // body as the image, so a plain PNG (no real envelope) still cleans.+ const badPrefix = Buffer.alloc(4);+ badPrefix.writeUInt32BE(0xffffffff, 0);+ const envelope = Buffer.concat([badPrefix, pngFixture]);+ const res = await postImage('?mask=1', envelope);+ // The body now starts with a bogus prefix, so it's not a valid PNG → the+ // sniffer rejects it as unsupported (proves we didn't 500 on the bad frame).+ expect([200, 400]).toContain(res.status);+ });+it('auto-orients images via EXIF Orientation tag', async () => {// 4×8 JPEG re-emitted with EXIF Orientation=6 (rotate 90° CW). The metadata// re-encode path bakes in the rotation → output is 8×4 (dims swapped).