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

Strengthen SynthID regen: universal resize-squeeze, CPU fallback, fidelity metric, adaptive strength

[._.]/ Adam Eivy3dfbf08e5212
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9da9181d96..ad7059b623 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -20,6 +20,8 @@
## Changed
+- **[issue-912] Stronger, more compatible SynthID regeneration** — The gallery "Regenerate" pass (which overwrites Google's invisible SynthID watermark by round-tripping the image through a local FLUX model) gets four upgrades drawn from a survey of public watermark-removal tools. (1) Every regen now also nudges the render resolution down-and-back-up, not just oversized images — SynthID's invisible signal is keyed to resolution, so this resolution shift disrupts it for free on top of the model round-trip. (2) A new **Light (CPU)** option appears even on machines without a local FLUX runner: a fast, GPU-free spatial pass that disrupts the watermark directly in the pixels — clearly labeled as less reliable than the full round-trip, so installs that previously had no defeat path at all now have a best-effort one. (3) Each regenerated image now records and shows **how much it actually changed** (a percentage and PSNR in the image's lineage row), so you can see at a glance whether a pass stayed faithful or drifted — and it surfaces silent failures that used to be invisible. (4) The default denoise strength now adapts to the source: watermark-bearing generators (gpt-image / Gemini / Imagen) keep the conservative known-good setting, while your own local renders use a lighter, more faithful default. The original image is always kept; you can still tune strength and prompt by hand.
+
- **[issue-878] City photo mode freezes the scene for a clean shot** — When you enter photo mode, the city now holds still once the camera settles into its framing — particles, data streams, weather, and landmark pulses pause — so your postcard captures a deliberate, motion-free frame instead of whatever the animation happened to be doing. The camera still flies smoothly to each preset (and re-animates when you switch shots); the scene only freezes once it arrives. Leaving photo mode resumes the live, always-moving city.
- **City night sky, horizon, and flight controls** — Night is now a moonlit cyber-night rather than a near-black dusk: a galaxy starfield wraps the dome, distant mountains and themed terrain fill the horizon, and the sky dome cross-dissolves with daylight so the stars fade out as day comes up. Buildings gain lit floor bands and brighter facades so dark towers stay readable, and the AI Core spire gets light rings, an additive apex glow, and a point light. First-person exploration is now free-look flight: WASD moves, Q/E descend/ascend, Shift sprints, and the interact key moved to F (E is now "up"); you can fly up and over the city, with building collision disabled above rooftop height. The galaxy texture only loads at night. No change to the daytime look.
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 1570ebf7a9..60d91fff00 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -54,8 +54,12 @@ function describeCleanedLineage(item) {
// SynthID-defeat regen reuses `cleanedFrom` for grouping but is a generative
// round-trip, not a clean — describe it honestly (issue #912).
if (item.regenerated && item.cleanedFrom) {
- const pct = typeof item.regenStrength === 'number' ? ` · ${Math.round(item.regenStrength * 100)}% denoise` : '';
- return `Regenerated from ${item.cleanedFrom}${pct}`;
+ const denoise = typeof item.regenStrength === 'number' ? ` · ${Math.round(item.regenStrength * 100)}% denoise` : '';
+ // Realized fidelity (how much the pixels actually changed) — stamped by the
+ // server so the lineage row reflects the true delta, not just the request.
+ const fidelity = typeof item.regenPixelDeltaPct === 'number' ? ` · ${item.regenPixelDeltaPct}% changed` : '';
+ const method = item.regenMethod === 'light-spatial' ? ' (light)' : '';
+ return `Regenerated${method} from ${item.cleanedFrom}${denoise}${fidelity}`;
}
if (item.cleanedFrom) {
return `${item.cleanLevel ? `Cleaned (${item.cleanLevel}) ` : 'Cleaned '}from ${item.cleanedFrom}`;
@@ -374,11 +378,15 @@ function SettingsPane({
const asideClasses = 'md:w-80 lg:w-96 shrink-0 flex flex-col border-t md:border-t-0 md:border-l border-port-border max-h-[40vh] md:max-h-[92vh]';
const [cleaning, setCleaning] = useState(false);
const [regenerating, setRegenerating] = useState(false);
+ const [lightRegenerating, setLightRegenerating] = useState(false);
// Regen controls: the button toggles an inline panel (strength slider +
// optional prompt) so a watermark-defeat pass can be tuned without leaving the
// lightbox. Slider bounds come from the server (`regenBounds`) so the floor
// stays in lock-step with route validation.
const { strengthMin: regenMin = 0.02, strengthMax: regenMax = 0.6, strengthDefault: regenDefault = 0.25 } = regenBounds || {};
+ // CPU-only spatial fallback — always offered (sharp is server-side), so an
+ // install without a FLUX runner can still attempt a (less reliable) pass.
+ const regenLightAvailable = !!regenBounds?.lightAvailable;
const [regenOpen, setRegenOpen] = useState(false);
const [regenStrength, setRegenStrength] = useState(regenDefault);
const [regenPrompt, setRegenPrompt] = useState('');
@@ -680,14 +688,40 @@ function SettingsPane({
</div>
<button
type="button"
- disabled={regenerating}
+ disabled={regenerating || lightRegenerating}
onClick={runBusyAction(regenerating, setRegenerating, (it) => onRegenerate(it, { strength: regenStrength, prompt: regenPrompt.trim() || undefined }))}
className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-accent text-white hover:opacity-90 rounded disabled:opacity-50 disabled:cursor-not-allowed"
>
<Wand2 className="w-3.5 h-3.5" /> {regenerating ? 'Queuing…' : `Regenerate at ${regenStrength.toFixed(2)}`}
</button>
+ {regenLightAvailable && (
+ <button
+ type="button"
+ disabled={regenerating || lightRegenerating}
+ onClick={runBusyAction(lightRegenerating, setLightRegenerating, (it) => onRegenerate(it, { method: 'light' }))}
+ title="CPU-only spatial pass (no GPU). Faster, but less reliable than the FLUX round-trip."
+ className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-border hover:bg-port-border/70 text-white rounded disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Wand2 className="w-3.5 h-3.5" /> {lightRegenerating ? 'Processing…' : 'Light (CPU, less reliable)'}
+ </button>
+ )}
</div>
)}
+ {/* No FLUX runner installed, but the CPU spatial pass is always available
+ — offer it standalone so these installs aren't left with no SynthID
+ defeat path at all. Honestly labeled as less reliable. */}
+ {!isVideo && onRegenerate && !regenAvailable && regenLightAvailable && (
+ <button
+ type="button"
+ disabled={lightRegenerating}
+ onClick={runBusyAction(lightRegenerating, setLightRegenerating, (it) => onRegenerate(it, { method: 'light' }))}
+ title="CPU-only spatial pass to disrupt SynthID watermarking (no GPU required). Less reliable than a FLUX round-trip; install a local FLUX runner for the stronger pass. Creates a new variant; the original is kept."
+ aria-label="Light CPU regen to disrupt SynthID watermark"
+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs text-white hover:opacity-90 rounded bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ <Wand2 className="w-3.5 h-3.5" /> {lightRegenerating ? 'Processing…' : 'Regen (light)'}
+ </button>
+ )}
{isVideo && onContinue && (
<button
type="button"
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index d567ad2cff..240b4276cf 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -839,6 +839,18 @@ export default function ImageGen() {
// pollQueue). Bump pendingQueued so the queue indicator + 4s poll engage.
const handleRegenerate = async (img, opts = {}) => {
if (!img?.filename) throw new Error('Missing filename');
+ // CPU-only light path is synchronous (like Clean): it returns the new
+ // variant directly, so insert it into the gallery rather than waiting on
+ // the render queue.
+ if (opts.method === 'light') {
+ const variant = await regenerateGalleryImage(img.filename, { method: 'light' }).catch((err) => {
+ toast.error(err.message || 'Failed to run light regen');
+ throw err;
+ });
+ setGallery((g) => [variant, ...g.filter((x) => x.filename !== variant.filename)]);
+ toast.success(`Light regen → ${variant.filename}`);
+ return;
+ }
await regenerateGalleryImage(img.filename, { strength: opts.strength, prompt: opts.prompt }).catch((err) => {
toast.error(err.message || 'Failed to start regeneration');
throw err;
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 296da771f8..ddc0222c03 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -30,13 +30,16 @@ export const cleanGalleryImage = (filename) => request(`/image-gen/${encodeURICo
// of a gallery image; returns the queue ack ({ jobId, position, ... }) — the
// finished render lands in the gallery via the normal queue-completion refresh.
// `silent` so the lightbox owns its own error toast (single-layer rule).
-export const regenerateGalleryImage = (filename, { strength, steps, prompt } = {}) =>
+// `method: 'light'` runs the CPU-only spatial pass (synchronous — returns the
+// new variant directly, not a queue ack), for installs without a FLUX runner.
+export const regenerateGalleryImage = (filename, { strength, steps, prompt, method } = {}) =>
request(`/image-gen/${encodeURIComponent(filename)}/regenerate`, {
method: 'POST',
body: JSON.stringify({
...(strength != null ? { strength } : {}),
...(steps != null ? { steps } : {}),
...(prompt != null ? { prompt } : {}),
+ ...(method != null ? { method } : {}),
}),
silent: true,
});
diff --git a/docs/plans/2026-06-05-synthid-removal-eval.md b/docs/plans/2026-06-05-synthid-removal-eval.md
new file mode 100644
index 0000000000..3022f13fd6
--- /dev/null
+++ b/docs/plans/2026-06-05-synthid-removal-eval.md
@@ -0,0 +1,55 @@
+# SynthID-removal: competitive evaluation + regen improvements
+
+**Date:** 2026-06-05 · **Area:** `server/services/imageGen/regen.js`, `local.js`, `routes/imageGen.js`, `MediaLightbox.jsx` · **Issue lineage:** #912, #970
+
+Design record for an evaluation of five public AI-watermark-removal repos against PortOS's
+**mflux/FLUX img2img reprocessing** regen, and the improvements that evaluation produced.
+
+## How PortOS regen works (baseline)
+
+`server/services/imageGen/regen.js` round-trips a gallery image through a local FLUX model via
+img2img at low denoise (0.25, **empty prompt**) so the VAE resample overwrites SynthID's per-pixel
+signal with minimal visible change. Large sources are clamped to a ~2MP FLUX attention budget and
+upscaled back. The plain `imageClean.js` (C2PA strip + median/sharpen) deliberately does **not**
+touch SynthID — regen is the honest defeat path. It is hardware-gated on a local FLUX runner.
+
+## The five repos evaluated
+
+| Repo | Method | Takeaway vs PortOS |
+|---|---|---|
+| **mertizci/noai-watermark** | SD img2img + optional CtrlRegen (Canny/IP-Adapter), tiling | Same core (VAE roundtrip); adds ControlNet structure guidance + tiling. |
+| **wiltodelta/remove-ai-watermarks** | Diffusion w/ vendor-adaptive strength (OpenAI 0.10 / Gemini 0.15) + reverse-alpha for *visible* marks + metadata strip | Vendor-adaptive strength; visible-watermark removal; most feature-complete. |
+| **samukingx/SynthIDBye** | LSB destruction + noise (browser) | **Cautionary tale** — SynthID is not LSB; misadvertised/ineffective. Validates our VAE approach. |
+| **00quebec/Synthid-Bypass** | ComfyUI: low-denoise (0.1) Qwen redraw + Canny ControlNet + per-face refine; resolution-aware adaptive denoise | Confirms low-denoise roundtrip works; adds adaptive denoise. |
+| **aloshdenny/reverse-SynthID** | 7-stage spectral+spatial: VAE roundtrip → elastic deform → affine → **resize-squeeze** → color nudge → FFT phase subtraction → recompress; PSNR-gated | Most sophisticated. **SynthID carriers are resolution-dependent** — resize-squeeze is a deliberate, CPU-cheap defeat stage. |
+
+**Key learnings:** (1) SynthID's invisible carriers move with resolution, so a downscale→upscale
+resize-squeeze disrupts them for free; (2) layered cheap *spatial* stages (no GPU) meaningfully add
+to a single VAE vector; (3) tune denoise by generator, not a flat value; (4) serious tools measure
+fidelity (PSNR-gating) and verify against a detector; (5) LSB-only is a dead end.
+
+## What shipped
+
+1. **Universal resize-squeeze** (`clampRegenDimensions`, `REGEN_SQUEEZE_FACTOR`): the
+ downscale→upscale that previously fired only for >2MP images now applies to *every* regen, so
+ each pass gets a resolution-shift disruption vector layered on the VAE roundtrip.
+2. **CPU-only light fallback** (`applyLightRegen` + `runLightRegen` route, `method: 'light'`): a
+ sharp-only spatial stack (resize-squeeze + micro color/contrast nudge + median/sharpen) for
+ installs with no FLUX runner — which previously had no SynthID defeat path at all. Honestly
+ labeled as less reliable (`regenMethod: 'light-spatial'` sidecar stamp, UI copy says so).
+3. **Output fidelity metric** (`computePixelDelta`): source-vs-delivered pixel delta % + PSNR
+ stamped on every regen sidecar (`regenPixelDeltaPct`/`regenPsnr`) and surfaced in the lightbox
+ lineage row — catches the mflux strength-0.0 footgun, silent txt2img fallbacks, over-mutation.
+4. **Provider-adaptive strength default** (`resolveRegenStrengthDefault`): SynthID-bearing sources
+ (codex/gpt-image, gemini/imagen/nano-banana) keep the conservative known-good 0.25; local FLUX
+ sources (no Google watermark) default to a lighter 0.15. Explicit `strength` override unchanged.
+
+## Considered, NOT pursued
+
+- **ControlNet/Canny structure guidance** — lets others push higher denoise; we deliberately keep
+ denoise *low* (simpler, reuses the GPU lane, no heavy deps). Right trade-off for minimal mutation.
+- **Visible-watermark removal** (Gemini sparkle, Doubao/Jimeng text, Samsung) via reverse-alpha +
+ NCC + inpainting — a real compatibility gap, but a substantial separate feature. → future `PLAN.md`.
+- **Automated detector verification loop** — Google's SynthID Detector is limited-access, no broad
+ public API; full automation isn't feasible today. The manual sweep-down workflow stands; the new
+ fidelity metric gives an objective in-tool signal in its absence.
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 9533d8ae89..cadc1a52ea 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -40,7 +40,8 @@ import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
import { cleanImageBuffer } from '../lib/imageClean.js';
import {
resolveRegenBackend, getRegenAvailability, readImageDimensions, buildRegenParams,
- DEFAULT_REGEN_STRENGTH, REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,
+ REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,
+ resolveRegenStrengthDefault, applyLightRegen, computePixelDelta,
} from '../services/imageGen/regen.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
import { listCollections, addItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
@@ -156,6 +157,9 @@ const regenerateSchema = z.object({
strength: z.number().min(REGEN_STRENGTH_MIN).max(REGEN_STRENGTH_MAX).optional(),
steps: z.number().int().min(1).max(50).optional(),
prompt: z.string().max(8000).optional(),
+ // 'flux' (default) = GPU img2img round-trip; 'light' = CPU-only spatial pass
+ // for installs without a FLUX runner (strength/steps/prompt ignored).
+ method: z.enum(['flux', 'light']).optional(),
});
router.get('/status', asyncHandler(async (req, res) => {
@@ -625,6 +629,68 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
});
}));
+// CPU-only "light" regen (issue #912). The no-GPU fallback: applies sharp's
+// spatial-domain disruption stack (resize-squeeze + color nudge + median/sharpen)
+// to overwrite SynthID's resolution-dependent carriers without a FLUX runner.
+// Synchronous like Clean — writes a `_regen-light.png` variant + sidecar and
+// returns it. Honestly LESS reliable than the GPU round-trip (no FFT phase
+// subtraction); the sidecar stamps `regenMethod: 'light-spatial'` so the UI
+// never overclaims. Mirrors the manual-clean route's file/sidecar/collection shape.
+async function runLightRegen({ filename, sourceAbsPath, sourceMeta }) {
+ const buffer = await readFile(sourceAbsPath).catch((err) => {
+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
+ throw err;
+ });
+ const result = await applyLightRegen(buffer);
+ if (!result) {
+ throw new ServerError('Could not decode image for light regen', { status: 400, code: 'INVALID_IMAGE' });
+ }
+
+ const base = filename.slice(0, -'.png'.length);
+ const outFilename = `${base}_regen-light.png`;
+ const outPath = join(PATHS.images, outFilename);
+ const sidecarPath = join(PATHS.images, `${base}_regen-light.metadata.json`);
+ // Anchor the variant group at the root original (same rule as buildRegenParams):
+ // regenerating a cleaned/regenerated variant must group under the root, not orphan.
+ const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
+ ? sourceMeta.cleanedFrom : filename;
+ const createdAt = new Date().toISOString();
+ // Strip hidden/filename/id so the listGallery `...metadata` spread doesn't
+ // overwrite the disk-derived filename or re-hide the deliberate variant.
+ const { hidden: _hidden, filename: _srcFilename, id: _srcId, ...sourceMetaForVariant } = sourceMeta;
+
+ // Compare the in-memory source/output buffers — no need to re-read outPath
+ // off disk just to measure the delta.
+ const delta = await computePixelDelta(buffer, result.data).catch(() => null);
+ const variantMeta = {
+ ...sourceMetaForVariant,
+ createdAt,
+ cleanedFrom: groupRoot,
+ regenerated: true,
+ regenMethod: 'light-spatial',
+ ...(delta ? { regenPixelDeltaPct: delta.pixelDeltaPct, regenPsnr: delta.psnr } : {}),
+ };
+ await Promise.all([
+ writeFile(outPath, result.data),
+ writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
+ ]);
+
+ const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
+ console.warn(`⚠️ Auto-file light-regen ${outFilename} → collections failed: ${err?.message || err}`);
+ return [];
+ });
+ console.log(`♻️ Light-regen ${filename} → ${outFilename} (${delta ? `${delta.pixelDeltaPct}% changed` : 'fidelity n/a'}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
+
+ // Response is the sidecar record plus the disk-derived fields listGallery adds.
+ return {
+ ...variantMeta,
+ filename: outFilename,
+ path: `/data/images/${outFilename}`,
+ width: result.width,
+ height: result.height,
+ };
+}
+
// SynthID-defeat regeneration (issue #912). Round-trips an existing gallery
// image through local FLUX img2img at low–moderate denoise so the per-pixel
// watermark is overwritten by fresh sampling — the only honest defeat path
@@ -648,12 +714,22 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
readImageDimensions(sourceAbsPath),
]);
+ // CPU-only light path (no FLUX runner required). A best-effort spatial pass
+ // for installs that can't run the GPU round-trip — synchronous like Clean:
+ // it writes a `_regen-light.png` variant inline and returns it (no queue).
+ if (body.method === 'light') {
+ return res.json(await runLightRegen({ filename, sourceAbsPath, sourceMeta }));
+ }
+
const backend = await resolveRegenBackend({ sourceModelId: sourceMeta.modelId });
if (!backend.available) {
throw new ServerError(backend.reason, { status: 400, code: 'REGEN_BACKEND_UNAVAILABLE' });
}
- const strength = body.strength ?? DEFAULT_REGEN_STRENGTH;
+ // Provider-aware default (issue #912): SynthID-bearing sources keep the
+ // known-good 0.25; local FLUX sources use a lighter pass. The explicit
+ // `strength` override always wins.
+ const strength = body.strength ?? resolveRegenStrengthDefault(sourceMeta);
const params = buildRegenParams({
filename,
sourceAbsPath,
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 480d33b5dd..eec8bad752 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -28,6 +28,7 @@ import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js
import { hfTokenEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { IMAGE_GEN_MODE } from './modes.js';
+import { computePixelDelta } from './regen.js';
const IS_WIN = process.platform === 'win32';
@@ -383,6 +384,9 @@ export function buildSidecarMeta({
if (typeof regenOf === 'string' && regenOf && validInitImagePath) {
meta.cleanedFrom = regenOf;
meta.regenerated = true;
+ // Explicit method so consumers never infer it by absence — the CPU path
+ // stamps 'light-spatial', this GPU round-trip stamps 'flux'.
+ meta.regenMethod = 'flux';
meta.regenStrength = validInitImageStrength;
meta.regenSteps = actualSteps;
meta.regenModelId = modelId;
@@ -726,6 +730,19 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
console.log(`🔍 Upscaled regen [${jobId.slice(0, 8)}] ${meta.renderWidth}x${meta.renderHeight} → ${targetW}x${targetH}`);
}
}
+ // Regen fidelity (issue #912): for a regen pass, measure how much the
+ // delivered image actually changed vs. the source so the sidecar records
+ // the *realized* delta, not just the requested strength. Catches the
+ // mflux strength-0.0 footgun, silent txt2img fallbacks, and over-mutation.
+ // Best-effort — a decode failure just skips the stamp.
+ if (regenOf && validInitImagePath) {
+ const delta = await computePixelDelta(validInitImagePath, outputPath).catch(() => null);
+ if (delta) {
+ meta.regenPixelDeltaPct = delta.pixelDeltaPct;
+ meta.regenPsnr = delta.psnr;
+ console.log(`📐 Regen fidelity [${jobId.slice(0, 8)}]: ${delta.pixelDeltaPct}% changed, PSNR ${delta.psnr}dB`);
+ }
+ }
// Sidecar: persist a metadata record next to the PNG so the gallery
// and Remix flow can recover prompt/seed/steps even if mflux's own
// --metadata sidecar lives at a slightly different filename shape.
diff --git a/server/services/imageGen/regen.js b/server/services/imageGen/regen.js
index 621195ff48..7addf10ff4 100644
--- a/server/services/imageGen/regen.js
+++ b/server/services/imageGen/regen.js
@@ -54,6 +54,33 @@ export const DEFAULT_REGEN_STRENGTH = 0.25;
export const REGEN_STRENGTH_MIN = 0.02;
export const REGEN_STRENGTH_MAX = 0.6;
+// Lighter default for sources that DON'T carry Google's SynthID. The big tools
+// tune denoise by generator (remove-ai-watermarks: OpenAI 0.10 / Gemini 0.15)
+// rather than using one flat value. We do the same, but conservatively: the
+// known-good 0.25 is preserved for SynthID-bearing generators (never lower the
+// SynthID path below the value confirmed to clear a detector), while local FLUX
+// renders — which have no Google watermark — use a lighter pass for better
+// fidelity when regenerated for other reasons.
+export const REGEN_LIGHT_STRENGTH_DEFAULT = 0.15;
+
+// Provider-aware denoise default for a regen of `sourceMeta`. SynthID rides on
+// gpt-image (codex) / Imagen / Gemini / Nano-Banana output; those keep the
+// conservative 0.25. Local FLUX sources (a `modelId` with no external `mode`,
+// or `mode: 'local'`) carry no SynthID, so default to the lighter pass.
+// Anything unidentified falls back to the conservative 0.25. The API `strength`
+// override and the [MIN, MAX] bounds are unaffected — this only sets the
+// *default* when the caller doesn't pin a value.
+export function resolveRegenStrengthDefault(sourceMeta = {}) {
+ const meta = sourceMeta || {};
+ const mode = typeof meta.mode === 'string' ? meta.mode.toLowerCase() : null;
+ const model = (typeof meta.modelId === 'string' ? meta.modelId
+ : typeof meta.model === 'string' ? meta.model : '').toLowerCase();
+ const synthIdBearing = mode === 'codex' || /gpt-image|imagen|gemini|nano-?banana/.test(model);
+ if (synthIdBearing) return DEFAULT_REGEN_STRENGTH;
+ const isLocalFlux = (!mode || mode === 'local') && !!model;
+ return isLocalFlux ? REGEN_LIGHT_STRENGTH_DEFAULT : DEFAULT_REGEN_STRENGTH;
+}
+
// FLUX runs self-attention over latent tokens (~pixels/256) and the cost is
// O(tokens²), so render resolution can't track the source for large images:
// a 12.6 MP (4096×3072) codex render is ~60× the attention compute of a 1.5 MP
@@ -73,13 +100,30 @@ export const DEFAULT_MAX_REGEN_MEGAPIXELS = (() => {
// a tiny input can't collapse to 0.
const floor16 = (n) => Math.max(16, Math.floor(n / 16) * 16);
+// Deliberate resolution shift applied to EVERY regen, not just over-budget
+// images. SynthID's invisible carriers live at resolution-dependent FFT bins
+// (the key finding from the reverse-SynthID project: a codebook built at one
+// resolution can't locate the watermark at another), so a downscale→upscale
+// "resize-squeeze" disrupts them at essentially zero cost. The render runs at
+// this fraction of the source and is upscaled back to the exact source dims, so
+// every regen gets a second, GPU-free disruption vector layered on top of the
+// VAE round-trip. 0.9 reliably clears at least one /16 step for typical sizes
+// while keeping the upscale-back blur minimal.
+export const REGEN_SQUEEZE_FACTOR = 0.9;
+
/**
- * Resolve the render dimensions for a regen pass: clamp the source to a
- * FLUX-sane megapixel budget (aspect-preserved) and round to multiples of 16.
- * Pure. Returns `{ width, height, scaled }` where `scaled` is true whenever the
- * render dims differ from the source (either because it was downscaled to fit
- * the budget OR because the source wasn't already /16) — i.e. whenever the
- * caller must upscale the result back to the source's exact dimensions.
+ * Resolve the render dimensions for a regen pass. Two reasons the render runs
+ * off the source's native resolution, both delivered back at the exact source
+ * dims via `upscaleTo`:
+ * 1. Over the megapixel budget → downscale (aspect-preserved) to fit FLUX's
+ * O(tokens²) attention budget (a hard ceiling — see DEFAULT_MAX_REGEN_MEGAPIXELS).
+ * 2. Under budget → still apply the deliberate `REGEN_SQUEEZE_FACTOR` resize-
+ * squeeze so the resolution always shifts, disrupting SynthID's
+ * resolution-dependent frequency carriers.
+ * Pure. Returns `{ width, height, scaled }`; `scaled` is true whenever the
+ * render dims differ from the source — i.e. whenever the caller must upscale
+ * the result back to the source's exact dimensions (which, with the universal
+ * squeeze, is every real image).
*/
export function clampRegenDimensions(srcWidth, srcHeight, maxMegapixels = DEFAULT_MAX_REGEN_MEGAPIXELS) {
const w = Math.round(Number(srcWidth));
@@ -90,7 +134,8 @@ export function clampRegenDimensions(srcWidth, srcHeight, maxMegapixels = DEFAUL
return { width: 1024, height: 1024, scaled: false };
}
const budgetPx = Math.max(1, maxMegapixels) * 1_000_000;
- const scale = w * h > budgetPx ? Math.sqrt(budgetPx / (w * h)) : 1;
+ // Over budget: downscale to fit. Under budget: apply the universal squeeze.
+ const scale = w * h > budgetPx ? Math.sqrt(budgetPx / (w * h)) : REGEN_SQUEEZE_FACTOR;
const rw = floor16(w * scale);
const rh = floor16(h * scale);
return { width: rw, height: rh, scaled: rw !== w || rh !== h };
@@ -180,6 +225,13 @@ export async function getRegenAvailability() {
strengthMin: REGEN_STRENGTH_MIN,
strengthMax: REGEN_STRENGTH_MAX,
strengthDefault: DEFAULT_REGEN_STRENGTH,
+ // CPU-only spatial fallback. Always available (sharp is a hard dependency),
+ // so installs without a FLUX runner can still attempt a SynthID-disrupting
+ // pass — clearly labeled as less reliable than the GPU round-trip.
+ lightAvailable: true,
+ lightReason: resolved.available
+ ? 'CPU-only spatial pass — faster but less reliable than the FLUX round-trip.'
+ : 'No local FLUX runner installed. The light CPU pass is a best-effort, lower-reliability fallback.',
};
}
@@ -243,3 +295,73 @@ export function buildRegenParams({ filename, sourceAbsPath, sourceMeta = {}, sou
if (steps != null) params.steps = steps;
return params;
}
+
+// Measure how much a regen actually changed the image — source vs. delivered.
+// Every serious watermark tool gates on a fidelity metric (reverse-SynthID
+// PSNR-gates each stage); we only stamped the *requested* strength, never the
+// realized delta. This turns "trust me" into a number that catches the failure
+// modes a blind pass can't see: the mflux strength-0.0 footgun (~49% change), a
+// silent txt2img fallback, or plain over-mutation. Both images are decoded to a
+// small common raster (cheap, resolution-independent) and compared per-channel.
+// `a`/`b` are each a file path OR an in-memory Buffer (sharp accepts both) — the
+// caller passes buffers when it already has the bytes to skip a disk re-read.
+// Returns `{ pixelDeltaPct, psnr }` (psnr in dB; Infinity for identical), or
+// null on a decode failure so the caller can skip the stamp without failing the
+// render.
+export async function computePixelDelta(a, b, sampleSize = 256) {
+ const toRaster = (src) => sharp(src)
+ .resize(sampleSize, sampleSize, { fit: 'fill', kernel: 'cubic' })
+ .removeAlpha()
+ .raw()
+ .toBuffer()
+ .catch(() => null);
+ const [ra, rb] = await Promise.all([toRaster(a), toRaster(b)]);
+ if (!ra || !rb || ra.length !== rb.length) return null;
+ let sumAbs = 0;
+ let sumSq = 0;
+ for (let i = 0; i < ra.length; i++) {
+ const d = ra[i] - rb[i];
+ sumAbs += d < 0 ? -d : d;
+ sumSq += d * d;
+ }
+ const pixelDeltaPct = Math.round((sumAbs / ra.length / 255) * 1000) / 10;
+ const mse = sumSq / ra.length;
+ const psnr = mse === 0 ? Infinity : Math.round(10 * Math.log10((255 * 255) / mse) * 10) / 10;
+ return { pixelDeltaPct, psnr };
+}
+
+// CPU-only "light" regen — the no-GPU fallback for installs without a local
+// FLUX runner (Windows mflux, no-GPU boxes, diffusers-only setups), which today
+// get NOTHING: imageClean.js's median+sharpen explicitly can't touch SynthID.
+// This layers the cheap spatial-domain stages the research tools use when no
+// diffusion model is available (reverse-SynthID's resize-squeeze + color nudge,
+// Synthid-Bypass's recompress):
+// 1. resize-squeeze (cubic down → lanczos up) — disrupts the resolution-
+// dependent SynthID carriers, same idea as clampRegenDimensions but CPU-side.
+// 2. micro color/contrast nudge (modulate + linear) — imperceptible, shifts
+// pixel statistics the watermark detector keys on.
+// 3. high-frequency perturbation (median + sharpen) — perturbs the band the
+// invisible mark rides in.
+// HONESTLY less reliable than the VAE round-trip — spatial transforms can't do
+// the FFT phase-subtraction the GPU tools layer on top, so the caller MUST
+// label this as best-effort. Pure-ish: sharp in, `{ data, width, height }` out.
+// `sharpImpl` is injectable for tests.
+export async function applyLightRegen(buffer, { sharpImpl = sharp } = {}) {
+ const meta = await sharpImpl(buffer).metadata().catch(() => null);
+ const w = Math.round(Number(meta?.width));
+ const h = Math.round(Number(meta?.height));
+ if (!(w > 0) || !(h > 0)) return null;
+ const sw = floor16(w * REGEN_SQUEEZE_FACTOR);
+ const sh = floor16(h * REGEN_SQUEEZE_FACTOR);
+ const data = await sharpImpl(buffer)
+ .rotate() // honor EXIF orientation so output matches what the browser showed
+ .resize(sw, sh, { kernel: 'cubic' })
+ .resize(w, h, { fit: 'fill', kernel: 'lanczos3' })
+ .modulate({ brightness: 1.01, saturation: 0.99, hue: 1 })
+ .linear(1.02, -2)
+ .median(2)
+ .sharpen()
+ .png({ compressionLevel: 6 })
+ .toBuffer();
+ return { data, width: w, height: h };
+}
diff --git a/server/services/imageGen/regen.sharp.test.js b/server/services/imageGen/regen.sharp.test.js
new file mode 100644
index 0000000000..de6735a32f
--- /dev/null
+++ b/server/services/imageGen/regen.sharp.test.js
@@ -0,0 +1,71 @@
+// Real-sharp tests for the regen pixel/spatial helpers (issue #912). Kept in a
+// SEPARATE file from regen.test.js because that suite mocks `sharp` for the
+// pure param-assembly tests — computePixelDelta and applyLightRegen need the
+// genuine decoder/encoder. sharp accepts a Buffer or a path, so the fixtures
+// are in-memory PNG buffers (no temp files).
+import { describe, it, expect } from 'vitest';
+import sharp from 'sharp';
+import { computePixelDelta, applyLightRegen, REGEN_SQUEEZE_FACTOR } from './regen.js';
+
+// Solid-color PNG of the given size — a deterministic fixture for delta math.
+const solidPng = (w, h, { r, g, b }) =>
+ sharp({ create: { width: w, height: h, channels: 3, background: { r, g, b } } }).png().toBuffer();
+
+describe('computePixelDelta', () => {
+ it('reports zero delta / infinite PSNR for an identical image', async () => {
+ const buf = await solidPng(128, 128, { r: 120, g: 64, b: 200 });
+ const delta = await computePixelDelta(buf, buf);
+ expect(delta.pixelDeltaPct).toBe(0);
+ expect(delta.psnr).toBe(Infinity);
+ });
+
+ it('reports a large delta for opposite solid colors', async () => {
+ const black = await solidPng(128, 128, { r: 0, g: 0, b: 0 });
+ const white = await solidPng(128, 128, { r: 255, g: 255, b: 255 });
+ const delta = await computePixelDelta(black, white);
+ expect(delta.pixelDeltaPct).toBeGreaterThan(95); // ~100% of full range
+ expect(delta.psnr).toBeLessThan(5); // near-worst-case
+ });
+
+ it('returns null when an input cannot be decoded', async () => {
+ const ok = await solidPng(64, 64, { r: 10, g: 10, b: 10 });
+ const delta = await computePixelDelta(ok, Buffer.from('not an image'));
+ expect(delta).toBeNull();
+ });
+});
+
+describe('applyLightRegen', () => {
+ it('returns a re-encoded PNG at the SOURCE dimensions (squeeze is upscaled back)', async () => {
+ const src = await solidPng(256, 192, { r: 80, g: 160, b: 240 });
+ const out = await applyLightRegen(src);
+ expect(Buffer.isBuffer(out.data)).toBe(true);
+ expect(out.width).toBe(256);
+ expect(out.height).toBe(192);
+ // Output decodes back at the original dimensions, not the squeezed render size.
+ const meta = await sharp(out.data).metadata();
+ expect(meta.width).toBe(256);
+ expect(meta.height).toBe(192);
+ });
+
+ it('actually changes the pixels (it is a disruption pass, not a copy)', async () => {
+ // A non-uniform image so the spatial stages have detail to perturb.
+ const src = await sharp({
+ create: { width: 256, height: 256, channels: 3, background: { r: 30, g: 90, b: 180 } },
+ }).composite([{
+ input: { create: { width: 128, height: 256, channels: 3, background: { r: 220, g: 60, b: 60 } } },
+ left: 0, top: 0,
+ }]).png().toBuffer();
+ const out = await applyLightRegen(src);
+ const delta = await computePixelDelta(src, out.data);
+ expect(delta.pixelDeltaPct).toBeGreaterThan(0);
+ });
+
+ it('returns null for an undecodable buffer', async () => {
+ expect(await applyLightRegen(Buffer.from('nope'))).toBeNull();
+ });
+
+ it('squeeze factor is a sane fraction below 1', () => {
+ expect(REGEN_SQUEEZE_FACTOR).toBeGreaterThan(0.5);
+ expect(REGEN_SQUEEZE_FACTOR).toBeLessThan(1);
+ });
+});
diff --git a/server/services/imageGen/regen.test.js b/server/services/imageGen/regen.test.js
index fbda0fec9f..cc9c5f3f05 100644
--- a/server/services/imageGen/regen.test.js
+++ b/server/services/imageGen/regen.test.js
@@ -25,7 +25,8 @@ import { existsSync } from 'node:fs';
import {
orderRegenCandidates, modelSupportsRegen, modelUsesFluxVenv,
resolveRegenBackend, buildRegenParams, DEFAULT_REGEN_STRENGTH,
- clampRegenDimensions,
+ REGEN_LIGHT_STRENGTH_DEFAULT, REGEN_SQUEEZE_FACTOR,
+ clampRegenDimensions, resolveRegenStrengthDefault, computePixelDelta,
} from './regen.js';
const FLUX2 = { id: 'flux2-klein-9b', runner: 'flux2', cfgDisabled: true };
@@ -155,11 +156,12 @@ describe('buildRegenParams', () => {
initImagePath: '/data/images/source.png',
initImageStrength: DEFAULT_REGEN_STRENGTH,
regenOf: 'source.png',
- width: 1024,
- height: 768,
});
- // 1024x768 is ≤2MP and /16, so no scale-back is needed.
- expect(params.upscaleTo).toBeUndefined();
+ // Universal resize-squeeze: even an under-budget /16 image renders smaller
+ // and is upscaled back to the source dims (the SynthID carrier-disruption pass).
+ expect(params.width).toBeLessThan(1024);
+ expect(params.height).toBeLessThan(768);
+ expect(params.upscaleTo).toEqual({ width: 1024, height: 768 });
});
it('honors an explicit promptOverride (creative re-roll) and carries the source negative', () => {
@@ -199,8 +201,11 @@ describe('buildRegenParams', () => {
sourceMeta: { prompt: 'x', width: 100, height: 100 },
sourceDims: { width: 1280, height: 720 },
});
- expect(params.width).toBe(1280);
- expect(params.height).toBe(720);
+ // The render is squeezed, but it's delivered back at the MEASURED 1280x720
+ // (not the bogus 100x100 sidecar) — proving measured dims won.
+ expect(params.upscaleTo).toEqual({ width: 1280, height: 720 });
+ expect(params.width).toBeLessThan(1280);
+ expect(params.width).toBeGreaterThan(1280 * 0.8);
});
it('keeps the prompt empty even when the source has one (minimal mutation)', () => {
@@ -244,8 +249,18 @@ describe('buildRegenParams', () => {
});
describe('clampRegenDimensions', () => {
- it('leaves a /16 image under budget untouched (no scale-back)', () => {
- expect(clampRegenDimensions(1024, 1536)).toEqual({ width: 1024, height: 1536, scaled: false });
+ it('applies the universal resize-squeeze to an under-budget /16 image', () => {
+ // Even though 1024x1536 is ≤2MP and /16, the deliberate squeeze shifts the
+ // resolution (disrupting SynthID's resolution-dependent carriers) and flags
+ // scaled so the caller upscales back to the exact source dims.
+ const r = clampRegenDimensions(1024, 1536);
+ expect(r.scaled).toBe(true);
+ expect(r.width).toBeLessThan(1024);
+ expect(r.height).toBeLessThan(1536);
+ expect(r.width % 16).toBe(0);
+ expect(r.height % 16).toBe(0);
+ // Stays close to the source (≈ REGEN_SQUEEZE_FACTOR), not a drastic downscale.
+ expect(r.width).toBeGreaterThan(1024 * REGEN_SQUEEZE_FACTOR - 16);
});
it('downscales a 12.6MP image under the 2MP budget, /16, aspect-preserved', () => {
@@ -276,3 +291,26 @@ describe('clampRegenDimensions', () => {
expect(clampRegenDimensions(NaN, NaN)).toEqual({ width: 1024, height: 1024, scaled: false });
});
});
+
+describe('resolveRegenStrengthDefault', () => {
+ it('keeps the known-good 0.25 for SynthID-bearing codex sources', () => {
+ expect(resolveRegenStrengthDefault({ mode: 'codex', model: 'gpt-image-2' })).toBe(DEFAULT_REGEN_STRENGTH);
+ });
+
+ it('keeps 0.25 for gemini / imagen / nano-banana sources by model id', () => {
+ expect(resolveRegenStrengthDefault({ modelId: 'gemini-2.5-flash-image' })).toBe(DEFAULT_REGEN_STRENGTH);
+ expect(resolveRegenStrengthDefault({ modelId: 'imagen-3' })).toBe(DEFAULT_REGEN_STRENGTH);
+ expect(resolveRegenStrengthDefault({ modelId: 'nano-banana-pro' })).toBe(DEFAULT_REGEN_STRENGTH);
+ });
+
+ it('uses the lighter default for local FLUX sources (no Google watermark)', () => {
+ expect(resolveRegenStrengthDefault({ modelId: 'flux2-klein-9b' })).toBe(REGEN_LIGHT_STRENGTH_DEFAULT);
+ expect(resolveRegenStrengthDefault({ mode: 'local', modelId: 'dev' })).toBe(REGEN_LIGHT_STRENGTH_DEFAULT);
+ });
+
+ it('falls back to the conservative 0.25 for unidentified sources', () => {
+ expect(resolveRegenStrengthDefault({})).toBe(DEFAULT_REGEN_STRENGTH);
+ expect(resolveRegenStrengthDefault({ mode: 'external' })).toBe(DEFAULT_REGEN_STRENGTH);
+ expect(resolveRegenStrengthDefault(null)).toBe(DEFAULT_REGEN_STRENGTH);
+ });
+});