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

image cleaning: per-provider auto-clean, variant toggle, honest SynthID copy

[._.]/ Adam Eivy1e510602ac4b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7a7a6e79c3..fcdef49016 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,8 +10,18 @@
- **Per-bucket exporter hash cache.** Subscription re-exports of large series no longer re-hash every referenced asset to confirm "blob already there." A new `<bucket>/assets/blobs/.index.json` sidecar maps `<sourcePath>:<mtimeMs>:<size> → <hash>` so `server/services/sharing/exporter.js#copyAssetIfPresent` skips both `sha256File` (multi-GB stream read) and the redundant `copyFile` when the cache hit's blob is still on disk. mtime change invalidates automatically because it's part of the key. A 200MB re-export drops from ~200MB of disk reads to a single JSON load + stat per asset.
+- **Auto-clean after generation — per-provider opt-in (codex / local / external).** New `settings.imageGen.{codex,local,external}.autoClean` flag wires the existing image-clean pipeline into the post-generation success path for each backend independently. When on for a provider, every generated PNG is run through `cleanImageBuffer` (sharp `median(3).sharpen()` + C2PA strip) and the cleaned bytes replace the original in place via atomic temp+rename — fires BEFORE the SSE `complete` event so subscribers see the cleaned image on first fetch. The sidecar gets `autoCleaned: true`, `cleanLevel: 'aggressive'`, `c2paStripped: <bool>`. A clean failure never fails the generation (logs + falls back to the un-cleaned PNG). Three new checkboxes in Settings → Image Gen (one per mode section); the manual Clean button on existing gallery images still produces a separate `_clean-aggressive.png` sidecar copy. Reachable from the lightbox: the metadata panel now shows a "Cleaned" row when the sidecar carries either `autoCleaned` (in-place) or `cleanedFrom` (manual copy) lineage. The clean primitives moved from `server/routes/imageClean.js` to `server/lib/imageClean.js` so the new `autoCleanGeneratedImage` helper is callable from services without crossing the routes→services dep direction; the HTTP route is now a thin wrapper.
+
+- **Manual clean now auto-files into the source's collections.** Previously cleaning an image via the lightbox Clean button created `<filename>_clean-aggressive.png` in the gallery, but the cleaned copy didn't appear in any collection the source was part of — users had to manually re-add it everywhere. `POST /api/image-gen/:filename/clean` now scans every collection (`listCollections()`), finds the ones containing the source `image:<filename>` key, and calls `addItem()` for the cleaned filename on each. Idempotent across re-cleans (`ERR_DUPLICATE` is swallowed); best-effort overall (collection-write failures log a warning but don't fail the clean).
+
+- **Lightbox: original ↔ cleaned variant toggle.** When the previewed image has a manually-cleaned sibling in the same items list (or IS a cleaned sibling), a small segmented control appears at the top of the SettingsPane labeled "View: Original | Cleaned (aggressive)" — click flips the lightbox to the other variant without closing the modal. Drives the swap through the host page's existing `setPreview` URL machinery, so the toggle is also a deep-linkable URL change. New `client/src/components/media/variants.js` houses the pure `computeImageVariantGroup(item, items)` helper (unit-tested in `variants.test.js`); `MediaPreview.jsx` computes the group from its `items` prop and threads `variantGroup` + `onSelectVariant` into `MediaLightbox`. Auto-cleaned images replace the original in place (only one file exists) so the toggle correctly does not appear for them.
+
+- **Per-render "Auto-clean this render" checkbox on the Image Gen form** + a quiet fix to make saved auto-clean actually work for codex/local. The Image Gen page (`/media/image`) now exposes a checkbox under the Generate button that lets the user override the saved per-mode `imageGen.{mode}.autoClean` setting for a single render — toggles label changes to "(overrides saved default)" when the value differs from the saved one. The checkbox is seeded on mount + every mode switch from the active mode's saved setting, so the default-off case stays unsurprising. Wired through a new `autoClean: z.boolean().optional()` field on the generate route's schema, with multipart string→bool coercion in `coerceFormFields`. Same fix uncovered a latent bug: codex + local enqueue through `mediaJobQueue` and bypass the dispatcher's autoClean resolution, so the saved settings flag previously had no effect for those modes (only external mode worked, and nobody had caught it yet). The route is now the single resolution point — `data.autoClean = body.autoClean ?? settings.imageGen[mode].autoClean` runs once and the value flows through all three dispatch paths verbatim. The dispatcher still resolves autoClean as a safety net for direct callers (avatar route, voice tool). 6 new tests in `imageGen.test.js` cover the precedence matrix (body wins / saved inherited / default false / all three modes).
+
## Changed
+- **Image Cleaner copy: honest about SynthID.** The lightbox Clean tooltip, both auto-clean settings descriptions (Settings → Image Gen, and per-render Image Gen form checkbox), the `/devtools/image-clean` page subtitle, the success toast, the file-header comment in `server/lib/imageClean.js`, and the palette nav-manifest keywords (dropped `watermark`) now all explicitly say the cleaner removes the C2PA metadata chunk (verified: confirmed by openai.com/synthid showing "Content Credentials not detected" after a clean of a gpt-image render) but does NOT defeat SynthID. SynthID is embedded in pixel values and Google's published claims state it survives median+sharpen+re-encode by design; gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers after a clean. The prior copy ("strips C2PA provenance + reduces AI artifacts") was technically accurate per-step but implicitly framed the cleaner as a provenance-stripper, which over-promised against SynthID-bearing output. Devtools page also adds a yellow-tagged Note paragraph linking to openai.com/synthid.
+
- **`isPlainObject` promoted to a named export of `server/lib/objects.js`.** The `(v && typeof v === 'object' && !Array.isArray(v))` check was previously inlined at 16 sites across `server/lib/`, `server/services/`, and `server/routes/`. The helper is now a named export of `objects.js` (surfaces through the `server/lib/index.js` barrel automatically) and all 16 sites import it. Pure refactor — no behavioral changes; the helper retains the "non-null, non-array `object`" semantics that match every existing call site (Date / Map / class instances still return true).
- **AI Toolkit "not initialized" errors now carry a typed code + 503 status across runner + promptService.** `server/services/runner.js` (13 sites) and `server/services/promptService.js` (12 sites) previously each inlined `if (!aiToolkitInstance) throw new Error(…)` checks that surfaced as untyped 500s with string-matched messages. Both now go through a private `requireToolkit()` helper that throws `ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — the same shape `providers.js` already throws. Callers (e.g. `visionTest.js`) can gate on `err.code === 'AI_TOOLKIT_NOT_INITIALIZED'` uniformly regardless of which service raised, and routes that hit any of the three services during toolkit warm-up now return 503 (service-unavailable) rather than a generic 500. No behavior change for the warmed path.
@@ -28,8 +38,12 @@
- **PLAN.md cleanup.** Removed 9 already-completed `[x]` items (Universe-as-Canon Phase 2, Pipeline continuity / approval, scattered Code quality / Better-audit / Deferred-from-better entries) — those sections went away or shrunk since DONE.md is the canonical archive. Reorganized the Backlog: 32 items requiring decision/design or waiting on a precondition moved to a new `## Blocked on decision / design (skip for \`/claim\`)` section at the bottom, split into Audio/Video/Image gen, Voice/agents, Large product/UX redesigns, and Trigger-gated subsections. The remaining Backlog is now items an agent can pick up cold via `/claim` — concrete file:line bugs, scoped refactors, and well-specified small features. 218 → 200 lines.
+- **Image cleaning collapsed to a single button.** The light/aggressive split is gone — `light` (median(1) only) was tested in production and proved unreliable, leaving visible C2PA-adjacent noise patterns. The `MediaLightbox` Clean affordance is now a single Eraser-icon button with a `title` tooltip ("Re-encode and denoise to strip embedded provenance metadata (C2PA) and reduce AI-generation artifacts. Saves a new image alongside the original."), and the `/devtools/image-clean` page dropped its level picker. The `POST /api/image-clean` and `POST /api/image-gen/:filename/clean` request bodies no longer accept `level`; the gallery clean filename suffix (`_clean-aggressive.png`) and sidecar `cleanLevel: 'aggressive'` field are kept unchanged so existing on-disk cleaned files round-trip correctly. `cleanGalleryImage(filename)` and `cleanImage(base64)` API helpers + the shared `useImagePreviewActions` `handleClean(img)` dropped their `level` argument across all five call sites (ImageGen, MediaHistory, MediaCollectionDetail, UniverseBuilder, lightbox).
+
## Fixed
+- **HF token banner no longer surfaces in Codex / External mode.** The `needsHfTokenGate` predicate in `client/src/pages/ImageGen.jsx` checked `currentModel?.requiresHfToken && !isFlux2Model` but forgot to also require `isLocalMode`. A user who'd selected a gated mflux model (e.g. FLUX.1-dev) and later switched the backend chip to Codex saw the "Flux 1 Dev is a gated model — paste your HF token" banner over the Codex form, even though Codex uses gpt-image-2 and never touches HuggingFace. The gate now requires `isLocalMode` first, matching the FLUX.2 install/status block right below it.
+
- **v2.1.0 review residue — small-fixes bundle (11 items).** Universe Builder render registration moves before the enqueue loop so the worker can't race past run registration and lose per-image emit coalescing; `seasonCoverSchema` gained `.passthrough()` so a full-series round-trip echoing server-built render fields no longer 400s; `volumePdf.js` sort now uses `arcPosition || number || id` with `?? Infinity` so null-arcPosition issues sink to the end instead of interleaving via the `number` fallback; series PATCH `console.warn`s when legacy `characters` / `settings` / `objects` are stripped so stale-tab POSTs are observable; `promptRunner.js` cwd guard now treats empty-string overrides as absent (matches `tuiPromptRunner`); `loops.js` no longer misclassifies an `onComplete({success:true})` throw as `iteration:error`; dead `|| series.characters` fallback removed from `textStages.js`; `migrateSeriesCanon.js` defers the orphan-series universe-link write until after the canon patch lands so a crash window doesn't leave the series stripped + universe empty; importer warns when arc-extract returns empty `summary` + `logline` before falling back to a synthetic value; `ansiStrip.js` adds a `\x1B(?![@-_\[\]])` second-pass strip so chunks like `\x1B\x1B[31m` no longer leak an orphan escape byte.
- **Sharing/annotation-merge hardening — 5 v2.1.0 residue items.** Outgoing annotation manifests now honor per-bucket `displayNameOverride` (previously all buckets got the global name); peer payloads with missing/invalid `updatedAt` are dropped on import instead of winning LWW via a `now`-fallback; future-skewed peer timestamps are clamped to local-now to stop one bad clock from ratcheting every subsequent merge; `peerInstanceId === 'unknown'` (or empty) is refused on import to match the existing outgoing-path guard; and `exportAnnotationsToBucket` now skips both the asset-dir scan AND the record write when local has no annotations and no prior record exists, so a fresh-install annotation edit doesn't fan an empty manifest into every auto-merge bucket.
diff --git a/PLAN.md b/PLAN.md
index 782dc4e5fc..366046e2f8 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -10,16 +10,6 @@ _Nothing currently parked — pick the next item from the Backlog._
## Backlog
-### Voice agent
-
-- [ ] [wire-proactive-cos-speech-to-real-triggers] **Wire proactive CoS speech to real triggers.** Plumbing landed (`POST /api/voice/speak` + `voice:speak` socket event); hook to high-severity `errorEvents`, `task:ready`, and `notificationEvents` with per-source rate-limits.
-- [ ] [optimize-voice-ui-index-text-payload-lazy-only-run] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.
-- [ ] [voice-agent-explicit-long-term-memory-routing-on] **Voice agent — explicit long-term memory routing.** On retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search`.
-
-### Image / Video Gen UI
-
-- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs.
-
### Code quality / dedup (from `/simplify` passes)
- [ ] [extract-mergeexpandintodraft-draft-result-from] **Extract `mergeExpandIntoDraft(draft, result)` from `UniverseBuilder.jsx#handleExpand`.** The function is ~150 lines mixing pure-merge logic (categories, sheets, canon, locks) with I/O shell (API call, setDraft, auto-save, toast). Pull the merge into a top-level pure helper so the I/O surface shrinks and the merge is unit-testable. Deferred from Phase B `/simplify` to keep that PR tightly scoped.
@@ -36,6 +26,11 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.
- [ ] [extract-readcertmeta-helper] **Extract a shared `readCertMeta()` helper from `data/certs/meta.json` readers.** Three independent readers exist: `server/lib/peerSelfHost.js:13-18` (hostname only), `server/services/certRenewer.js:30-31` (mode + hostname), `server/lib/networkExposure.js:25-29` (mode + hostname + ips). Each does its own `statSync({ throwIfNoEntry: false }) + readFileSync + safeJSONParse`. Consolidate into `server/lib/certMeta.js` exporting `readCertMeta() → { mode, hostname, ips } | null`. Surfaced by /simplify during `[codex5-network-exposure-ui]`; deferred to keep that PR scoped. Note `peerSelfHost.js` is in a hot path — verify perf when consolidating.
- [ ] [hoist-loopback-host-helper-to-client-lib] **Hoist `isLoopbackHost` to `client/src/lib/loopbackHost.js`.** `server/lib/networkExposure.js` exports `isLoopbackHost`, but `client/src/components/NetworkExposureWidget.jsx:22-30` re-declares the same `LOOPBACK_HOSTS` Set and `describeMicAvailability()` helper inline (server export isn't reachable from browser). Move the client copy into `client/src/lib/loopbackHost.js` + add a barrel entry so future secure-context callers (voiceClient, etc.) can reuse it. When hoisting, broaden the IPv4 check from a single literal `127.0.0.1` to the full `127.0.0.0/8` loopback range to match browser secure-context behavior — easy `/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/` regex. Surfaced by /simplify and the codex review during `[codex5-network-exposure-ui]`.
+- [ ] [imagegen-autoclean-double-resolution] **Deduplicate `autoClean` resolution across route + dispatcher.** `server/routes/imageGen.js:204-206` and `server/services/imageGen/index.js:73-79` both compute the same `body.autoClean ?? settings.imageGen[mode].autoClean === true` precedence. The route's resolution is the one that matters in practice (it's the single path that feeds both the synchronous external dispatch AND the codex/local job queue, which bypasses the dispatcher); the dispatcher's resolution is only a safety net for direct callers like `generateAvatar`. Either extract `resolveAutoClean(body, settings, mode)` into one helper and call from both, or thread the resolved value through `params` and have the dispatcher trust it. Cosmetic dup; works correctly today. Settings is cache-backed so the double `getSettings()` call is sub-ms. Surfaced by /simplify after the per-render checkbox PR.
+- [ ] [imagegentab-triplicate-autoclean-state-collapse] **Collapse triplicate auto-clean state in `ImageGenTab.jsx`.** Three near-identical state vars (`autoCleanCodex/Local/External` at `client/src/components/settings/ImageGenTab.jsx:56-58`), three `saved` snapshot fields (`:73-77`), three isDirty comparisons (`:191-193`), three save-patch entries (`:204-209`), three reload assignments (`:149-169`). Collapse to one object: `const [autoCleanByMode, setAutoCleanByMode] = useState({ codex: false, local: false, external: false })` with checkbox `onChange={(v) => setAutoCleanByMode(p => ({ ...p, codex: v }))}`. Cuts ~15 LOC. Surfaced by /simplify after the per-render checkbox PR.
+- [ ] [imagegen-savedautocleanbymode-derive] **Derive `savedAutoCleanByMode` instead of holding it as state.** `client/src/pages/ImageGen.jsx:161,245-249,256-259` keeps a `savedAutoCleanByMode` map + a re-seed `useEffect` that fires on every `effectiveMode` change. Could be a single inline computation in `reloadBackends` + the chip `onChange`: `setAutoClean(s.imageGen?.[mode]?.autoClean === true)`. Kills one state var and one effect. Surfaced by /simplify after the per-render checkbox PR.
+- [ ] [image-gen-mode-enum-unify] **Unify image-gen mode enum across server + client.** Server has `IMAGE_GEN_MODES = ['external','local','codex']` (a Zod-validator alphabet) at `server/services/imageGen/index.js:21`; client has `IMAGE_GEN_MODE` constants at `client/src/utils/imageGenBackends.js:3`. Code reads strings (`'codex'`, `'local'`, `'external'`) inline at ~10 sites across `server/services/imageGen/{codex,local,external}.js`, `server/routes/imageGen.js`, and several client pages. Either export a typed enum object on the server (`IMAGE_GEN_MODE = Object.freeze({ CODEX: 'codex', ... })`) and use throughout, or accept the string-soup and drop the unused `IMAGE_GEN_MODES` array. Surfaced by /simplify after the per-render checkbox PR.
+- [ ] [autoclean-sidecar-read-parallelize] **Parallelize sidecar read with PNG write in `autoCleanGeneratedImage`.** `server/lib/imageClean.js#autoCleanGeneratedImage` awaits the cleaned-PNG `atomicWrite` before kicking off `tryReadFile(sidecarPath)`, even though the sidecar read has no data dependency on the PNG write. Start `tryReadFile(sidecarPath)` immediately after `cleanImageBuffer` returns and `await` both. Saves ~1ms per auto-clean. Marginal — only matters under sustained parallel codex/local generation. Surfaced by /simplify after the per-render checkbox PR.
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
@@ -57,7 +52,7 @@ _Nothing currently parked — pick the next item from the Backlog._
### Better-audit residue
- [ ] [extract-shared-requiretoolkit-helper] **[LOW][CODE]** Three services now carry an identical private `requireToolkit()` helper that throws `ServerError('AI Toolkit not initialized', { status: 503, code: 'AI_TOOLKIT_NOT_INITIALIZED' })` — `server/services/providers.js`, `server/services/runner.js`, `server/services/promptService.js`. Three module-level `let aiToolkitInstance = null` declarations all receive the same toolkit object from `server/index.js` via per-service `setAIToolkit(toolkit)` setters. Candidate consolidation: extract to `server/lib/aiToolkitState.js` exporting `setAIToolkitInstance(toolkit)` + `requireToolkit()` so all three services import the same module-level state. Includes barrel + README row per `server/lib/` maintenance rule. Deferred from `[extract-requiretoolkit-pattern-to-runner-js]` — three callers crosses the threshold but the 8-line helper × 3 sites is low-maintenance enough that this can wait for a fourth caller or somebody actually wanting to consolidate.
-- [ ] [feeds-ssrf-ipv6-bracket-hostname-gap] **[MED][SECURITY]** `server/services/feeds.js#isHostSafe` doesn't reliably reject IPv6 literal hostnames like `http://[::1]/feed`. `new URL(...).hostname` returns `'[::1]'` (with brackets), so `net.isIP('[::1]')` returns 0 (brackets aren't valid IP syntax) and execution falls through to `dns.resolve4('[::1]')`. Production DNS typically errors → empty addresses → `return false`, so the loopback is protected *incidentally*, but the protection is fragile (any caching resolver or unusual hosts file could subvert it). Fix: strip surrounding `[…]` brackets before `net.isIP`, add an explicit `if (net.isIP(stripped) === 6) return !isPrivateIP(stripped)` branch, and extend `isPrivateIP` to cover ULA (`fc00::/7`) and link-local (`fe80::/10`) ranges. `isPrivateIP` already handles `::1`/`::`. Surfaced 2026-05-19 while adding feeds.js test coverage; deferred to keep that PR scoped to tests.
+- [ ] [feeds-ssrf-ipv6-bracket-hostname-gap] **[MED][SECURITY]** `server/services/feeds.js#isHostSafe` doesn't reliably reject IPv6 literal hostnames like `http://[::1]/feed`. `new URL(...).hostname` returns `'[::1]'` (with brackets), so `net.isIP('[::1]')` returns 0 (brackets aren't valid IP syntax) and execution falls through to `dns.resolve4('[::1]')`. Production DNS typically errors → empty addresses → `return false`, so the loopback is protected _incidentally_, but the protection is fragile (any caching resolver or unusual hosts file could subvert it). Fix: strip surrounding `[…]` brackets before `net.isIP`, add an explicit `if (net.isIP(stripped) === 6) return !isPrivateIP(stripped)` branch, and extend `isPrivateIP` to cover ULA (`fc00::/7`) and link-local (`fe80::/10`) ranges. `isPrivateIP` already handles `::1`/`::`. Surfaced 2026-05-19 while adding feeds.js test coverage; deferred to keep that PR scoped to tests.
### Pipeline — deferred
@@ -86,6 +81,16 @@ The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule n
- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.
+### Voice agent
+
+- [ ] [wire-proactive-cos-speech-to-real-triggers] **Wire proactive CoS speech to real triggers.** Plumbing landed (`POST /api/voice/speak` + `voice:speak` socket event); hook to high-severity `errorEvents`, `task:ready`, and `notificationEvents` with per-source rate-limits.
+- [ ] [optimize-voice-ui-index-text-payload-lazy-only-run] **Optimize `voice:ui:index` text payload.** Lazy: only run `extractVisibleText` when server requests via `voice:ui:read-request`. Keep current behavior as fallback.
+- [ ] [voice-agent-explicit-long-term-memory-routing-on] **Voice agent — explicit long-term memory routing.** On retrieval-shaped voice turns, inject top-N relevant memories into the system prompt via `brain_search`.
+
+### Image / Video Gen UI
+
+- [ ] [flux2-multi-reference-python-runner] **FLUX.2 multi-reference Python runner.** The UI + server contract for multi-reference editing shipped 2026-05-17 (slug `multi-reference-image-editing-for-flux-2-ui`); the Python runner (`scripts/flux2_macos.py`) currently ignores the `--reference-images`/`--reference-strengths` args that `local.js` now passes. Wire diffusers' multi-reference API in the runner and swap `server/lib/mediaModels.js#flux2-klein-9b` `tokenizerRepo` to `FLUX.2-klein-9B-kv` (gated repo — requires the user to accept the license on HF). Validate end-to-end with 2–4 uploaded refs.
+
---
## Deferred Architecture (human-led planning)
@@ -113,8 +118,6 @@ God-file decomposition candidates — none are bugs; pick up when touching the f
- `autofixer/ui.js` (972 LOC) — inline HTML template needs extraction.
- API contract — standardize error response shapes (`asyncHandler` + `ServerError` everywhere).
-**Known low-severity:** pm2 ReDoS (GHSA-x5gf-qvw8-r2rm) — no upstream fix, not exploitable via PortOS routes.
-
---
## Blocked on decision / design (skip for `/claim`)
@@ -178,3 +181,4 @@ Items here need a research / design pass, an explicit decision, or a preconditio
- **Inline Code Review Annotations** — one-click fix from self-improvement findings.
- **Major Dependency Upgrades** — React 19, Zod 4, PM2 6, Vite 8.
- **Workflow tab Phase 2** — drag-and-drop ordering of stages, custom user-defined stages, per-app workflow overrides.
+- **Generative regen path for SynthID defeat (image cleaner).** Current `cleanImageBuffer` (`server/lib/imageClean.js`) only strips the C2PA `caBX` chunk + runs `median(3).sharpen()` — SynthID survives by design (verified: post-clean codex output still detected by openai.com/synthid). A real SynthID defeater needs to round-trip pixels through a generative model: img2img on a local FLUX runner at moderate denoise strength (~0.35–0.5) so the composition holds but the per-pixel watermark signal is overwritten by the new sampling. New "Defeat watermark (slow, alters image)" option exposed in the lightbox + Settings → Image Gen + per-render Image Gen checkbox, gated on local mode being configured (or fallback to a cloud img2img provider, which costs money). Sidecar records `regenerated: true, regenStrength: 0.4, regenModelId: 'flux-v1'` so the lineage is honest. Probably wants its own queue lane since each run is ~5–15s on local mflux. UX caveat: this is the only honest watermark-defeat path; the existing C2PA-strip-and-denoise will always be a no-op against SynthID and should never be relabeled as a watermark stripper.
diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsx
index 6522ae830a..a5751341ce 100644
--- a/client/src/components/media/MediaLightbox.jsx
+++ b/client/src/components/media/MediaLightbox.jsx
@@ -29,12 +29,30 @@ const isEditableTarget = (e) => {
return !!(t && (t.tagName === 'TEXTAREA' || t.tagName === 'INPUT' || t.isContentEditable));
};
-// Mirror of CLEAN_LEVELS in server/routes/imageClean.js. If the server adds a
-// new level, drop a label here and the pill renders automatically.
-const CLEAN_LEVEL_LABELS = { light: 'Light', aggressive: 'Aggressive' };
+const CLEAN_TOOLTIP = 'Re-encode and denoise: removes the C2PA metadata chunk (when present) and reduces visible AI-generation artifacts. Does NOT defeat SynthID — gpt-image / Imagen / Gemini renders remain detectable by their vendor watermark checkers. Saves a new image alongside the original.';
-// onClean(item, level) — optional. Returning a rejected promise keeps the
-// lightbox open (e.g. on error) so the user can retry.
+// Three lineage cases:
+// - auto-cleaned (replaced in place): "Auto-cleaned (aggressive)"
+// - manually cleaned (sidecar copy): "Cleaned (aggressive) from <orig>"
+// - neither: returns null and the meta row is dropped by the null-filter
+function describeCleanedLineage(item) {
+ if (item.autoCleaned) {
+ return `Auto-cleaned (${item.cleanLevel || 'aggressive'})${item.c2paStripped ? ' · C2PA stripped' : ''}`;
+ }
+ if (item.cleanedFrom) {
+ return `${item.cleanLevel ? `Cleaned (${item.cleanLevel}) ` : 'Cleaned '}from ${item.cleanedFrom}`;
+ }
+ return null;
+}
+
+// onClean(item) — optional. Returning a rejected promise keeps the lightbox
+// open (e.g. on error) so the user can retry.
+//
+// variantGroup — optional `{ active, group: [{ label, item }, ...] }` shape
+// from `computeImageVariantGroup` (in `./variants.js`). When present, the
+// SettingsPane renders a segmented control to swap between the original
+// image and its cleaned copies without closing the modal. `onSelectVariant`
+// is the click handler — typically wired to the host page's `setPreview`.
export default function MediaLightbox({
item,
onClose,
@@ -48,6 +66,8 @@ export default function MediaLightbox({
hasNext = false,
annotation = null,
onAnnotationChange,
+ variantGroup = null,
+ onSelectVariant,
}) {
const [fullScreen, setFullScreen] = useState(false);
const [refineOpen, setRefineOpen] = useState(false);
@@ -113,6 +133,8 @@ export default function MediaLightbox({
// 'canon' / 'variation' / 'sheet' (ENTRY_REF_KIND values) for parity with
// the server contract; users shouldn't see the wire tokens.
const entryKindLabel = ({ canon: 'Canon entry', variation: 'Category variation', sheet: 'Composite sheet' })[item.entryKind] || item.entryKind;
+ const cleanedLabel = describeCleanedLineage(item);
+
const meta = [
// Universe Builder context — placed first so "this is Ash from MyVerse"
// reads before the technical render params. Sidecars without a universe
@@ -132,6 +154,7 @@ export default function MediaLightbox({
// unique-run identifier.
['Seed', item.seed ?? (isCodex ? 'n/a (gpt-image-2)' : null)],
['Codex session', item.codexSessionId],
+ ['Cleaned', cleanedLabel],
['Frames', item.numFrames],
['FPS', item.fps],
['Created', item.createdAt && new Date(item.createdAt).toLocaleString()],
@@ -226,6 +249,8 @@ export default function MediaLightbox({
onRefine={() => setRefineOpen(true)}
annotation={annotation}
onAnnotationChange={onAnnotationChange}
+ variantGroup={variantGroup}
+ onSelectVariant={onSelectVariant}
/>
)}
</div>
@@ -264,9 +289,10 @@ function SettingsPane({
onClose, onRemix, onSendToVideo, onContinue, onClean,
copy, onRefine,
annotation, onAnnotationChange,
+ variantGroup, onSelectVariant,
}) {
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(null);
+ const [cleaning, setCleaning] = useState(false);
const starred = !!annotation?.starred;
// Local draft state debounces saves so each keystroke doesn't PATCH.
// onSaveRef keeps the debounce effect off the parent's render churn —
@@ -403,6 +429,32 @@ function SettingsPane({
</div>
)}
+ {variantGroup && onSelectVariant && (
+ <div>
+ <div className="text-gray-500 uppercase tracking-wide text-xs mb-1">View</div>
+ <div className="flex items-stretch rounded overflow-hidden border border-port-border">
+ {variantGroup.group.map((entry) => {
+ const isActive = entry.item.filename === item.filename;
+ return (
+ <button
+ key={entry.item.filename}
+ type="button"
+ onClick={() => { if (!isActive) onSelectVariant(entry.item); }}
+ aria-pressed={isActive}
+ className={`flex-1 px-2 py-1.5 text-xs border-r border-port-border last:border-r-0 transition-colors ${
+ isActive
+ ? 'bg-port-accent text-white cursor-default'
+ : 'bg-port-bg text-gray-300 hover:text-white hover:bg-port-border/50'
+ }`}
+ >
+ {entry.label}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
{meta.length > 0 && (
<dl className="grid grid-cols-[auto,1fr] gap-x-3 gap-y-1">
{meta.map(([k, v]) => {
@@ -459,39 +511,29 @@ function SettingsPane({
</button>
)}
{!isVideo && onClean && (
- <div
- className="flex items-stretch rounded overflow-hidden border border-port-border"
- role="group"
+ <button
+ type="button"
+ disabled={cleaning}
+ onClick={async () => {
+ if (cleaning) return;
+ setCleaning(true);
+ let ok = false;
+ try {
+ await onClean(item);
+ ok = true;
+ } catch {
+ // Caller toasts its own error; stay open so the user can retry.
+ } finally {
+ setCleaning(false);
+ }
+ if (ok) onClose();
+ }}
+ title={CLEAN_TOOLTIP}
aria-label="Clean image"
+ className="flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs bg-port-warning/80 text-white hover:opacity-90 rounded disabled:opacity-50 disabled:cursor-not-allowed"
>
- <span className="flex items-center gap-1 px-2 py-1.5 text-xs bg-port-border/40 text-gray-300">
- <Eraser className="w-3.5 h-3.5" /> Clean
- </span>
- {Object.entries(CLEAN_LEVEL_LABELS).map(([level, label]) => (
- <button
- key={level}
- type="button"
- disabled={cleaning != null}
- onClick={async () => {
- if (cleaning) return;
- setCleaning(level);
- let ok = false;
- try {
- await onClean(item, level);
- ok = true;
- } catch {
- // Caller toasts its own error; stay open so the user can retry.
- } finally {
- setCleaning(null);
- }
- if (ok) onClose();
- }}
- className={`px-2 py-1.5 text-xs border-l border-port-border text-white hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed ${level === 'aggressive' ? 'bg-port-warning/80' : 'bg-port-border/70'}`}
- >
- {cleaning === level ? '…' : label}
- </button>
- ))}
- </div>
+ <Eraser className="w-3.5 h-3.5" /> {cleaning ? 'Cleaning…' : 'Clean'}
+ </button>
)}
{isVideo && onContinue && (
<button
diff --git a/client/src/components/media/MediaPreview.jsx b/client/src/components/media/MediaPreview.jsx
index 2d6869a815..9106634f76 100644
--- a/client/src/components/media/MediaPreview.jsx
+++ b/client/src/components/media/MediaPreview.jsx
@@ -1,6 +1,7 @@
-import { useMemo } from 'react';
+import { useMemo, useCallback } from 'react';
import MediaLightbox from './MediaLightbox';
import { getMediaNavProps } from '../../lib/mediaNavigation';
+import { computeImageVariantGroup } from './variants';
// Thin wrapper around MediaLightbox that owns the consistent wiring every
// page repeated by hand: open/close, prev/next nav, and the annotation
@@ -24,12 +25,26 @@ export default function MediaPreview({
() => getMediaNavProps(items, preview, setPreview),
[items, preview, setPreview]
);
+ // Original-vs-cleaned toggle. Computed from the same `items` list that
+ // drives prev/next nav — so if the cleaned copy was auto-filed into this
+ // page's source collection, both variants are present and the toggle
+ // appears. Returns null for non-image previews or single-variant items.
+ const variantGroup = useMemo(
+ () => computeImageVariantGroup(preview, items),
+ [preview, items]
+ );
+ const onSelectVariant = useCallback((nextItem) => {
+ if (!nextItem) return;
+ setPreview(nextItem);
+ }, [setPreview]);
return (
<MediaLightbox
item={preview}
onClose={() => setPreview(null)}
annotation={annotations?.[preview?.key] ?? null}
onAnnotationChange={preview && updateAnnotation ? (patch) => updateAnnotation(preview.key, patch) : undefined}
+ variantGroup={variantGroup}
+ onSelectVariant={onSelectVariant}
{...handlers}
{...navProps}
/>
diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.js
index 3221c1740a..0f61141d5d 100644
--- a/client/src/components/media/normalize.js
+++ b/client/src/components/media/normalize.js
@@ -60,6 +60,14 @@ export function normalizeImage(i) {
hidden: !!i.hidden,
extractedFromVideoId: i.extractedFromVideoId || null,
extractedFromVideoFilename: i.extractedFromVideoFilename || null,
+ // Cleaning lineage — stamped by /api/image-gen/:filename/clean (manual,
+ // `cleanedFrom` points at the source) or by the auto-clean post-generation
+ // hook (`autoCleaned: true`, in-place replace). Surfaced in the lightbox
+ // so the user can tell at a glance which version they're looking at.
+ cleanedFrom: i.cleanedFrom || null,
+ cleanLevel: i.cleanLevel || null,
+ autoCleaned: i.autoCleaned === true,
+ c2paStripped: typeof i.c2paStripped === 'boolean' ? i.c2paStripped : null,
raw: i,
};
}
diff --git a/client/src/components/media/variants.js b/client/src/components/media/variants.js
new file mode 100644
index 0000000000..e50ea7b889
--- /dev/null
+++ b/client/src/components/media/variants.js
@@ -0,0 +1,56 @@
+// Group a normalized image item with its cleaned siblings (or its original,
+// if `item` itself is a cleaned copy). Returns `{ active, group }` where
+// `group` is an ordered list of variants — original first, then cleaned
+// copies sorted by clean level / creation order — and `active` is the entry
+// in the group that matches `item`.
+//
+// Returns null when there's no toggle to render: either the items array
+// doesn't contain a sibling, or the preview isn't an image. Both happen on
+// pages where the user hasn't manually cleaned anything; this keeps the
+// lightbox unchanged for the common case.
+//
+// Image variants are identified via the sidecar `cleanedFrom` field —
+// stamped by `POST /api/image-gen/:filename/clean` on the cleaned copy.
+// Auto-cleaned images replace the original in place (`autoCleaned: true`,
+// no `cleanedFrom`) so they're treated as the original, not a sibling — the
+// auto-clean toggle doesn't apply because there IS only one file.
+export function computeImageVariantGroup(item, items) {
+ if (!item || item.kind !== 'image') return null;
+ if (!Array.isArray(items) || items.length === 0) return null;
+
+ // Resolve the original filename: either `item` itself (if it's not a clean)
+ // or its `cleanedFrom` target. We then collect everyone that points back to
+ // that filename.
+ const originalFilename = item.cleanedFrom || item.filename;
+ if (!originalFilename) return null;
+
+ const imageItems = items.filter((i) => i?.kind === 'image' && typeof i.filename === 'string');
+ const original = imageItems.find((i) => i.filename === originalFilename && !i.cleanedFrom) || null;
+ const cleaned = imageItems
+ .filter((i) => i.cleanedFrom === originalFilename)
+ .sort((a, b) => {
+ // Deterministic order: aggressive after light if both exist (legacy on-disk
+ // files may have `_clean-light.png` from before the simplification), then
+ // by createdAt as the final tiebreaker.
+ const levelOrder = { light: 0, aggressive: 1 };
+ const al = levelOrder[a.cleanLevel] ?? 99;
+ const bl = levelOrder[b.cleanLevel] ?? 99;
+ if (al !== bl) return al - bl;
+ return String(a.createdAt || '').localeCompare(String(b.createdAt || ''));
+ });
+
+ // No toggle to render unless we actually have at least two variants the
+ // user can switch between.
+ if ((original ? 1 : 0) + cleaned.length < 2) return null;
+
+ const group = [];
+ if (original) group.push({ label: 'Original', item: original });
+ for (const c of cleaned) {
+ const levelTag = c.cleanLevel ? ` (${c.cleanLevel})` : '';
+ group.push({ label: `Cleaned${levelTag}`, item: c });
+ }
+
+ const active = group.find((entry) => entry.item.filename === item.filename) || null;
+ if (!active) return null;
+ return { active, group };
+}
diff --git a/client/src/components/media/variants.test.js b/client/src/components/media/variants.test.js
new file mode 100644
index 0000000000..97079d7760
--- /dev/null
+++ b/client/src/components/media/variants.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect } from 'vitest';
+import { computeImageVariantGroup } from './variants';
+
+const img = (filename, extra = {}) => ({ kind: 'image', filename, ...extra });
+
+describe('computeImageVariantGroup', () => {
+ it('returns null when item has no sibling in items', () => {
+ const orig = img('a.png');
+ expect(computeImageVariantGroup(orig, [orig])).toBeNull();
+ });
+
+ it('returns null for non-image items (videos do not have clean lineage)', () => {
+ const video = { kind: 'video', filename: 'a.mp4' };
+ const cleaned = img('a_clean-aggressive.png', { cleanedFrom: 'a.mp4' });
+ expect(computeImageVariantGroup(video, [video, cleaned])).toBeNull();
+ });
+
+ it('returns null when items is empty / not an array', () => {
+ expect(computeImageVariantGroup(img('a.png'), [])).toBeNull();
+ expect(computeImageVariantGroup(img('a.png'), null)).toBeNull();
+ });
+
+ it('groups original + one cleaned sibling, active = original', () => {
+ const orig = img('a.png');
+ const cleaned = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive' });
+ const result = computeImageVariantGroup(orig, [orig, cleaned]);
+ expect(result).not.toBeNull();
+ expect(result.group).toEqual([
+ { label: 'Original', item: orig },
+ { label: 'Cleaned (aggressive)', item: cleaned },
+ ]);
+ expect(result.active.item.filename).toBe('a.png');
+ });
+
+ it('groups when the preview IS the cleaned copy, active = cleaned', () => {
+ const orig = img('a.png');
+ const cleaned = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive' });
+ const result = computeImageVariantGroup(cleaned, [orig, cleaned]);
+ expect(result).not.toBeNull();
+ expect(result.active.label).toBe('Cleaned (aggressive)');
+ });
+
+ it('orders light before aggressive when both legacy clean variants exist', () => {
+ const orig = img('a.png');
+ const aggressive = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive' });
+ const light = img('a_clean-light.png', { cleanedFrom: 'a.png', cleanLevel: 'light' });
+ const result = computeImageVariantGroup(orig, [orig, aggressive, light]);
+ expect(result.group.map((g) => g.label)).toEqual([
+ 'Original',
+ 'Cleaned (light)',
+ 'Cleaned (aggressive)',
+ ]);
+ });
+
+ it('omits "Original" entry if the source image is not in the items list (cleaned-only collection)', () => {
+ const cleaned1 = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive' });
+ const cleaned2 = img('a_clean-light.png', { cleanedFrom: 'a.png', cleanLevel: 'light' });
+ const result = computeImageVariantGroup(cleaned1, [cleaned1, cleaned2]);
+ expect(result.group.map((g) => g.label)).toEqual([
+ 'Cleaned (light)',
+ 'Cleaned (aggressive)',
+ ]);
+ });
+
+ it('returns null when only the original exists (no clean siblings yet — no toggle needed)', () => {
+ const orig = img('a.png');
+ const unrelated = img('b.png');
+ expect(computeImageVariantGroup(orig, [orig, unrelated])).toBeNull();
+ });
+
+ it('returns null when the preview filename does not match any group entry', () => {
+ // Defensive: preview was passed but it isn't actually part of the variant
+ // set (e.g. items list was filtered after preview was set). Toggle should
+ // not render rather than mislead with a stale group.
+ const orig = img('a.png');
+ const cleaned = img('a_clean-aggressive.png', { cleanedFrom: 'a.png', cleanLevel: 'aggressive' });
+ const other = img('c.png'); // preview pointing at an unrelated image
+ expect(computeImageVariantGroup(other, [orig, cleaned, other])).toBeNull();
+ });
+});
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index b0ee73787e..d579293025 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -47,6 +47,15 @@ export function ImageGenTab() {
const [codexPath, setCodexPath] = useState('');
const [codexModel, setCodexModel] = useState('');
const [codexParallelLimit, setCodexParallelLimit] = useState(1);
+ // Auto-clean toggles — per-provider so users can opt in selectively. The
+ // clean runs after the PNG lands and before the SSE complete event so
+ // subscribers see the cleaned bytes. Scope: removes the C2PA metadata chunk
+ // (when present) and reduces visible AI-generation artifacts via a median
+ // pass + sharpen. Does NOT defeat SynthID — gpt-image embeds SynthID and our
+ // median+sharpen+re-encode falls inside Google's stated robustness envelope.
+ const [autoCleanCodex, setAutoCleanCodex] = useState(false);
+ const [autoCleanLocal, setAutoCleanLocal] = useState(false);
+ const [autoCleanExternal, setAutoCleanExternal] = useState(false);
// Raw string held while the user is typing in the parallel-limit input.
// Clamping is deferred to onBlur so multi-digit entry isn't blocked.
const [parallelLimitDraft, setParallelLimitDraft] = useState('1');
@@ -64,6 +73,7 @@ export function ImageGenTab() {
const [saved, setSaved] = useState({
mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false,
codexEnabled: false, codexPath: '', codexModel: '', codexParallelLimit: 1,
+ autoCleanCodex: false, autoCleanLocal: false, autoCleanExternal: false,
});
const [status, setStatus] = useState(null);
@@ -136,6 +146,9 @@ export function ImageGenTab() {
: PARALLEL_FALLBACK;
setParallelBounds(bounds);
const cxParallel = clampParallel(cx.parallelLimit, bounds);
+ const acCodex = cx.autoClean === true;
+ const acLocal = ig.local?.autoClean === true;
+ const acExternal = ig.external?.autoClean === true;
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -145,10 +158,14 @@ export function ImageGenTab() {
setCodexModel(cxModel);
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
+ setAutoCleanCodex(acCodex);
+ setAutoCleanLocal(acLocal);
+ setAutoCleanExternal(acExternal);
setSaved({
mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel,
codexParallelLimit: cxParallel,
+ autoCleanCodex: acCodex, autoCleanLocal: acLocal, autoCleanExternal: acExternal,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -172,7 +189,10 @@ export function ImageGenTab() {
|| codexEnabled !== saved.codexEnabled
|| codexPath !== saved.codexPath
|| codexModel !== saved.codexModel
- || codexParallelLimit !== saved.codexParallelLimit;
+ || codexParallelLimit !== saved.codexParallelLimit
+ || autoCleanCodex !== saved.autoCleanCodex
+ || autoCleanLocal !== saved.autoCleanLocal
+ || autoCleanExternal !== saved.autoCleanExternal;
const handleSave = async () => {
setSaving(true);
@@ -183,9 +203,12 @@ export function ImageGenTab() {
const patch = {
imageGen: {
mode,
- external: { sdapiUrl: url },
- local: { pythonPath: pythonPath || undefined },
- codex: { enabled: codexEnabled, codexPath: cxPath, model: cxModel, parallelLimit: cxParallel },
+ external: { sdapiUrl: url, autoClean: autoCleanExternal },
+ local: { pythonPath: pythonPath || undefined, autoClean: autoCleanLocal },
+ codex: {
+ enabled: codexEnabled, codexPath: cxPath, model: cxModel, parallelLimit: cxParallel,
+ autoClean: autoCleanCodex,
+ },
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
// `imageGen.sdapiUrl` directly stays working.
@@ -202,6 +225,7 @@ export function ImageGenTab() {
mode, sdapiUrl: url || '', pythonPath, exposeA1111,
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '',
codexParallelLimit: cxParallel,
+ autoCleanCodex, autoCleanLocal, autoCleanExternal,
});
if (cxParallel !== codexParallelLimit) {
setCodexParallelLimit(cxParallel);
@@ -402,6 +426,7 @@ export function ImageGenTab() {
placeholder="http://localhost:7860"
/>
<p className="text-xs text-gray-500">Base URL for the SD WebUI server PortOS should send generation requests to.</p>
+ <AutoCleanToggle checked={autoCleanExternal} onChange={setAutoCleanExternal} />
</div>
)}
@@ -415,6 +440,7 @@ export function ImageGenTab() {
and are surfaced in <a href="/media/models" className="text-port-accent hover:underline">Media → Models</a>.
</p>
<LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} />
+ <AutoCleanToggle checked={autoCleanLocal} onChange={setAutoCleanLocal} />
</div>
)}
@@ -510,6 +536,7 @@ export function ImageGenTab() {
)}
</p>
</div>
+ <AutoCleanToggle checked={autoCleanCodex} onChange={setAutoCleanCodex} />
</div>
)}
</div>
@@ -713,4 +740,29 @@ export function ImageGenTab() {
);
}
+// Shared per-provider "auto-clean after generation" checkbox. The user-visible
+// helper text below already explains scope (C2PA removed, SynthID not
+// defeated) so the comment doesn't need to repeat it. Ordering invariant:
+// the clean must run before the SSE complete event fires so subscribers see
+// the cleaned bytes on first fetch — enforced by the provider success paths,
+// not here.
+function AutoCleanToggle({ checked, onChange }) {
+ return (
+ <label className="flex items-start gap-3 cursor-pointer pt-1">
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={(e) => onChange(e.target.checked)}
+ className="rounded mt-0.5"
+ />
+ <span className="text-sm text-gray-300">
+ Auto-clean after generation
+ <span className="block text-xs text-gray-500 mt-0.5">
+ Remove the C2PA metadata chunk (when present) and reduce visible AI-generation artifacts on every render. Does NOT defeat SynthID — gpt-image / Imagen renders stay detectable by their vendor watermark checkers. The cleaned image replaces the original on disk.
+ </span>
+ </span>
+ </label>
+ );
+}
+
export default ImageGenTab;
diff --git a/client/src/hooks/useImagePreviewActions.js b/client/src/hooks/useImagePreviewActions.js
index b2b54b5bb3..51f94d8ae5 100644
--- a/client/src/hooks/useImagePreviewActions.js
+++ b/client/src/hooks/useImagePreviewActions.js
@@ -17,7 +17,7 @@ import { cleanGalleryImage, extractLastFrame } from '../services/apiImageVideo';
* prepend vs. ignore) — supplied via `onCleanComplete`.
*
* @param {object} [options]
- * @param {(cleaned: object, level: string) => any | Promise<any>} [options.onCleanComplete]
+ * @param {(cleaned: object) => any | Promise<any>} [options.onCleanComplete]
* Fires AFTER `cleanGalleryImage` resolves. Use it to splice the cleaned
* image into the consumer's local state (collection items, gallery list,
* variation imageRefs, etc.). Errors thrown from the callback bubble.
@@ -79,20 +79,20 @@ export default function useImagePreviewActions({ onCleanComplete = null } = {})
navigate(`/media/video?${params}`);
}, [navigate]);
- // Clean: send to the SDAPI background-cleaner endpoint (`light` /
- // `aggressive`). Returns the resulting gallery item so consumers can
- // splice it into local state. `onCleanComplete` is the consumer-specific
- // post-step (add-to-collection / prepend-to-history / etc.) — fired
- // AFTER the success toast so a failing post-step still shows the user
- // the clean succeeded server-side.
- const handleClean = useCallback(async (img, level) => {
+ // Clean: re-encode + denoise via the gallery clean endpoint to strip C2PA
+ // provenance and reduce AI artifacts. Returns the resulting gallery item so
+ // consumers can splice it into local state. `onCleanComplete` is the
+ // consumer-specific post-step (add-to-collection / prepend-to-history /
+ // etc.) — fired AFTER the success toast so a failing post-step still shows
+ // the user the clean succeeded server-side.
+ const handleClean = useCallback(async (img) => {
if (!img?.filename) throw new Error('Missing filename');
- const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {
+ const cleaned = await cleanGalleryImage(img.filename).catch((err) => {
toast.error(err.message || 'Failed to clean image');
throw err;
});
- toast.success(`Cleaned (${level}) → ${cleaned.filename}`);
- if (onCleanComplete) await onCleanComplete(cleaned, level);
+ toast.success(`Cleaned → ${cleaned.filename}`);
+ if (onCleanComplete) await onCleanComplete(cleaned);
return cleaned;
}, [onCleanComplete]);
diff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsx
index 90b6a2d2ec..dc734c7a29 100644
--- a/client/src/pages/ImageClean.jsx
+++ b/client/src/pages/ImageClean.jsx
@@ -9,12 +9,10 @@ import { readFileAsBase64 } from '../utils/fileUpload';
// Keep aligned with MAX_INPUT_BYTES in server/routes/imageClean.js — both are
// sized so the base64+JSON envelope fits under the 55mb body parser cap.
const MAX_BYTES = 40 * 1024 * 1024;
-const CLEAN_LEVELS = ['light', 'aggressive'];
const ALLOWED_EXT = /\.(png|jpe?g|webp)$/i;
const ALLOWED_MIME = /^image\/(png|jpe?g|webp)$/i;
export default function ImageClean() {
- const [level, setLevel] = useState('light');
const [original, setOriginal] = useState(null); // { previewUrl, base64, size, name }
const [result, setResult] = useState(null);
const [busy, setBusy] = useState(false);
@@ -23,11 +21,6 @@ export default function ImageClean() {
const requestIdRef = useRef(0);
const previewUrlRef = useRef(null);
const resultUrlRef = useRef(null);
- // Mirror `level` so handleFile can read the user's CURRENT choice after the
- // readFileAsBase64 await — otherwise the closure captures the level at the
- // moment the upload started and a mid-read level switch would be ignored.
- const levelRef = useRef(level);
- useEffect(() => { levelRef.current = level; }, [level]);
// Revoke any outstanding blob URL on unmount so we don't leak.
useEffect(() => () => {
@@ -45,7 +38,7 @@ export default function ImageClean() {
return URL.createObjectURL(blob);
};
- const runClean = useCallback(async (base64, lvl) => {
+ const runClean = useCallback(async (base64) => {
const myRequestId = ++requestIdRef.current;
setBusy(true);
if (resultUrlRef.current) {
@@ -53,7 +46,7 @@ export default function ImageClean() {
resultUrlRef.current = null;
}
setResult(null);
- const cleaned = await api.cleanImage(base64, lvl).catch((err) => {
+ const cleaned = await api.cleanImage(base64).catch((err) => {
toast.error(err.message || 'Failed to clean image');
return null;
});
@@ -80,7 +73,7 @@ export default function ImageClean() {
// alongside the blob URL would double the in-memory image footprint.
const { data: _omit, ...meta } = cleaned;
setResult({ ...meta, objectUrl });
- toast.success(cleaned.c2paStripped ? 'C2PA provenance stripped' : 'Image cleaned');
+ toast.success(cleaned.c2paStripped ? 'C2PA chunk removed' : 'Image cleaned (no C2PA chunk found)');
}, []);
const handleFile = async (file) => {
@@ -120,12 +113,7 @@ export default function ImageClean() {
size: file.size,
name: file.name,
});
- runClean(base64, levelRef.current);
- };
-
- const handleLevelChange = (newLevel) => {
- setLevel(newLevel);
- if (original?.base64) runClean(original.base64, newLevel);
+ runClean(base64);
};
const handleDrag = (e) => {
@@ -183,34 +171,20 @@ export default function ImageClean() {
Image Cleaner
</h2>
<p className="text-gray-500 text-sm">
- Strip C2PA provenance + median-filter pixel noise from gpt-image / Codex output.
+ Removes the C2PA metadata chunk (when present) and reduces visible AI-generation artifacts via a median pass + sharpen.
+ </p>
+ <p className="text-gray-500 text-xs mt-1">
+ <span className="text-port-warning">Note:</span>{' '}
+ does NOT defeat SynthID. gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers
+ (e.g.{' '}
+ <a href="https://openai.com/synthid" target="_blank" rel="noopener noreferrer" className="text-port-accent hover:underline">
+ openai.com/synthid
+ </a>
+ ) after a clean — SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode.
</p>
</div>
</div>
- <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col sm:flex-row sm:items-center gap-3">
- <span className="text-sm text-gray-400">Cleaning level</span>
- <div className="flex gap-2">
- {CLEAN_LEVELS.map((opt) => (
- <button
- key={opt}
- type="button"
- onClick={() => handleLevelChange(opt)}
- className={`px-3 py-1.5 rounded-lg text-sm transition-colors capitalize ${
- level === opt
- ? 'bg-port-accent text-white'
- : 'bg-port-bg border border-port-border text-gray-400 hover:text-white'
- }`}
- >
- {opt}
- </button>
- ))}
- </div>
- <span className="text-xs text-gray-600 sm:ml-auto">
- {level === 'light' ? 'median(1)' : 'median(3) + sharpen'}
- </span>
- </div>
-
{!original && (
<div
className={`relative p-12 border-2 border-dashed rounded-lg text-center transition-colors ${
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index 670d547c54..e179c9f33e 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -151,6 +151,15 @@ export default function ImageGen() {
// async modes (local + codex); external is synchronous and runs N=1.
const [batchCount, setBatchCount] = useState(1);
+ // Per-render auto-clean override. Seeded from
+ // `settings.imageGen.{mode}.autoClean` whenever the active mode changes;
+ // the user can flip the checkbox to override the saved default for this
+ // submit. The server's /generate route stamps the resolved value into the
+ // payload so all three dispatch paths (external sync, codex queue, local
+ // queue) see the same boolean.
+ const [autoClean, setAutoClean] = useState(false);
+ const [savedAutoCleanByMode, setSavedAutoCleanByMode] = useState({});
+
const [generating, setGenerating] = useState(false);
const [statusMsg, setStatusMsg] = useState('');
const [errorMeta, setErrorMeta] = useState(null); // { kind, repo } for typed-error guidance
@@ -233,9 +242,22 @@ export default function ImageGen() {
if (backends.length) return backends[0].id;
return saved;
});
+ setSavedAutoCleanByMode({
+ external: s?.imageGen?.external?.autoClean === true,
+ local: s?.imageGen?.local?.autoClean === true,
+ codex: s?.imageGen?.codex?.autoClean === true,
+ });
}).catch(() => {});
}, []);
+ // Re-seed the autoClean checkbox whenever the effective mode changes (mode
+ // switch OR settings refresh). Without this, a user who flips from external
+ // to local would still see the external autoClean value in the form.
+ useEffect(() => {
+ if (Object.keys(savedAutoCleanByMode).length === 0) return;
+ setAutoClean(savedAutoCleanByMode[effectiveMode] === true);
+ }, [effectiveMode, savedAutoCleanByMode]);
+
useEffect(() => {
listImageModels().then((m) => {
setModels(m);
@@ -481,8 +503,11 @@ export default function ImageGen() {
// Lazy-fetch HF token presence for legacy mflux gated models (FLUX.1-dev).
// FLUX.2 has its own combined status fetch above (which also covers the
- // venv install), so skip the duplicate request when isFlux2Model.
- const needsHfTokenGate = !!currentModel?.requiresHfToken && !isFlux2Model;
+ // venv install), so skip the duplicate request when isFlux2Model. The
+ // `isLocalMode` gate is the important one: codex + external don't run mflux,
+ // so a stale Flux modelId left in state from a prior local session must not
+ // surface the HF banner under those backends.
+ const needsHfTokenGate = isLocalMode && !!currentModel?.requiresHfToken && !isFlux2Model;
useEffect(() => {
if (!needsHfTokenGate) { setHfTokenPresent(null); return; }
const controller = new AbortController();
@@ -554,6 +579,7 @@ export default function ImageGen() {
negativePrompt: composed.negativePrompt || undefined,
width, height,
mode: 'codex',
+ autoClean,
} : {
prompt: composed.prompt,
negativePrompt: composed.negativePrompt || undefined,
@@ -566,6 +592,7 @@ export default function ImageGen() {
loraFilenames: selectedLoras.map((l) => l.filename),
loraScales: selectedLoras.map((l) => l.scale),
mode: 'local',
+ autoClean,
};
const hasInitImage = isLocalMode && initImage.source != null;
// Multi-reference editing is FLUX.2-only; gate the slot read so it can't
@@ -709,6 +736,7 @@ export default function ImageGen() {
steps: steps ? Number(steps) : 25,
cfgScale,
mode: 'external',
+ autoClean,
};
if (seed && Number(seed) >= 0) payload.seed = Number(seed);
const data = await generateImage(payload);
@@ -758,14 +786,14 @@ export default function ImageGen() {
if (result) toast.success(nextHidden ? 'Image hidden' : 'Image unhidden');
};
- const handleClean = async (img, level) => {
+ const handleClean = async (img) => {
if (!img?.filename) throw new Error('Missing filename');
- const cleaned = await cleanGalleryImage(img.filename, level).catch((err) => {
+ const cleaned = await cleanGalleryImage(img.filename).catch((err) => {
toast.error(err.message || 'Failed to clean image');
throw err;
});
setGallery((g) => [cleaned, ...g.filter((x) => x.filename !== cleaned.filename)]);
- toast.success(`Cleaned (${level}) → ${cleaned.filename}`);
+ toast.success(`Cleaned → ${cleaned.filename}`);
};
const sendToVideo = (img) => {
@@ -1133,6 +1161,24 @@ export default function ImageGen() {
)}
</div>
+ <label
+ className="flex items-center gap-2 text-xs text-gray-400 cursor-pointer select-none"
+ title="Re-encode + denoise this render in place: removes the C2PA metadata chunk (when present) and reduces visible AI artifacts. Does NOT defeat SynthID — gpt-image renders stay detectable by openai.com/synthid after a clean. Overrides the saved Settings → Image Gen default for this generation only."
+ >
+ <input
+ type="checkbox"
+ checked={autoClean}
+ onChange={(e) => setAutoClean(e.target.checked)}
+ className="rounded"
+ />
+ <span>
+ Auto-clean this render
+ {savedAutoCleanByMode[effectiveMode] !== undefined && autoClean !== savedAutoCleanByMode[effectiveMode] && (
+ <span className="ml-1 text-port-warning">(overrides saved default)</span>
+ )}
+ </span>
+ </label>
+
{error && (
<div className="rounded-lg border border-port-error/40 bg-port-error/10 px-3 py-3 text-xs text-port-error space-y-2">
<div className="font-semibold text-sm">
@@ -1293,7 +1339,7 @@ export default function ImageGen() {
updateAnnotation={updateAnnotation}
onRemix={(item) => item?.raw && handleRemix(item.raw)}
onSendToVideo={(item) => item?.raw?.filename && sendToVideo(item.raw)}
- onClean={(item, level) => handleClean(item?.raw, level)}
+ onClean={(item) => handleClean(item?.raw)}
/>
diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsx
index 345f42b283..dc06191f33 100644
--- a/client/src/pages/MediaCollectionDetail.jsx
+++ b/client/src/pages/MediaCollectionDetail.jsx
@@ -508,7 +508,7 @@ export default function MediaCollectionDetail() {
onRemix={handleRemix}
onSendToVideo={handleSendToVideo}
onContinue={(i) => handleContinue(i.raw || i)}
- onClean={(i, level) => handleClean(i?.raw || i, level)}
+ onClean={(i) => handleClean(i?.raw || i)}
/>
</div>
);
diff --git a/client/src/pages/MediaHistory.jsx b/client/src/pages/MediaHistory.jsx
index 8e3c1d707d..666f6fab3b 100644
--- a/client/src/pages/MediaHistory.jsx
+++ b/client/src/pages/MediaHistory.jsx
@@ -299,7 +299,7 @@ export default function MediaHistory() {
onRemix={handleRemix}
onSendToVideo={handleSendToVideo}
onContinue={handleContinue}
- onClean={(item, level) => handleClean(item?.raw, level)}
+ onClean={(item) => handleClean(item?.raw)}
/>
</div>
);
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 51bb9c8263..722f905d98 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -2205,7 +2205,7 @@ export default function UniverseBuilder() {
updateAnnotation={updateAnnotation}
onRemix={previewActions.handleRemix}
onSendToVideo={previewActions.handleSendToVideo}
- onClean={(item, level) => previewActions.handleClean(item?.raw || item, level)}
+ onClean={(item) => previewActions.handleClean(item?.raw || item)}
onContinue={(item) => previewActions.handleContinue(item?.raw || item)}
/>
</div>
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 67e384484f..ff13e019fc 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -19,9 +19,9 @@ export const setImageHidden = (filename, hidden) => request(`/image-gen/${encode
method: 'POST',
body: JSON.stringify({ hidden }),
});
-export const cleanGalleryImage = (filename, level = 'light') => request(`/image-gen/${encodeURIComponent(filename)}/clean`, {
+export const cleanGalleryImage = (filename) => request(`/image-gen/${encodeURIComponent(filename)}/clean`, {
method: 'POST',
- body: JSON.stringify({ level }),
+ body: JSON.stringify({}),
});
// HuggingFace token (gated local Flux models). Stored in settings.imageGen.hfToken;
diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.js
index a7624d587f..e12fb63211 100644
--- a/client/src/services/apiMedia.js
+++ b/client/src/services/apiMedia.js
@@ -28,8 +28,8 @@ export const deleteAllUploads = () => request('/uploads?confirm=true', { method:
// Image Cleaner — strips C2PA provenance + median-filters AI-generated noise.
// silent: true so the page can render its own error toast without duplicating
// the one apiCore.request() fires by default.
-export const cleanImage = (base64Data, level = 'light') => request('/image-clean', {
+export const cleanImage = (base64Data) => request('/image-clean', {
method: 'POST',
silent: true,
- body: JSON.stringify({ data: base64Data, level })
+ body: JSON.stringify({ data: base64Data })
});
diff --git a/server/lib/README.md b/server/lib/README.md
index 1e70675a04..75ab9b5ba8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -81,6 +81,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
+| `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `multipart.js` | Streaming multipart/form-data parser. |
| `pdfImageEmbed.js` | PDF image embed helpers for comic / volume PDFs. |
| `zipStream.js` | Streaming ZIP parser. |
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index da067cd323..6c138e802f 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -132,7 +132,9 @@ export async function ensureDirs(dirs) {
* await atomicWrite(LOG_FILE, 'raw string content');
*/
export async function atomicWrite(filePath, data) {
- const payload = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
+ // Buffer must pass through unchanged — JSON.stringify on a Buffer produces
+ // `{"type":"Buffer","data":[...]}` which corrupts binary writes (PNG, etc.).
+ const payload = typeof data === 'string' || Buffer.isBuffer(data) ? data : JSON.stringify(data, null, 2);
await ensureDir(dirname(filePath));
const tmp = `${filePath}.${process.pid}.${Date.now()}.${randomUUID()}.tmp`;
await writeFile(tmp, payload);
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
new file mode 100644
index 0000000000..8ba75cdf73
--- /dev/null
+++ b/server/lib/imageClean.js
@@ -0,0 +1,212 @@
+// Image cleaning primitives — removes the C2PA `caBX` metadata chunk (when
+// present) and runs a median(3) + sharpen pass to reduce visible AI-generation
+// artifacts on gpt-image / FLUX output. Lives in lib/ (not routes/) so services
+// can call it without crossing the routes→services dependency direction. The
+// HTTP route in `server/routes/imageClean.js` is a thin wrapper that just
+// imports `cleanImageBuffer` from here.
+//
+// Scope caveat: this is NOT a watermark stripper. SynthID (used by gpt-image,
+// Imagen, Gemini) is embedded in pixel values and Google's published claims
+// state it survives median filters, sharpen, and re-encode by design — cleaned
+// gpt-image renders remain detectable by openai.com/synthid. Keep UI copy
+// honest about that distinction.
+
+import sharp from 'sharp';
+import { readFile } from 'fs/promises';
+import { basename } from 'node:path';
+import { ServerError } from './errorHandler.js';
+import { tryReadFile, safeJSONParse, atomicWrite } from './fileUtils.js';
+
+// All sizes here are MiB (1024*1024). 40 MiB decoded → ~53.3 MiB base64 (4*ceil(n/3))
+// + small JSON envelope, which fits under the 55mb (= 55 MiB) body parser limit
+// in server/index.js. Keep these aligned — raising the decoded cap requires
+// raising the body parser limit too.
+export const MAX_INPUT_BYTES = 40 * 1024 * 1024;
+// Reject oversized payloads before allocating the decoded Buffer.
+export const MAX_BASE64_CHARS = Math.ceil((MAX_INPUT_BYTES * 4) / 3) + 4;
+// Cap decoded pixel count to prevent decompression-bomb images: a small payload
+// can declare gigantic dimensions and OOM the process during sharp decode. ~96MP
+// covers reasonable photos (12000×8000) without allowing pathological inputs.
+const MAX_PIXELS = 96 * 1000 * 1000;
+
+// Exported as a single-value array so the Zod enum shape stays stable if a
+// future variant is added.
+export const CLEAN_LEVELS = ['aggressive'];
+
+// Magic-byte sniff so we re-encode as the source format and emit the right
+// MIME type — extension/header is supplied by the client and not trustworthy.
+function detectFormat(buf) {
+ if (buf.length >= 8 &&
+ buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
+ return 'png';
+ }
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
+ return 'jpeg';
+ }
+ if (buf.length >= 12 &&
+ buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
+ buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
+ return 'webp';
+ }
+ return null;
+}
+
+// PNG chunk type bytes must be ASCII letters per the PNG spec (RFC 2083 §3.2).
+// Validating this lets us bail out of the walker on garbage payloads that
+// happen to start with the PNG signature, instead of looping millions of times.
+function isPngChunkType(buf, offset) {
+ for (let i = 0; i < 4; i++) {
+ const b = buf[offset + i];
+ if (!((b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a))) return false;
+ }
+ return true;
+}
+
+// Real PNGs have well under 50 chunks. Cap the walk so a buffer crafted with
+// the PNG signature followed by many tiny ASCII-typed zero-length chunks can't
+// force millions of iterations at the 40MiB input limit.
+const MAX_PNG_CHUNKS = 10000;
+
+// Walks PNG chunks once for the `caBX` provenance chunk emitted by gpt-image.
+// Sharp's default re-encode drops it; we detect it explicitly so the response
+// can flag what was stripped. Bails on invalid chunk type, truncated chunk, or
+// chunk-count overrun — a buffer that only matches the PNG signature but is
+// otherwise garbage could otherwise trigger millions of loop iterations
+// (CPU/event-loop DoS).
+function pngHasC2PA(buf) {
+ let offset = 8;
+ let count = 0;
+ while (offset + 8 <= buf.length) {
+ if (++count > MAX_PNG_CHUNKS) return false;
+ if (!isPngChunkType(buf, offset + 4)) return false;
+ const length = buf.readUInt32BE(offset);
+ if (offset + 8 + length + 4 > buf.length) return false;
+ const type = buf.toString('ascii', offset + 4, offset + 8);
+ if (type === 'caBX') return true;
+ if (type === 'IEND') return false;
+ offset += 8 + length + 4;
+ }
+ return false;
+}
+
+const MIME_TYPES = {
+ png: 'image/png',
+ jpeg: 'image/jpeg',
+ webp: 'image/webp',
+};
+
+function applyDenoise(pipeline) {
+ return pipeline.median(3).sharpen();
+}
+
+function applyEncoder(pipeline, format) {
+ if (format === 'png') return pipeline.png({ compressionLevel: 9 });
+ if (format === 'jpeg') return pipeline.jpeg({ quality: 92, mozjpeg: true });
+ return pipeline.webp({ quality: 92 });
+}
+
+// Throws ServerError (400) on invalid input so callers get a consistent
+// status instead of a sharp stack trace surfacing as a 500.
+export async function cleanImageBuffer(buffer) {
+ if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
+ throw new ServerError('Decoded payload is empty', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ if (buffer.length > MAX_INPUT_BYTES) {
+ throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {
+ status: 400,
+ code: 'FILE_TOO_LARGE',
+ });
+ }
+
+ const format = detectFormat(buffer);
+ if (!format) {
+ throw new ServerError('Unsupported image format (expected PNG, JPEG, or WebP)', {
+ status: 400,
+ code: 'UNSUPPORTED_FORMAT',
+ });
+ }
+
+ const c2paStripped = format === 'png' && pngHasC2PA(buffer);
+
+ // Single decode for both EXIF auto-orient + denoise/encode. .rotate() with no
+ // args applies the EXIF Orientation tag so the cleaned pixels match what the
+ // browser showed in the Before preview (browsers honor EXIF orientation but
+ // sharp does not by default). resolveWithObject gives us output dimensions
+ // (post-rotation), avoiding a second decode for metadata.
+ const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
+ try {
+ const { data, info } = await applyEncoder(applyDenoise(base), format)
+ .toBuffer({ resolveWithObject: true });
+ return {
+ data,
+ format,
+ mimeType: MIME_TYPES[format],
+ sizeBefore: buffer.length,
+ sizeAfter: data.length,
+ width: info.width || null,
+ height: info.height || null,
+ c2paStripped,
+ };
+ } catch (err) {
+ // Wrap sharp errors (truncated/corrupt buffer that still passed the
+ // magic-byte sniff) into a 400 so bad input doesn't surface as a 500.
+ throw new ServerError('Invalid or corrupt image', {
+ status: 400,
+ code: 'INVALID_IMAGE',
+ context: { details: { format, reason: err.message } },
+ });
+ }
+}
+
+// Post-generation auto-clean. Reads the just-written PNG, runs cleanImageBuffer,
+// atomically replaces the file in place via temp + rename, and patches the
+// sidecar to record the clean (`autoCleaned: true`, `cleanLevel: 'aggressive'`,
+// `c2paStripped: bool`). No-op when `enabled` is false. Logs and swallows
+// errors — a clean failure must never fail the underlying generation (the
+// un-cleaned PNG stays on disk and the user gets what they would have gotten
+// without the feature).
+//
+// `mode` is one of 'codex' | 'local' | 'external' — only used in log lines so
+// failures are attributable. The caller (the image-gen dispatcher) is
+// responsible for resolving `enabled` from `settings.imageGen[mode].autoClean`
+// — this keeps the helper decoupled from the settings shape.
+export async function autoCleanGeneratedImage({ enabled, pngPath, sidecarPath, mode = 'unknown' }) {
+ if (!enabled) return { cleaned: false };
+
+ const buffer = await readFile(pngPath).catch(() => null);
+ if (!buffer) {
+ console.warn(`⚠️ Auto-clean skipped (source missing): ${pngPath}`);
+ return { cleaned: false };
+ }
+
+ const result = await cleanImageBuffer(buffer).catch((err) => {
+ console.warn(`⚠️ Auto-clean failed for ${basename(pngPath)}: ${err?.message || err}`);
+ return null;
+ });
+ if (!result || result.format !== 'png') return { cleaned: false };
+
+ const replaced = await atomicWrite(pngPath, result.data)
+ .then(() => true)
+ .catch((err) => {
+ console.warn(`⚠️ Auto-clean write failed for ${basename(pngPath)}: ${err?.message || err}`);
+ return false;
+ });
+ if (!replaced) return { cleaned: false };
+
+ // Best-effort sidecar patch — a missing sidecar is fine, the clean still
+ // happened. Merge so other fields aren't dropped.
+ if (sidecarPath) {
+ const raw = await tryReadFile(sidecarPath);
+ const patched = {
+ ...safeJSONParse(raw, {}),
+ autoCleaned: true,
+ cleanLevel: 'aggressive',
+ c2paStripped: result.c2paStripped,
+ };
+ await atomicWrite(sidecarPath, patched).catch(() => {});
+ }
+
+ console.log(`🧼 Auto-cleaned ${basename(pngPath)} (mode=${mode}, ${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped})`);
+ return { cleaned: true, c2paStripped: result.c2paStripped };
+}
diff --git a/server/lib/imageClean.test.js b/server/lib/imageClean.test.js
new file mode 100644
index 0000000000..b2346d5a8a
--- /dev/null
+++ b/server/lib/imageClean.test.js
@@ -0,0 +1,131 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
+import { mkdtemp, rm, writeFile, readFile, stat } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import sharp from 'sharp';
+import { autoCleanGeneratedImage } from './imageClean.js';
+
+let sandbox;
+let pngFixture;
+
+beforeAll(async () => {
+ sandbox = await mkdtemp(join(tmpdir(), 'portos-autoclean-'));
+ // Noisy 32×32 RGB — large enough that sharp's median+sharpen passes don't
+ // produce zero-byte output, small enough that tests stay fast.
+ const raw = Buffer.alloc(32 * 32 * 3);
+ for (let i = 0; i < raw.length; i += 1) raw[i] = (i * 73 + 11) % 256;
+ pngFixture = await sharp(raw, { raw: { width: 32, height: 32, channels: 3 } })
+ .png()
+ .toBuffer();
+});
+
+afterAll(async () => {
+ await rm(sandbox, { recursive: true, force: true });
+});
+
+describe('autoCleanGeneratedImage', () => {
+ let pngPath;
+ let sidecarPath;
+
+ beforeEach(async () => {
+ // Unique filenames per test so they don't see each other's leftovers.
+ const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ pngPath = join(sandbox, `${id}.png`);
+ sidecarPath = join(sandbox, `${id}.metadata.json`);
+ await writeFile(pngPath, pngFixture);
+ await writeFile(sidecarPath, JSON.stringify({
+ prompt: 'a noisy fixture', seed: 42, modelId: 'fixture',
+ }));
+ });
+
+ it('no-ops when enabled=false (file + sidecar untouched)', async () => {
+ const beforeBytes = await readFile(pngPath);
+ const beforeSidecar = await readFile(sidecarPath, 'utf-8');
+ const result = await autoCleanGeneratedImage({
+ enabled: false, pngPath, sidecarPath, mode: 'local',
+ });
+ expect(result.cleaned).toBe(false);
+ expect((await readFile(pngPath)).equals(beforeBytes)).toBe(true);
+ expect(await readFile(sidecarPath, 'utf-8')).toBe(beforeSidecar);
+ });
+
+ it('replaces the PNG in place and patches the sidecar when enabled=true', async () => {
+ const beforeBytes = await readFile(pngPath);
+ const result = await autoCleanGeneratedImage({
+ enabled: true, pngPath, sidecarPath, mode: 'local',
+ });
+ expect(result.cleaned).toBe(true);
+
+ // Bytes changed — sharp's median(3).sharpen() on a noisy fixture must
+ // produce a different output than the source.
+ const afterBytes = await readFile(pngPath);
+ expect(afterBytes.equals(beforeBytes)).toBe(false);
+
+ // Sidecar gets autoCleaned + cleanLevel + c2paStripped, AND keeps the
+ // pre-existing fields (lineage preserved).
+ const sidecar = JSON.parse(await readFile(sidecarPath, 'utf-8'));
+ expect(sidecar.autoCleaned).toBe(true);
+ expect(sidecar.cleanLevel).toBe('aggressive');
+ expect(typeof sidecar.c2paStripped).toBe('boolean');
+ expect(sidecar.prompt).toBe('a noisy fixture');
+ expect(sidecar.seed).toBe(42);
+ });
+
+ it('still cleans the PNG when sidecarPath is null (external mode has no sidecar)', async () => {
+ const beforeBytes = await readFile(pngPath);
+ const result = await autoCleanGeneratedImage({
+ enabled: true, pngPath, sidecarPath: null, mode: 'external',
+ });
+ expect(result.cleaned).toBe(true);
+ expect((await readFile(pngPath)).equals(beforeBytes)).toBe(false);
+ });
+
+ it('returns cleaned=false (no throw) when the source file is missing', async () => {
+ const result = await autoCleanGeneratedImage({
+ enabled: true, pngPath: join(sandbox, 'does-not-exist.png'),
+ sidecarPath: null, mode: 'local',
+ });
+ expect(result.cleaned).toBe(false);
+ });
+
+ it('returns cleaned=false (no throw) when the source file is corrupt', async () => {
+ const corruptPath = join(sandbox, 'corrupt.png');
+ // PNG magic byte followed by garbage — passes detectFormat but breaks sharp.
+ await writeFile(corruptPath, Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.alloc(64),
+ ]));
+ const result = await autoCleanGeneratedImage({
+ enabled: true, pngPath: corruptPath, sidecarPath: null, mode: 'codex',
+ });
+ expect(result.cleaned).toBe(false);
+ // The corrupt file stays exactly as-is — no half-written tmp left behind.
+ expect(existsSync(corruptPath)).toBe(true);
+ });
+
+ it('cleans atomically: a temp file is not left behind on success', async () => {
+ await autoCleanGeneratedImage({
+ enabled: true, pngPath, sidecarPath, mode: 'codex',
+ });
+ // Look for any orphaned `.tmp` files in the sandbox — the rename should
+ // have moved the temp over the original.
+ const { readdir } = await import('fs/promises');
+ const entries = await readdir(sandbox);
+ const tmps = entries.filter((n) => n.endsWith('.tmp'));
+ expect(tmps).toEqual([]);
+ });
+
+ it('preserves PNG size sanity (output is non-zero and roughly the same magnitude)', async () => {
+ const before = await stat(pngPath);
+ await autoCleanGeneratedImage({
+ enabled: true, pngPath, sidecarPath, mode: 'local',
+ });
+ const after = await stat(pngPath);
+ expect(after.size).toBeGreaterThan(0);
+ // A median+sharpen pass on a small noisy fixture stays within an order of
+ // magnitude of the original size — a wildly different size would suggest a
+ // truncated write or format regression.
+ expect(after.size).toBeLessThan(before.size * 10);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 719a21abd9..3507b16cc4 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -69,6 +69,7 @@ export * from './tuiPromptRunner.js';
// === File & I/O ===
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
+export * from './imageClean.js';
export * from './multipart.js';
export * from './pdfImageEmbed.js';
export * from './zipStream.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 3301bebb1f..4c891f2422 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -82,7 +82,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.feature-agents', path: '/feature-agents', label: 'Feature Agents', section: 'Dev Tools', aliases: ['feature-agents'] },
{ id: 'nav.devtools.github', path: '/devtools/github', label: 'GitHub', section: 'Dev Tools', aliases: ['github', 'devtools-github'] },
{ id: 'nav.devtools.history', path: '/devtools/history', label: 'History', section: 'Dev Tools', aliases: ['devtools-history'] },
- { id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['watermark', 'metadata', 'c2pa', 'sharp', 'denoise'] },
+ { id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },
{ id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', aliases: ['jira', 'devtools-jira'] },
{ id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },
{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },
diff --git a/server/routes/imageClean.js b/server/routes/imageClean.js
index a33edca53f..3c2c443986 100644
--- a/server/routes/imageClean.js
+++ b/server/routes/imageClean.js
@@ -1,168 +1,27 @@
-// Mirrors void-private's CodexImagegenService.cleanImage — strips C2PA
-// provenance + median-filters pixel-level noise from gpt-image (Codex) output.
+// HTTP wrapper around the core cleaning primitives in server/lib/imageClean.js.
+// All sharp/PNG-walker logic lives in the lib so services can call it directly
+// (services importing from routes would be a layering violation).
import { Router } from 'express';
import { z } from 'zod';
-import sharp from 'sharp';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
+import {
+ cleanImageBuffer, CLEAN_LEVELS, MAX_INPUT_BYTES, MAX_BASE64_CHARS,
+} from '../lib/imageClean.js';
const router = Router();
-// All sizes here are MiB (1024*1024). 40 MiB decoded → ~53.3 MiB base64 (4*ceil(n/3))
-// + small JSON envelope, which fits under the 55mb (= 55 MiB) body parser limit
-// in server/index.js. Keep these aligned — raising the decoded cap requires
-// raising the body parser limit too.
-const MAX_INPUT_BYTES = 40 * 1024 * 1024;
-// Reject oversized payloads before allocating the decoded Buffer.
-const MAX_BASE64_CHARS = Math.ceil((MAX_INPUT_BYTES * 4) / 3) + 4;
-// Cap decoded pixel count to prevent decompression-bomb images: a small payload
-// can declare gigantic dimensions and OOM the process during sharp decode. ~96MP
-// covers reasonable photos (12000×8000) without allowing pathological inputs.
-const MAX_PIXELS = 96 * 1000 * 1000;
-
-export const CLEAN_LEVELS = ['light', 'aggressive'];
+// Re-export so existing `import { CLEAN_LEVELS } from './imageClean.js'`
+// consumers in the routes layer keep working.
+export { cleanImageBuffer, CLEAN_LEVELS };
const cleanBodySchema = z.object({
data: z.string().min(1, 'data is required (base64)'),
- level: z.enum(CLEAN_LEVELS).optional().default('light'),
});
-// Magic-byte sniff so we re-encode as the source format and emit the right
-// MIME type — extension/header is supplied by the client and not trustworthy.
-function detectFormat(buf) {
- if (buf.length >= 8 &&
- buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
- buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) {
- return 'png';
- }
- if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
- return 'jpeg';
- }
- if (buf.length >= 12 &&
- buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
- buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) {
- return 'webp';
- }
- return null;
-}
-
-// PNG chunk type bytes must be ASCII letters per the PNG spec (RFC 2083 §3.2).
-// Validating this lets us bail out of the walker on garbage payloads that
-// happen to start with the PNG signature, instead of looping millions of times.
-function isPngChunkType(buf, offset) {
- for (let i = 0; i < 4; i++) {
- const b = buf[offset + i];
- if (!((b >= 0x41 && b <= 0x5a) || (b >= 0x61 && b <= 0x7a))) return false;
- }
- return true;
-}
-
-// Real PNGs have well under 50 chunks. Cap the walk so a buffer crafted with
-// the PNG signature followed by many tiny ASCII-typed zero-length chunks can't
-// force millions of iterations at the 40MiB input limit.
-const MAX_PNG_CHUNKS = 10000;
-
-// Walks PNG chunks once for the `caBX` provenance chunk emitted by gpt-image.
-// Sharp's default re-encode drops it; we detect it explicitly so the response
-// can flag what was stripped. Bails on invalid chunk type, truncated chunk, or
-// chunk-count overrun — a buffer that only matches the PNG signature but is
-// otherwise garbage could otherwise trigger millions of loop iterations
-// (CPU/event-loop DoS).
-function pngHasC2PA(buf) {
- let offset = 8;
- let count = 0;
- while (offset + 8 <= buf.length) {
- if (++count > MAX_PNG_CHUNKS) return false;
- if (!isPngChunkType(buf, offset + 4)) return false;
- const length = buf.readUInt32BE(offset);
- if (offset + 8 + length + 4 > buf.length) return false;
- const type = buf.toString('ascii', offset + 4, offset + 8);
- if (type === 'caBX') return true;
- if (type === 'IEND') return false;
- offset += 8 + length + 4;
- }
- return false;
-}
-
-const MIME_TYPES = {
- png: 'image/png',
- jpeg: 'image/jpeg',
- webp: 'image/webp',
-};
-
-function applyDenoise(pipeline, level) {
- if (level === 'light') return pipeline.median(1);
- return pipeline.median(3).sharpen();
-}
-
-function applyEncoder(pipeline, format) {
- if (format === 'png') return pipeline.png({ compressionLevel: 9 });
- if (format === 'jpeg') return pipeline.jpeg({ quality: 92, mozjpeg: true });
- return pipeline.webp({ quality: 92 });
-}
-
-// Throws ServerError (400) on invalid input so callers get a consistent
-// status instead of a sharp stack trace surfacing as a 500.
-export async function cleanImageBuffer(buffer, level = 'light') {
- if (!CLEAN_LEVELS.includes(level)) {
- throw new ServerError(`Invalid clean level "${level}" (expected one of: ${CLEAN_LEVELS.join(', ')})`, {
- status: 400,
- code: 'VALIDATION_ERROR',
- });
- }
- if (!Buffer.isBuffer(buffer) || buffer.length === 0) {
- throw new ServerError('Decoded payload is empty', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (buffer.length > MAX_INPUT_BYTES) {
- throw new ServerError(`Image exceeds ${MAX_INPUT_BYTES / 1024 / 1024}MB limit`, {
- status: 400,
- code: 'FILE_TOO_LARGE',
- });
- }
-
- const format = detectFormat(buffer);
- if (!format) {
- throw new ServerError('Unsupported image format (expected PNG, JPEG, or WebP)', {
- status: 400,
- code: 'UNSUPPORTED_FORMAT',
- });
- }
-
- const c2paStripped = format === 'png' && pngHasC2PA(buffer);
-
- // Single decode for both EXIF auto-orient + denoise/encode. .rotate() with no
- // args applies the EXIF Orientation tag so the cleaned pixels match what the
- // browser showed in the Before preview (browsers honor EXIF orientation but
- // sharp does not by default). resolveWithObject gives us output dimensions
- // (post-rotation), avoiding a second decode for metadata.
- const base = sharp(buffer, { limitInputPixels: MAX_PIXELS }).rotate();
- try {
- const { data, info } = await applyEncoder(applyDenoise(base, level), format)
- .toBuffer({ resolveWithObject: true });
- return {
- data,
- format,
- mimeType: MIME_TYPES[format],
- sizeBefore: buffer.length,
- sizeAfter: data.length,
- width: info.width || null,
- height: info.height || null,
- c2paStripped,
- };
- } catch (err) {
- // Wrap sharp errors (truncated/corrupt buffer that still passed the
- // magic-byte sniff) into a 400 so bad input doesn't surface as a 500.
- throw new ServerError('Invalid or corrupt image', {
- status: 400,
- code: 'INVALID_IMAGE',
- context: { details: { format, reason: err.message } },
- });
- }
-}
-
router.post('/', asyncHandler(async (req, res) => {
- const { data, level } = validateRequest(cleanBodySchema, req.body);
+ const { data } = validateRequest(cleanBodySchema, req.body);
// Cap by base64 length BEFORE allocating the decoded Buffer so an oversized
// payload doesn't briefly balloon RSS.
@@ -174,15 +33,14 @@ router.post('/', asyncHandler(async (req, res) => {
}
const buffer = Buffer.from(data, 'base64');
- const result = await cleanImageBuffer(buffer, level);
+ const result = await cleanImageBuffer(buffer);
- console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (level=${level}, c2pa=${result.c2paStripped})`);
+ console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (c2pa=${result.c2paStripped})`);
res.json({
data: result.data.toString('base64'),
mimeType: result.mimeType,
format: result.format,
- level,
sizeBefore: result.sizeBefore,
sizeAfter: result.sizeAfter,
width: result.width,
diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.js
index 5debf3d97d..090f8fc350 100644
--- a/server/routes/imageClean.test.js
+++ b/server/routes/imageClean.test.js
@@ -49,12 +49,11 @@ describe('POST /api/image-clean', () => {
it('cleans a PNG and returns base64 + metadata', async () => {
const res = await request(buildApp())
.post('/api/image-clean')
- .send({ data: pngFixture.toString('base64'), level: 'light' });
+ .send({ data: pngFixture.toString('base64') });
expect(res.status).toBe(200);
expect(res.body.format).toBe('png');
expect(res.body.mimeType).toBe('image/png');
- expect(res.body.level).toBe('light');
expect(res.body.width).toBe(4);
expect(res.body.height).toBe(4);
expect(res.body.c2paStripped).toBe(false);
@@ -70,18 +69,16 @@ describe('POST /api/image-clean', () => {
expect(res.status).toBe(200);
expect(res.body.format).toBe('jpeg');
expect(res.body.mimeType).toBe('image/jpeg');
- expect(res.body.level).toBe('light'); // default
});
it('cleans a WebP', async () => {
const res = await request(buildApp())
.post('/api/image-clean')
- .send({ data: webpFixture.toString('base64'), level: 'aggressive' });
+ .send({ data: webpFixture.toString('base64') });
expect(res.status).toBe(200);
expect(res.body.format).toBe('webp');
expect(res.body.mimeType).toBe('image/webp');
- expect(res.body.level).toBe('aggressive');
});
it('flags c2paStripped=true when PNG contains a caBX chunk', async () => {
@@ -168,15 +165,6 @@ describe('POST /api/image-clean', () => {
expect(res.body.code).toBe('FILE_TOO_LARGE');
});
- it('rejects invalid level enum with VALIDATION_ERROR', async () => {
- const res = await request(buildApp())
- .post('/api/image-clean')
- .send({ data: pngFixture.toString('base64'), level: 'nuclear' });
-
- expect(res.status).toBe(400);
- expect(res.body.code).toBe('VALIDATION_ERROR');
- });
-
it('auto-orients images via EXIF Orientation tag', async () => {
// Build a 4×8 JPEG, then re-emit with EXIF Orientation=6 (rotate 90° CW)
// embedded via withMetadata. After the route's auto-orient, the output
diff --git a/server/routes/imageGen.clean.test.js b/server/routes/imageGen.clean.test.js
index 622b02c3fb..7a00e86d8b 100644
--- a/server/routes/imageGen.clean.test.js
+++ b/server/routes/imageGen.clean.test.js
@@ -50,6 +50,21 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => []),
}));
+// Mock the collections service so the clean route's auto-file behavior is
+// observable + the tests don't depend on PATHS.data state. Default
+// `listCollections` returns empty, which makes the auto-file step a no-op for
+// every test that doesn't override the mock. Tests that exercise auto-file
+// re-configure `listCollectionsMock` per-case.
+const { listCollectionsMock, addItemMock } = vi.hoisted(() => ({
+ listCollectionsMock: vi.fn(async () => []),
+ addItemMock: vi.fn(async () => ({})),
+}));
+vi.mock('../services/mediaCollections.js', () => ({
+ listCollections: listCollectionsMock,
+ addItem: addItemMock,
+ ERR_DUPLICATE: 'DUPLICATE',
+}));
+
let imageGenRoutes;
let pngFixture;
@@ -79,82 +94,58 @@ describe('POST /api/image-gen/:filename/clean', () => {
app.use(express.json());
app.use('/api/image-gen', imageGenRoutes);
app.use(errorMiddleware);
+ listCollectionsMock.mockReset();
+ listCollectionsMock.mockResolvedValue([]);
+ addItemMock.mockReset();
+ addItemMock.mockResolvedValue({});
});
- it('cleans an existing PNG and writes _clean-light.png back to the gallery', async () => {
+ it('cleans an existing PNG and writes _clean-aggressive.png back to the gallery', async () => {
await writeFile(join(sandbox, 'render-1.png'), pngFixture);
await writeFile(join(sandbox, 'render-1.metadata.json'), JSON.stringify({
prompt: 'a red square', seed: 42, modelId: 'flux-v1',
}));
- const res = await request(app).post('/api/image-gen/render-1.png/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/render-1.png/clean').send({});
expect(res.status).toBe(200);
- expect(res.body.filename).toBe('render-1_clean-light.png');
+ expect(res.body.filename).toBe('render-1_clean-aggressive.png');
expect(res.body.cleanedFrom).toBe('render-1.png');
- expect(res.body.cleanLevel).toBe('light');
+ expect(res.body.cleanLevel).toBe('aggressive');
// Source sidecar carried forward so the cleaned copy retains lineage.
expect(res.body.prompt).toBe('a red square');
expect(res.body.seed).toBe(42);
expect(res.body.modelId).toBe('flux-v1');
- expect(existsSync(join(sandbox, 'render-1_clean-light.png'))).toBe(true);
- expect(existsSync(join(sandbox, 'render-1_clean-light.metadata.json'))).toBe(true);
- });
-
- it('aggressive level produces a different output than light (different denoise)', async () => {
- await writeFile(join(sandbox, 'render-2.png'), pngFixture);
-
- const lightRes = await request(app).post('/api/image-gen/render-2.png/clean').send({ level: 'light' });
- const aggRes = await request(app).post('/api/image-gen/render-2.png/clean').send({ level: 'aggressive' });
- expect(lightRes.status).toBe(200);
- expect(aggRes.status).toBe(200);
- expect(lightRes.body.filename).toBe('render-2_clean-light.png');
- expect(aggRes.body.filename).toBe('render-2_clean-aggressive.png');
-
- const lightBuf = await readFile(join(sandbox, lightRes.body.filename));
- const aggBuf = await readFile(join(sandbox, aggRes.body.filename));
- expect(lightBuf.equals(aggBuf)).toBe(false);
+ expect(existsSync(join(sandbox, 'render-1_clean-aggressive.png'))).toBe(true);
+ expect(existsSync(join(sandbox, 'render-1_clean-aggressive.metadata.json'))).toBe(true);
});
- it('idempotent: running the same level twice overwrites instead of accumulating', async () => {
+ it('idempotent: running clean twice overwrites instead of accumulating', async () => {
await writeFile(join(sandbox, 'render-3.png'), pngFixture);
- const first = await request(app).post('/api/image-gen/render-3.png/clean').send({ level: 'light' });
- const second = await request(app).post('/api/image-gen/render-3.png/clean').send({ level: 'light' });
+ const first = await request(app).post('/api/image-gen/render-3.png/clean').send({});
+ const second = await request(app).post('/api/image-gen/render-3.png/clean').send({});
expect(first.body.filename).toBe(second.body.filename);
- expect(first.body.filename).toBe('render-3_clean-light.png');
- });
-
- it('defaults to light when level omitted', async () => {
- await writeFile(join(sandbox, 'render-4.png'), pngFixture);
- const res = await request(app).post('/api/image-gen/render-4.png/clean').send({});
- expect(res.status).toBe(200);
- expect(res.body.cleanLevel).toBe('light');
- });
-
- it('rejects unknown level', async () => {
- await writeFile(join(sandbox, 'render-5.png'), pngFixture);
- const res = await request(app).post('/api/image-gen/render-5.png/clean').send({ level: 'extreme' });
- expect(res.status).toBe(400);
+ expect(first.body.filename).toBe('render-3_clean-aggressive.png');
});
it('rejects non-PNG filenames (gallery is PNG-only)', async () => {
- const res = await request(app).post('/api/image-gen/render.jpg/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/render.jpg/clean').send({});
expect(res.status).toBe(400);
});
it('rejects path-traversal in filename', async () => {
- const res = await request(app).post('/api/image-gen/' + encodeURIComponent('../etc/passwd.png') + '/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/' + encodeURIComponent('../etc/passwd.png') + '/clean').send({});
expect(res.status).toBe(400);
});
it('returns 404 when the source image does not exist', async () => {
- const res = await request(app).post('/api/image-gen/does-not-exist.png/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/does-not-exist.png/clean').send({});
expect(res.status).toBe(404);
});
it('writes a sidecar that records the cleaning lineage', async () => {
await writeFile(join(sandbox, 'render-6.png'), pngFixture);
- await request(app).post('/api/image-gen/render-6.png/clean').send({ level: 'aggressive' });
+ await request(app).post('/api/image-gen/render-6.png/clean').send({});
const sidecar = JSON.parse(await readFile(join(sandbox, 'render-6_clean-aggressive.metadata.json'), 'utf-8'));
expect(sidecar.cleanedFrom).toBe('render-6.png');
expect(sidecar.cleanLevel).toBe('aggressive');
@@ -166,27 +157,104 @@ describe('POST /api/image-gen/:filename/clean', () => {
await writeFile(join(sandbox, 'render-hidden.metadata.json'), JSON.stringify({
prompt: 'a hidden render', hidden: true,
}));
- const res = await request(app).post('/api/image-gen/render-hidden.png/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/render-hidden.png/clean').send({});
expect(res.status).toBe(200);
expect(res.body.hidden).toBeUndefined();
expect(res.body.prompt).toBe('a hidden render');
- const sidecar = JSON.parse(await readFile(join(sandbox, 'render-hidden_clean-light.metadata.json'), 'utf-8'));
+ const sidecar = JSON.parse(await readFile(join(sandbox, 'render-hidden_clean-aggressive.metadata.json'), 'utf-8'));
expect(sidecar.hidden).toBeUndefined();
});
it('accepts legitimate filenames containing `..` substring (not exact `..`)', async () => {
await writeFile(join(sandbox, 'my..render.png'), pngFixture);
- const res = await request(app).post(`/api/image-gen/${encodeURIComponent('my..render.png')}/clean`).send({ level: 'light' });
+ const res = await request(app).post(`/api/image-gen/${encodeURIComponent('my..render.png')}/clean`).send({});
expect(res.status).toBe(200);
- expect(res.body.filename).toBe('my..render_clean-light.png');
+ expect(res.body.filename).toBe('my..render_clean-aggressive.png');
});
it('output file size is reflected in sizeBytes / sizeAfter', async () => {
await writeFile(join(sandbox, 'render-7.png'), pngFixture);
- const res = await request(app).post('/api/image-gen/render-7.png/clean').send({ level: 'light' });
+ const res = await request(app).post('/api/image-gen/render-7.png/clean').send({});
const s = await stat(join(sandbox, res.body.filename));
expect(res.body.sizeBytes).toBe(s.size);
expect(res.body.sizeAfter).toBe(s.size);
});
+
+ describe('auto-file cleaned image into source collections', () => {
+ it('adds the cleaned filename to every collection that contained the source', async () => {
+ await writeFile(join(sandbox, 'render-coll.png'), pngFixture);
+ listCollectionsMock.mockResolvedValue([
+ { id: 'col-a', items: [{ kind: 'image', ref: 'render-coll.png' }] },
+ { id: 'col-b', items: [{ kind: 'image', ref: 'render-coll.png' }, { kind: 'image', ref: 'other.png' }] },
+ { id: 'col-c-unrelated', items: [{ kind: 'image', ref: 'other.png' }] },
+ ]);
+
+ const res = await request(app).post('/api/image-gen/render-coll.png/clean').send({});
+ expect(res.status).toBe(200);
+
+ // Only the two collections containing the source get the cleaned copy.
+ // Order is non-deterministic (Promise.all), so assert by call set.
+ expect(addItemMock).toHaveBeenCalledTimes(2);
+ const calls = addItemMock.mock.calls.map(([id, item]) => ({ id, item }));
+ expect(calls).toEqual(expect.arrayContaining([
+ { id: 'col-a', item: { kind: 'image', ref: 'render-coll_clean-aggressive.png' } },
+ { id: 'col-b', item: { kind: 'image', ref: 'render-coll_clean-aggressive.png' } },
+ ]));
+ expect(calls.find((c) => c.id === 'col-c-unrelated')).toBeUndefined();
+ });
+
+ it('is a no-op when the source is not in any collection', async () => {
+ await writeFile(join(sandbox, 'render-orphan.png'), pngFixture);
+ listCollectionsMock.mockResolvedValue([
+ { id: 'col-x', items: [{ kind: 'image', ref: 'something-else.png' }] },
+ ]);
+
+ const res = await request(app).post('/api/image-gen/render-orphan.png/clean').send({});
+ expect(res.status).toBe(200);
+ expect(addItemMock).not.toHaveBeenCalled();
+ });
+
+ it('swallows ERR_DUPLICATE so re-cleans of an already-filed pair are idempotent', async () => {
+ await writeFile(join(sandbox, 'render-dup.png'), pngFixture);
+ listCollectionsMock.mockResolvedValue([
+ { id: 'col-dup', items: [{ kind: 'image', ref: 'render-dup.png' }] },
+ ]);
+ addItemMock.mockRejectedValue(Object.assign(new Error('Item already in collection'), { code: 'DUPLICATE' }));
+
+ const res = await request(app).post('/api/image-gen/render-dup.png/clean').send({});
+ // The clean itself succeeds; the duplicate is swallowed.
+ expect(res.status).toBe(200);
+ expect(res.body.filename).toBe('render-dup_clean-aggressive.png');
+ });
+
+ it('clean succeeds even if listCollections throws (best-effort)', async () => {
+ await writeFile(join(sandbox, 'render-listfail.png'), pngFixture);
+ listCollectionsMock.mockRejectedValue(new Error('disk full'));
+
+ const res = await request(app).post('/api/image-gen/render-listfail.png/clean').send({});
+ expect(res.status).toBe(200);
+ expect(res.body.filename).toBe('render-listfail_clean-aggressive.png');
+ // The cleaned file still landed on disk.
+ expect(existsSync(join(sandbox, 'render-listfail_clean-aggressive.png'))).toBe(true);
+ });
+
+ it('clean succeeds even when one addItem throws a non-DUPLICATE error (best-effort, others still fire)', async () => {
+ await writeFile(join(sandbox, 'render-mixed.png'), pngFixture);
+ listCollectionsMock.mockResolvedValue([
+ { id: 'col-ok', items: [{ kind: 'image', ref: 'render-mixed.png' }] },
+ { id: 'col-fail', items: [{ kind: 'image', ref: 'render-mixed.png' }] },
+ ]);
+ addItemMock.mockImplementation(async (id) => {
+ if (id === 'col-fail') throw new Error('collection write blew up');
+ return {};
+ });
+
+ const res = await request(app).post('/api/image-gen/render-mixed.png/clean').send({});
+ expect(res.status).toBe(200);
+ // Both ids were attempted — the success path doesn't short-circuit on
+ // a sibling failure.
+ expect(addItemMock).toHaveBeenCalledTimes(2);
+ });
+ });
});
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index e8f8b74961..aea4572311 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -33,8 +33,10 @@ import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
import { join } from 'node:path';
import { readFile, writeFile } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
-import { cleanImageBuffer, CLEAN_LEVELS } from './imageClean.js';
+import { cleanImageBuffer } from '../lib/imageClean.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
+import { listCollections, addItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
+import { itemKey } from '../lib/mediaItemKey.js';
const router = Router();
@@ -73,6 +75,11 @@ const generateSchema = z.object({
// array — file presence is enforced at the upload layer, and the route
// pairs filled slots with their strengths positionally.
referenceStrengths: z.array(z.number().min(0).max(1)).max(4).optional(),
+ // Per-render override of `settings.imageGen.{mode}.autoClean`. When omitted,
+ // the route falls back to the saved settings value. `true` forces in-place
+ // auto-clean for this one render; `false` skips it even when the saved
+ // setting is on.
+ autoClean: z.boolean().optional(),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
// JSON callers (SDAPI bridge, avatar route, the Imagine page's old payload
@@ -108,6 +115,9 @@ function coerceFormFields(body) {
const raw = Array.isArray(body.referenceStrengths) ? body.referenceStrengths : [body.referenceStrengths];
body.referenceStrengths = raw.map((v) => (typeof v === 'string' && v !== '' ? Number(v) : v));
}
+ // Multipart sends checkbox values as 'true' / 'false' strings; coerce to
+ // bool so Zod's `z.boolean()` accepts them.
+ if (typeof body.autoClean === 'string') body.autoClean = body.autoClean === 'true';
return body;
}
@@ -186,6 +196,14 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// is cheap — it's already read again below for the per-mode dispatch.)
const settings = await getSettings();
const mode = data.mode || settings.imageGen?.mode || 'external';
+ // Resolve autoClean ONCE at the route layer so all three dispatch paths
+ // (synchronous external, codex queue, local queue) see the same value.
+ // Body wins when explicit (the per-render checkbox); otherwise inherit the
+ // saved per-mode setting. Stamp onto `data` so the value flows through
+ // the spread-into-params calls below verbatim.
+ data.autoClean = (typeof data.autoClean === 'boolean')
+ ? data.autoClean
+ : (settings.imageGen?.[mode]?.autoClean === true);
// Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
// buildArgs only emits --reference-images/--reference-strengths inside the
@@ -437,10 +455,6 @@ router.post('/:filename/visibility', asyncHandler(async (req, res) => {
}));
router.post('/:filename/clean', asyncHandler(async (req, res) => {
- const { level } = validateRequest(
- z.object({ level: z.enum(CLEAN_LEVELS).optional().default('light') }),
- req.body,
- );
const filename = req.params.filename;
local.assertGalleryFilename(filename);
@@ -453,15 +467,19 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
local.readImageSidecar(filename),
]);
- const result = await cleanImageBuffer(buffer, level);
+ const result = await cleanImageBuffer(buffer);
if (result.format !== 'png') {
throw new ServerError('Gallery images must be PNG', { status: 400, code: 'UNSUPPORTED_FORMAT' });
}
+ // The `_clean-aggressive` filename suffix and `cleanLevel: 'aggressive'`
+ // sidecar field survive the light/aggressive collapse so already-cleaned
+ // images on disk keep round-tripping through the gallery unchanged. A future
+ // rename to `_cleaned.png` would need a backfill migration.
const base = filename.slice(0, -'.png'.length);
- const outFilename = `${base}_clean-${level}.png`;
+ const outFilename = `${base}_clean-aggressive.png`;
const outPath = join(PATHS.images, outFilename);
- const sidecarPath = join(PATHS.images, `${base}_clean-${level}.metadata.json`);
+ const sidecarPath = join(PATHS.images, `${base}_clean-aggressive.metadata.json`);
const createdAt = new Date().toISOString();
// Strip `hidden` so a clean of a hidden source still surfaces in the gallery
@@ -473,7 +491,7 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
...sourceMetaForCleaned,
createdAt,
cleanedFrom: filename,
- cleanLevel: level,
+ cleanLevel: 'aggressive',
c2paStripped: result.c2paStripped,
};
@@ -482,7 +500,18 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
writeFile(sidecarPath, JSON.stringify(cleanedMeta, null, 2)),
]);
- console.log(`🧼 Cleaned ${filename} → ${outFilename} (level=${level}, ${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped})`);
+ // Auto-file the cleaned copy into every collection that contained the
+ // source. Without this, users who built a collection around an original
+ // would have to manually re-add the cleaned variant — the prior behavior
+ // surprised users (cleaned image vanished from "their" view). Best-effort:
+ // a collection-add failure must not fail the clean itself. ERR_DUPLICATE
+ // is silently swallowed so re-cleans of an already-filed pair are no-ops.
+ const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
+ console.warn(`⚠️ Auto-file cleaned ${outFilename} → source collections failed: ${err?.message || err}`);
+ return [];
+ });
+
+ console.log(`🧼 Cleaned ${filename} → ${outFilename} (${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
// sourceMeta first so explicit fields below win on key collisions (the
// cleaned copy's createdAt must reflect the cleaning, not the original).
@@ -497,11 +526,34 @@ router.post('/:filename/clean', asyncHandler(async (req, res) => {
width: result.width,
height: result.height,
cleanedFrom: filename,
- cleanLevel: level,
+ cleanLevel: 'aggressive',
c2paStripped: result.c2paStripped,
});
}));
+// Add the cleaned-image filename to every collection that already contains
+// the source filename. Returns the ids of the collections that received the
+// new entry (excluding ones that already contained the cleaned filename).
+// Cross-collection writes run in parallel — addItem serializes per file write
+// internally, so concurrent calls on different collections are safe.
+async function autoFileCleanedToSourceCollections(sourceFilename, cleanedFilename) {
+ const sourceKey = itemKey({ kind: 'image', ref: sourceFilename });
+ const all = await listCollections();
+ const matching = all.filter((c) => c.items.some((it) => itemKey(it) === sourceKey));
+ if (matching.length === 0) return [];
+ const results = await Promise.all(matching.map(async (c) => {
+ try {
+ await addItem(c.id, { kind: 'image', ref: cleanedFilename });
+ return c.id;
+ } catch (err) {
+ if (err?.code === ERR_DUPLICATE) return null;
+ console.warn(`⚠️ Auto-file ${cleanedFilename} → collection ${c.id} failed: ${err?.message || err}`);
+ return null;
+ }
+ }));
+ return results.filter(Boolean);
+}
+
// --- Local-mode setup automation ---
router.get('/setup/python', asyncHandler(async (_req, res) => {
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 1010ab05bf..eebc5858d6 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -325,6 +325,72 @@ describe('Image Gen Routes', () => {
expect(imageGen.generateImage).not.toHaveBeenCalled();
});
+ describe('autoClean resolution (body wins over saved setting)', () => {
+ it('external mode: body autoClean=true overrides saved setting=false', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'external', external: { autoClean: false } },
+ });
+ imageGen.generateImage.mockResolvedValue({ filename: 'x.png', path: '/data/images/x.png' });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', autoClean: true });
+
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ autoClean: true }));
+ });
+
+ it('external mode: omitted body inherits saved setting=true', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'external', external: { autoClean: true } },
+ });
+ imageGen.generateImage.mockResolvedValue({ filename: 'x.png', path: '/data/images/x.png' });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });
+
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ autoClean: true }));
+ });
+
+ it('local mode: body autoClean=true flows through into enqueued params (was previously dropped)', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'local', local: { pythonPath: '/p', autoClean: false } },
+ });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', autoClean: true });
+
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.autoClean).toBe(true);
+ });
+
+ it('local mode: omitted body inherits saved setting=true on enqueued params', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'local', local: { pythonPath: '/p', autoClean: true } },
+ });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });
+
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.autoClean).toBe(true);
+ });
+
+ it('codex mode: body autoClean=false overrides saved setting=true on enqueued params', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'codex', codex: { enabled: true, autoClean: true } },
+ });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', autoClean: false });
+
+ const [call] = mediaJobQueue.enqueueJob.mock.calls;
+ expect(call[0].params.autoClean).toBe(false);
+ });
+
+ it('defaults to false when neither body nor settings specify', async () => {
+ getSettings.mockResolvedValueOnce({ imageGen: { mode: 'external' } });
+ imageGen.generateImage.mockResolvedValue({ filename: 'x.png', path: '/data/images/x.png' });
+
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });
+
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ autoClean: false }));
+ });
+ });
+
// Codex with the toggle off rejects up-front rather than enqueueing.
it('codex mode with disabled toggle returns 400 CODEX_IMAGEGEN_DISABLED', async () => {
getSettings.mockResolvedValueOnce({
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 8b30d2ff0c..01b2b87e16 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -26,6 +26,7 @@ import { homedir } from 'os';
import { randomUUID } from 'crypto';
import { ensureDir, PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
@@ -140,6 +141,7 @@ export async function generateImage({
codexPath, model, prompt, width, height, negativePrompt,
initImagePath, initImageStrength,
jobId: providedJobId = null,
+ autoClean = false,
}) {
if (!prompt?.trim()) {
throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
@@ -197,7 +199,7 @@ export async function generateImage({
// generateImage returns a job descriptor synchronously; the actual codex
// child runs out-of-band so the HTTP response can ship while the client
// attaches to the per-job SSE stream (mirrors local.js).
- runCodex(job, jobId, bin, args, outputPath, filename, meta).catch((err) => {
+ runCodex(job, jobId, bin, args, outputPath, filename, meta, { autoClean }).catch((err) => {
console.log(`❌ codex run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
});
@@ -210,7 +212,7 @@ export async function generateImage({
};
}
-async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
+async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { autoClean = false } = {}) {
const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
@@ -308,6 +310,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {
// useful for traceability even though it doesn't reproduce the output.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
await writeFile(sidecar, JSON.stringify({ ...meta, codexSessionId: sessionId }, null, 2)).catch(() => {});
+ // Auto-clean (settings.imageGen.codex.autoClean) — runs BEFORE the
+ // SSE complete + completed events so subscribers see the cleaned bytes.
+ // codex output is the highest-value target for cleaning because gpt-image
+ // is the one provider that embeds C2PA provenance.
+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: 'codex' });
job.status = 'complete';
if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
activeJobs.delete(jobId);
diff --git a/server/services/imageGen/external.js b/server/services/imageGen/external.js
index 81c3c5cc80..004d5d257b 100644
--- a/server/services/imageGen/external.js
+++ b/server/services/imageGen/external.js
@@ -12,6 +12,7 @@ import { randomUUID } from 'crypto';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
+import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';
@@ -102,7 +103,7 @@ function startProgressPolling(baseUrl, generationId) {
let activeJob = null;
export const getActiveJob = () => activeJob;
-export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, height, steps, cfgScale, seed }) {
+export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, height, steps, cfgScale, seed, autoClean }) {
const baseUrl = validateSdUrl(sdapiUrl);
const model = await detectModel(baseUrl);
const isFlux = model?.toLowerCase().includes('flux');
@@ -165,7 +166,12 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h
await ensureDir(PATHS.images);
const filename = `${randomUUID()}.png`;
- await writeFile(join(PATHS.images, filename), Buffer.from(data.images[0], 'base64'));
+ const pngPath = join(PATHS.images, filename);
+ await writeFile(pngPath, Buffer.from(data.images[0], 'base64'));
+ // Auto-clean BEFORE the SSE complete fires so the URL the client opens
+ // serves the cleaned bytes. External mode has no sidecar — pass null so
+ // the helper just patches the PNG in place.
+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath, sidecarPath: null, mode: 'external' });
const path = `/data/images/${filename}`;
console.log(`🖼️ Image saved: ${filename}`);
activeJob = null;
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index 61a8ae4d18..6cd478a5f4 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -69,6 +69,14 @@ export async function generateImage(params) {
delete normalized.initImagePath;
delete normalized.initImageStrength;
}
+ // Auto-clean is per-provider-mode, opt-in. Precedence: caller-supplied
+ // boolean (the `/generate` route's per-render checkbox) wins; otherwise
+ // inherit the saved per-mode setting. Strip from `normalized` so the
+ // explicit arg on each provider call isn't shadowed by the spread.
+ const autoClean = (typeof normalized.autoClean === 'boolean')
+ ? normalized.autoClean
+ : (cfg(s)[mode]?.autoClean === true);
+ delete normalized.autoClean;
if (mode === 'codex') {
const c = codexCfg(s);
if (!c.enabled) {
@@ -77,12 +85,12 @@ export async function generateImage(params) {
{ status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },
);
}
- return codex.generateImage({ codexPath: c.codexPath, model: c.model, ...normalized });
+ return codex.generateImage({ codexPath: c.codexPath, model: c.model, autoClean, ...normalized });
}
if (mode === 'local') {
- return local.generateImage({ pythonPath: pythonPath(s), ...normalized });
+ return local.generateImage({ pythonPath: pythonPath(s), autoClean, ...normalized });
}
- return external.generateImage({ sdapiUrl: sdapiUrl(s), ...normalized });
+ return external.generateImage({ sdapiUrl: sdapiUrl(s), autoClean, ...normalized });
}
const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index db0296a35a..1bbbab5bb0 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -20,6 +20,7 @@ import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
import { assertSafeFilename, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';
@@ -212,7 +213,7 @@ export const buildArgs = ({ pythonPath, model, prompt, negativePrompt, width, he
return { bin, args };
};
-export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null }) {
+export async function generateImage({ pythonPath, prompt, negativePrompt = '', modelId = 'dev', width = 1024, height = 1024, steps, guidance, seed, quantize = '8', loraFilenames = [], loraPaths = [], loraScales = [], initImagePath = null, initImageStrength = null, referenceImagePaths = [], referenceImageStrengths = [], jobId: providedJobId = null, autoClean = false }) {
if (!prompt?.trim()) throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
// Single-flight is enforced by the mediaJobQueue worker upstream. Direct
// callers that bypass the queue must not run two concurrent renders — the
@@ -556,6 +557,9 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// --metadata sidecar lives at a slightly different filename shape.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});
+ // Auto-clean (settings.imageGen.local.autoClean) — runs BEFORE the
+ // SSE complete + completed events so subscribers see the cleaned bytes.
+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: 'local' });
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}`);
const result = { filename, seed: actualSeed, path: `/data/images/${filename}` };
broadcastSse(job, { type: 'complete', result });