Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: CPU light diffusion pass for Image Cleaner SynthID disruption (#1763)
Adam Eivy4674459e7331
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d38bcb797b..a3745264f1 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -100,6 +100,7 @@## Dev Tools+- **[issue-1763] The Image Cleaner gained a CPU "Diffusion pass" step that actually disrupts SynthID.** Building on the Phase 1 composable pipeline (metadata/C2PA + median/sharpen toggles, #1768), the `/devtools/image-clean` page now offers a third opt-in step: a CPU-only diffusion pass (default OFF, lossy) that runs the same spatial round-trip as the ImageGen lightbox regenerate — resize-squeeze + micro color/contrast nudge + high-frequency perturbation (`applyLightRegen`) — perturbing SynthID's resolution-dependent watermark carriers. It runs synchronously in-request after the metadata and denoise steps (pipeline order: metadata → median/sharpen → diffusion), always re-encodes to PNG, and reports a fidelity metric (pixel-delta % + PSNR) in the per-step report so the UI can honestly say it *disrupts* the watermark rather than *removes* it (never verified against Google's detector). Options ride in the query string (`?diffusion=light`). The higher-reliability GPU FLUX img2img round-trip — which needs a non-gallery render seam factored out of the lightbox `/regenerate` flow plus async media-job progress — is a tracked follow-up; requesting it (`?diffusion=gpu`) returns an actionable 501 for now. The ignore-zone mask painter and resolution-aware GPU options also remain in that follow-up. (`server/routes/imageClean.js`, `client/src/services/apiMedia.js`, `client/src/pages/ImageClean.jsx`)- **The Usage page now shows your Claude Code subscription rate limits, not just PortOS's own token counts.** The `/devtools/usage` page previously only reported PortOS's internal AI-toolkit accounting (its own sessions/messages/tokens). It now leads with a **Claude Code Subscription** panel that surfaces the same numbers as the CLI's `/usage` command — current-session %, weekly % (all models and per-model, e.g. Fable), how much is left in each, and when each window resets — as color-coded meters that load on page open with a manual Refresh. Because there's no structured usage endpoint in the CLI, the server reads it the only way available: it runs `claude -p` with `/usage` on stdin (a read-only call that consumes zero tokens), parses the human-readable output into JSON, and caches it for 60s. Reset times render in the **machine's timezone** — resolved from the OS, not the server process's env — so a server running under PM2/systemd in UTC still shows the same reset times as an interactive `/usage`, instead of UTC-shifted ones. The numbers are a per-machine local approximation (they don't include other devices or claude.ai), and the panel says so. If the `claude` CLI isn't installed/signed-in, the panel shows a friendly note instead of erroring. (`server/services/claudeCodeUsage.js`, `server/routes/usage.js`, `client/src/pages/UsagePage.jsx`)## Fixeddiff --git a/client/src/pages/ImageClean.jsx b/client/src/pages/ImageClean.jsxindex 9f7f13726a..91bf382152 100644--- a/client/src/pages/ImageClean.jsx+++ b/client/src/pages/ImageClean.jsx@@ -28,8 +28,9 @@ export default function ImageClean() {const [result, setResult] = useState(null);const [busy, setBusy] = useState(false);const [dragActive, setDragActive] = useState(false);- // Opt-in pipeline steps. metadata defaults ON (lossless), denoise OFF (lossy).- const [steps, setSteps] = useState({ metadata: true, denoise: false });+ // Opt-in pipeline steps. metadata defaults ON (lossless), denoise OFF (lossy),+ // diffusion OFF (lossy — CPU light pass, the only step that touches SynthID).+ const [steps, setSteps] = useState({ metadata: true, denoise: false, diffusion: false });const fileInputRef = useRef(null);const requestIdRef = useRef(0);const previewUrlRef = useRef(null);@@ -50,7 +51,15 @@ export default function ImageClean() {resultUrlRef.current = null;}setResult(null);- const cleaned = await api.cleanImage(file, selectedSteps).catch((err) => {+ // Map the boolean diffusion toggle to the server's mode enum. Only the CPU+ // light pass is wired on this route today; the GPU FLUX round-trip is a+ // deferred follow-up (server returns 501 for diffusion=gpu).+ const payload = {+ metadata: selectedSteps.metadata,+ denoise: selectedSteps.denoise,+ diffusion: selectedSteps.diffusion ? 'light' : 'off',+ };+ const cleaned = await api.cleanImage(file, payload).catch((err) => {toast.error(err.message || 'Failed to clean image');return null;});@@ -167,6 +176,11 @@ export default function ImageClean() {label: 'Median + sharpen',hint: 'Lossy — reduces visible AI-generation artifacts but blurs fine text. Re-encodes the image.',},+ {+ key: 'diffusion',+ label: 'Diffusion pass — disrupt SynthID (CPU)',+ hint: 'Lossy, best-effort — a CPU spatial round-trip (resize-squeeze + color/high-frequency nudge) that perturbs SynthID\'s watermark carriers. Blurs fine text. This is the only step that touches SynthID, and it disrupts — never guarantees removal. GPU FLUX round-trip coming later.',+ },];return (@@ -182,13 +196,14 @@ export default function ImageClean() {</p><p className="text-gray-500 text-xs mt-1"><span className="text-port-warning">Note:</span>{' '}- these passes do NOT defeat SynthID. gpt-image / Imagen / Gemini renders stay detectable by their vendor watermark checkers- (e.g.{' '}+ the metadata and median/sharpen passes do 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>- ) — SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode. A local diffusion pass that- actually disrupts SynthID is tracked as a follow-up (issue #1763).+ ), since SynthID is embedded in pixel values and was designed to survive median + sharpen + re-encode. The <strong>diffusion pass</strong>{' '}+ (CPU) is the only step that perturbs SynthID's carriers — best-effort, and it <em>disrupts</em> rather than guarantees removal (never verified against+ Google's detector). The higher-reliability GPU FLUX round-trip is a follow-up.</p></div></div>@@ -239,7 +254,7 @@ export default function ImageClean() {<div className="flex items-center gap-2 mb-3"><Sparkles size={16} className="text-port-accent" /><span className="text-sm font-medium text-white">Pipeline steps</span>- <span className="text-xs text-gray-500">run in order: metadata → median/sharpen</span>+ <span className="text-xs text-gray-500">run in order: metadata → median/sharpen → diffusion</span></div><div className="grid grid-cols-1 sm:grid-cols-2 gap-3">{STEP_DEFS.map(({ key, label, hint }) => (diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.jsindex 5351824f87..6e579b9c55 100644--- a/client/src/services/apiMedia.js+++ b/client/src/services/apiMedia.js@@ -34,12 +34,15 @@ export const deleteAllUploads = (options = {}) => request('/uploads?confirm=true// custom header. Returns `{ blob, mimeType, report }`. Throws on failure so the// page's own catch can toast (no silent flag needed — this never double-toasts).//-// `steps` is `{ metadata?: boolean, denoise?: boolean }`; both default on the-// server (metadata ON, denoise OFF) when omitted.+// `steps` is `{ metadata?: boolean, denoise?: boolean, diffusion?: 'off'|'light'|'gpu' }`.+// metadata/denoise default on the server (metadata ON, denoise OFF); diffusion+// defaults to 'off'. 'light' runs the CPU spatial SynthID-disruption pass;+// 'gpu' (the FLUX round-trip) is not yet wired here and returns a 501.export const cleanImage = async (file, steps = {}) => {const params = new URLSearchParams();if (typeof steps.metadata === 'boolean') params.set('metadata', steps.metadata ? '1' : '0');if (typeof steps.denoise === 'boolean') params.set('denoise', steps.denoise ? '1' : '0');+ if (typeof steps.diffusion === 'string' && steps.diffusion !== 'off') params.set('diffusion', steps.diffusion);const qs = params.toString();// Always send application/octet-stream rather than the browser's reporteddiff --git a/server/lib/README.md b/server/lib/README.mdindex d006a562d2..1a7be67c80 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -120,7 +120,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |-| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |+| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). || `multipart.js` | Streaming multipart/form-data parser. |diff --git a/server/routes/imageClean.js b/server/routes/imageClean.jsindex 061715698e..a6d3a9a4a0 100644--- a/server/routes/imageClean.js+++ b/server/routes/imageClean.js@@ -13,6 +13,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { cleanImageBuffer, CLEAN_LEVELS } from '../lib/imageClean.js';+import { applyLightRegen, computePixelDelta } from '../services/imageGen/regen.js';const router = Router();@@ -33,10 +34,29 @@ const queryFlag = (def) => z.preprocess(z.boolean(),);+// Diffusion sub-mode. `off` (default) skips it entirely; `light` runs the+// CPU-only spatial pass (`applyLightRegen`) that actually perturbs SynthID's+// resolution-dependent carriers — the no-GPU fallback, always available since+// sharp is a hard dependency. `gpu` (the FLUX img2img round-trip) is NOT wired+// on this route yet: it needs the non-gallery render seam factored out of the+// lightbox `/regenerate` flow (async job queue + progress channel), deferred to+// a follow-up. Accepting the token but rejecting it with a clear 501 keeps the+// client contract stable for when that lands. Anything else → the `off` default.+const diffusionMode = z.preprocess(+ (v) => {+ if (v === undefined || v === '' || v === '0' || v === 'false' || v === 'off') return 'off';+ if (v === 'light' || v === 'cpu' || v === '1' || v === 'true') return 'light';+ if (v === 'gpu' || v === 'flux') return 'gpu';+ return 'off';+ },+ z.enum(['off', 'light', 'gpu']),+);+// Pipeline steps ride in the query string, not the body (the body is the image).const cleanQuerySchema = z.object({metadata: queryFlag(true),denoise: queryFlag(false),+ diffusion: diffusionMode,});// 256 MiB raw-byte ceiling — the transport is the only (generous) size bound now@@ -53,7 +73,18 @@ router.post('/',raw({ type: RAW_TYPES, limit: RAW_LIMIT }),asyncHandler(async (req, res) => {- const { metadata, denoise } = validateRequest(cleanQuerySchema, req.query);+ const { metadata, denoise, diffusion } = validateRequest(cleanQuerySchema, req.query);++ // The GPU FLUX round-trip needs the non-gallery render seam factored out of+ // the lightbox `/regenerate` flow (async job queue + media-job progress),+ // which this slice defers to a follow-up. Reject it explicitly so a client+ // that asked for it gets an actionable message rather than a silent CPU pass.+ if (diffusion === 'gpu') {+ throw new ServerError('GPU FLUX diffusion is not yet available on the Image Cleaner. Use the CPU light pass (diffusion=light) or run a regeneration from the ImageGen lightbox.', {+ status: 501,+ code: 'NOT_IMPLEMENTED',+ });+ }const buffer = Buffer.isBuffer(req.body) ? req.body : null;if (!buffer || buffer.length === 0) {@@ -65,24 +96,69 @@ router.post(const result = await cleanImageBuffer(buffer, { metadata, denoise });+ // Diffusion (CPU light pass) runs LAST in the pipeline order (metadata →+ // denoise → diffusion), on the already-cleaned bytes. `applyLightRegen` is a+ // pure sharp round-trip (resize-squeeze + micro color nudge + high-freq+ // perturbation) that perturbs SynthID's resolution-dependent carriers — the+ // only step here that touches SynthID at all, and honestly best-effort. It+ // always re-encodes to PNG, so the output format/mime flip to PNG when it+ // runs (regardless of the source format). No gallery/GPU dependency.+ let outData = result.data;+ let outFormat = result.format;+ let outMime = result.mimeType;+ let outWidth = result.width;+ let outHeight = result.height;+ const steps = [...result.steps];++ if (diffusion === 'light') {+ const light = await applyLightRegen(result.data);+ if (!light) {+ throw new ServerError('Invalid or corrupt image', {+ status: 400,+ code: 'INVALID_IMAGE',+ });+ }+ // Fidelity metric so the report can show how much the pass actually moved+ // the pixels (the pixel-delta/PSNR the diffusion research gates on) —+ // "disrupt", never "remove". Skipped silently on a decode failure.+ const delta = await computePixelDelta(result.data, light.data).catch(() => null);+ outData = light.data;+ outFormat = 'png';+ outMime = 'image/png';+ outWidth = light.width;+ outHeight = light.height;+ steps.push({+ step: 'diffusion',+ status: 'applied',+ lossless: false,+ mode: 'light',+ // ASCII-only: this rides in the X-Clean-Report HTTP header, which is+ // latin1 — a stray em-dash or delta glyph makes Node reject the send.+ detail: delta+ ? `CPU light pass - best-effort SynthID disruption (pixel delta ${delta.pixelDeltaPct}%, PSNR ${delta.psnr}dB); does not guarantee removal`+ : 'CPU light pass - best-effort SynthID disruption; does not guarantee removal',+ ...(delta ? { pixelDeltaPct: delta.pixelDeltaPct, psnr: delta.psnr } : {}),+ });+ }+const report = {- format: result.format,+ format: outFormat,sizeBefore: result.sizeBefore,- sizeAfter: result.sizeAfter,- width: result.width,- height: result.height,+ sizeAfter: outData.length,+ width: outWidth,+ height: outHeight,c2paStripped: result.c2paStripped,c2paPresent: result.c2paPresent,- steps: result.steps,+ steps,};- console.log(`🧼 Image cleaned: ${result.format} ${result.sizeBefore}B → ${result.sizeAfter}B (c2pa=${result.c2paStripped}, steps=${result.steps.map((s) => s.step).join('+') || 'none'})`);+ console.log(`🧼 Image cleaned: ${outFormat} ${result.sizeBefore}B → ${outData.length}B (c2pa=${result.c2paStripped}, steps=${steps.map((s) => s.step).join('+') || 'none'})`);// Expose the report header so a cross-origin / dev-proxied fetch can read it.res.setHeader('Access-Control-Expose-Headers', 'X-Clean-Report');res.setHeader('X-Clean-Report', JSON.stringify(report));- res.setHeader('Content-Type', result.mimeType);- res.send(result.data);+ res.setHeader('Content-Type', outMime);+ res.send(outData);}),);diff --git a/server/routes/imageClean.test.js b/server/routes/imageClean.test.jsindex b0d4eb4866..021ced6818 100644--- a/server/routes/imageClean.test.js+++ b/server/routes/imageClean.test.js@@ -115,6 +115,45 @@ describe('POST /api/image-clean (raw transport)', () => {expect(report.steps.some((s) => s.step === 'denoise' && s.status === 'applied')).toBe(true);});+ it('runs the CPU light diffusion pass when ?diffusion=light and reports a fidelity delta', async () => {+ // Use the multi-MB fixture — applyLightRegen resize-squeezes then upscales,+ // which needs real pixel content (a 4×4 solid fixture floor16-collapses to+ // its own dims and can no-op the squeeze).+ const res = await postImage('?diffusion=light', largePng);+ expect(res.status).toBe(200);+ // The light pass always re-encodes to PNG regardless of source format.+ expect(res.headers['content-type']).toBe('image/png');+ const report = reportOf(res);+ const diff = report.steps.find((s) => s.step === 'diffusion');+ expect(diff).toBeTruthy();+ expect(diff.status).toBe('applied');+ expect(diff.mode).toBe('light');+ expect(diff.lossless).toBe(false);+ // Fidelity metric attached so the report never claims "removed".+ expect(typeof diff.pixelDeltaPct).toBe('number');+ expect(typeof diff.psnr).toBe('number');+ expect(report.format).toBe('png');+ });++ it('runs metadata + denoise + diffusion in pipeline order when all are selected', async () => {+ const res = await postImage('?metadata=1&denoise=1&diffusion=light', largePng);+ expect(res.status).toBe(200);+ const report = reportOf(res);+ expect(report.steps.map((s) => s.step)).toEqual(['metadata', 'denoise', 'diffusion']);+ });++ it('rejects GPU diffusion with 501 NOT_IMPLEMENTED (deferred to a follow-up)', async () => {+ const res = await postImage('?diffusion=gpu', pngFixture);+ expect(res.status).toBe(501);+ expect(res.body.code).toBe('NOT_IMPLEMENTED');+ });++ it('treats an unknown diffusion value as off (no diffusion step)', async () => {+ const res = await postImage('?diffusion=banana', pngFixture);+ expect(res.status).toBe(200);+ expect(reportOf(res).steps.some((s) => s.step === 'diffusion')).toBe(false);+ });+it('runs no steps and passes bytes through when ?metadata=0&denoise=0', async () => {const res = await postImage('?metadata=0&denoise=0', pngWithC2PA);expect(res.status).toBe(200);