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
refactor: share image cleaner defaults across browser and server (#8556)
[._.]/ Adam Eivy6cfe5d26419a
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 18fcda6f9c..e53101f77d 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -69,7 +69,7 @@ grep -i "what you want to do" client/src/lib/README.md| `glbFailure.js` | Turns a 3D asset failure into an actionable sentence. `glbFailureHint(error)` matches the message against a shared table (an HTML body reaching the glTF parser, a WebGL context failure, a 404) and returns `null` when nothing recognizes it — so a caller can tell "we know the cause" from "we don't" and fall back to the raw text. `glbErrorText(error)` reads a message off whatever shape was thrown. Shared because the CoS avatars load remote GLBs too: every caught error there used to be reported as "this display has no WebGL", sending the user to change an unrelated setting (#4688). Consumed by `media/GlbViewer.jsx` and `cos/CoSCanvasGuard.jsx`. || `grokVideoClip.js` | Re-export of `server/lib/grokVideoClip.js` — `GROK_VIDEO_DURATIONS` (`[6, 10]`) + `GROK_VIDEO_DEFAULT_DURATION`, the clip lengths grok's `image_to_video` actually delivers. || `reactorVideoClip.js` | Re-export of `server/lib/reactorVideoClip.js` — `REACTOR_MAX_PROMPT_LENGTH` (800, counted in the VideoGen prompt field before submit), `REACTOR_MIN_CLIP_SECONDS` / `REACTOR_MAX_CLIP_SECONDS`, the picker list `REACTOR_CLIP_LENGTHS` + `REACTOR_DEFAULT_CLIP_LENGTH` + `reactorClipLengthLabel()`, and the canvas contract `REACTOR_CANVASES` / `REACTOR_ASPECTS` / `REACTOR_DEFAULT_ASPECT` / `reactorCanvas()` / `nearestReactorAspect()`. |-| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). |+| `imageCleaners.js` | Re-exports `resolveCleanersFromConfig` from the shared pure `server/lib/imageCleanDefaults.js` policy. Reads `{cleanC2PA, denoise}` off a per-mode settings record. `cleanC2PA` defaults are mode-aware (on for `codex` + `external` — the backends that emit C2PA chunks today — off otherwise, as an allow-list rather than a deny-list); `denoise` defaults off everywhere (lossy, opt-in only). || `reviewerModels.js` | `reviewerModelsFromDefaults` / `reviewerModelsToDefaults` / `reviewerEffortsFromDefaults` / `reviewerEffortsToDefaults` — adapt the Code Review Defaults' per-reviewer SCALARS (`codexModel`, `ollamaModel`, `claudeEffort`, …) to and from the token-keyed maps `ReviewerPicker`'s Model and Effort columns take. Mirrors `reviewerModelsFromDefaults` / `reviewerEffortsFromDefaults` in `server/lib/reviewerConfig.js`. Also preserves configured-provider model and effort pins in the additive `providerModels` / `providerEfforts` maps, keyed by `provider:<id>`; empty maps clear overrides without changing builtin scalars. || `reviewerPins.js` | Client mirror of the whole reviewer vocabulary — the roster (`REVIEWER_VALUES`), `REVIEWER_ALIASES`, `DEFAULT_REVIEWER(S)`, `normalizeReviewers`, the review-username pattern/cap (`MAX_REVIEW_USERNAMES` / `cleanReviewUsername` / `normalizeReviewUsernames`), `MAX_REVIEWER_MAX_ROUNDS`, `REVIEW_STOP_MODES` / `DEFAULT_REVIEW_STOP_MODE`, plus the per-reviewer pin vocabularies (`MODEL_SELECTABLE_REVIEWERS` / `EFFORT_SELECTABLE_REVIEWERS` / `REVIEWER_EFFORT_LEVELS` / `reviewerEffortLevels` / `normalizeReviewerSlug` / `sanitizeReviewerModelInput`) and their bounds. Dependency-free on purpose: the server suite imports it to pin the mirror against `server/lib/reviewerConfig.js`, so it must not reach for a client-only package. Re-exported by `components/cos/constants.js`. `isProviderReviewer` recognizes the shared `provider:<id>` identity alongside legacy harness slugs. || `loraDatasetReadiness.js` | Re-export of `server/lib/loraDataset.js` (#8297) — `MIN_TRAINING_IMAGES` / `RECOMMENDED_TRAINING_IMAGES` / `TRAINING_IMAGE_SWEET_SPOT_MAX`, `captionHasTriggerWord`, `datasetQualityTier`, `computeDatasetReadiness`, `analyzeCaptionInvariants` (+ its `INVARIANT_SHARE_THRESHOLD` / `MIN_CAPTIONS_FOR_INVARIANT_ANALYSIS`). `LoraDatasetDetail.jsx`'s live advisory (readiness summary, Train gate, shared-caption-fragment warning) calls these directly instead of a page-local mirror, so it cannot drift from the server's authoritative training gate. |diff --git a/client/src/lib/imageCleaners.js b/client/src/lib/imageCleaners.jsindex 3f05e5db61..ca5aa406ae 100644--- a/client/src/lib/imageCleaners.js+++ b/client/src/lib/imageCleaners.js@@ -1,16 +1,2 @@-// Client mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`.-// The server is authoritative — keep the two copies in sync. Used by the-// Settings ImageGenTab and the per-render ImageGen page so both surfaces-// agree on how the saved per-mode settings map into the two-flag world.-// Defaults are mode-aware: cleanC2PA defaults on only for backends that-// actually emit C2PA chunks today — codex + external. Allow-list rather-// than deny-list so a future 4th backend defaults off until confirmed.--export function resolveCleanersFromConfig(modeCfg, mode) {- const cfg = modeCfg || {};- const cleanC2PADefault = mode === 'codex' || mode === 'external';- return {- cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,- denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,- };-}+// Share the pure settings policy without importing image-processing dependencies.+export { resolveCleanersFromConfig } from '../../../server/lib/imageCleanDefaults.js';diff --git a/server/lib/README.md b/server/lib/README.mdindex 67d0c55696..48e60789b6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -351,6 +351,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `forgeIssueCli.js` | Pure `gh`/`glab` issue-filing argument shapes and output parsing — `forgeLabelCreateArgs`, `forgeIssueCreateArgs`, `parseCreatedForgeIssue` — so the two CLIs' body-flag, label-attachment, and label-create disagreements have one definition. || `forgeIssueState.js` | `normalizeIssueState(state)` — collapse a forge issue/PR/MR state string to `open`/`closed`. GitHub reports `OPEN`/`CLOSED`; GitLab reports `opened`/`closed`/`locked`; anything unrecognized is treated as open so an unfamiliar state can never read as "already resolved". Shared by `layeredIntelligence/forgeFiler.js` and `services/blockedIssueReconcile.js`. || `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |+| `imageCleanDefaults.js` | `resolveCleanersFromConfig(modeCfg, mode)` — dependency-free, shared browser/server cleaner defaults; C2PA defaults on for codex/external, denoise stays opt-in. || `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `stats-unavailable` is never memoized either — that branch catches transient probe failures too, and pinning `ok: null` on valid bytes would disable the gate for them. `__resetFrameStatsCache()` drops the memo in tests. || `imageThumbnail.js` | Lazy, single-flight WebP previews for flat gallery PNG files, refreshed when the source changes. || `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |diff --git a/server/lib/imageClean.js b/server/lib/imageClean.jsindex 7cd798b283..285a6b0654 100644--- a/server/lib/imageClean.js+++ b/server/lib/imageClean.js@@ -16,38 +16,7 @@ import { basename } from 'node:path';import { ServerError } from './errorHandler.js';import { tryReadFile, safeJSONParse, atomicWrite, detectImageFormat } from './fileUtils.js';-/**- * Read cleaner flags off a per-mode settings record. Pure: no I/O, no- * body-override layer (that's the resolver's job — this is the shared- * "what did the user save" rule that resolver + Settings UI + ImageGen- * page + test mocks all need to agree on).- *- * Defaults are mode-aware: `cleanC2PA` defaults on only for backends that- * actually emit C2PA chunks today — `codex` (gpt-image-2) and `external`- * (A1111 / Forge proxies that may re-encode through ComfyUI's C2PA stamp- * node). Allow-list rather than deny-list: a future 4th backend defaults- * off until someone confirms it emits caBX. `denoise` defaults to false- * everywhere (lossy, blurs text — must be explicitly opted into).- *- * Mirrored verbatim in `client/src/lib/imageCleaners.js` — keep the two- * copies in sync; the client tree can't import from server/lib.- */-// Backends that stamp a C2PA `caBX` chunk in current production. Grok-// (xAI Aurora) is deliberately NOT listed: unconfirmed as a C2PA emitter, so-// its renders skip the standalone strip walk even when the toggle is on —-// add it here (and flip its default) if/when confirmed. This set feeds both-// the per-mode cleanC2PA default below and the standalone-strip short-circuit-// in autoCleanGeneratedImage.-const C2PA_EMITTING_MODES = ['codex', 'external'];--export function resolveCleanersFromConfig(modeCfg, mode) {- const cfg = modeCfg || {};- const cleanC2PADefault = C2PA_EMITTING_MODES.includes(mode);- return {- cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,- denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,- };-}+export { resolveCleanersFromConfig } from './imageCleanDefaults.js';// There is intentionally no decoded-byte cap. The HTTP route streams raw bytes// through `express.raw({ limit })`, so the transport itself is the (generous)diff --git a/server/lib/imageCleanDefaults.js b/server/lib/imageCleanDefaults.jsnew file mode 100644index 0000000000..c16616bc32--- /dev/null+++ b/server/lib/imageCleanDefaults.js@@ -0,0 +1,25 @@+// Dependency-free policy shared by the server, browser, and route test doubles.++/**+ * Read cleaner flags off a per-mode settings record. Pure: no I/O, no+ * body-override layer (that's the resolver's job — this is the shared+ * "what did the user save" rule that resolver + Settings UI + ImageGen+ * page + test mocks all need to agree on).+ *+ * Defaults are mode-aware: `cleanC2PA` defaults on only for backends that+ * actually emit C2PA chunks today — `codex` (gpt-image-2) and `external`+ * (A1111 / Forge proxies that may re-encode through ComfyUI's C2PA stamp+ * node). Allow-list rather than deny-list: a future backend defaults+ * off until someone confirms it emits caBX. `denoise` defaults to false+ * everywhere (lossy, blurs text — must be explicitly opted into).+ */+const C2PA_EMITTING_MODES = ['codex', 'external'];++export function resolveCleanersFromConfig(modeCfg, mode) {+ const cfg = modeCfg || {};+ const cleanC2PADefault = C2PA_EMITTING_MODES.includes(mode);+ return {+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,+ denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,+ };+}diff --git a/server/lib/index.js b/server/lib/index.jsindex 798c466c3f..1677c01735 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -311,6 +311,7 @@ export * from './schemaVersions.js';export * from './secretText.js';export * from './piiRedactionPatterns.js';export * from './imageClean.js';+export * from './imageCleanDefaults.js';export * from './imageFrameStats.js';export * from './imageThumbnail.js';export * from './imageRgba.js';diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex a09d0e18ce..8d2e2d47fa 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';import express from 'express';+import { resolveCleanersFromConfig } from '../lib/imageCleanDefaults.js';import { request as httpRequest } from 'node:http';import { pinPlatform, request, startLoopbackServer, closeLoopbackServer } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';@@ -76,11 +77,7 @@ vi.mock('../services/imageGen/index.js', () => ({// resolver uses — keeps test mock and prod in lock-step automatically.// Legacy `autoClean: true` no longer carries into denoise (lossy, opt-in only).resolveImageCleaners: (body, settings, mode) => {- const cfg = settings?.imageGen?.[mode] || {};- const saved = {- cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,- denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,- };+ const saved = resolveCleanersFromConfig(settings?.imageGen?.[mode], mode);return {cleanC2PA: typeof body?.cleanC2PA === 'boolean' ? body.cleanC2PA : saved.cleanC2PA,denoise: typeof body?.denoise === 'boolean' ? body.denoise : saved.denoise,@@ -1025,6 +1022,24 @@ describe('Image Gen Routes', () => {expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ cleanC2PA: true, denoise: false }));});+ it.each([+ ['local', false],+ ['grok', false],+ ['agy', false],+ ['codex', true],+ ])('%s mode: omitted flags use the mode default without enabling denoise', async (mode, cleanC2PA) => {+ getSettings.mockResolvedValueOnce({+ imageGen: { mode, [mode]: { enabled: true, pythonPath: '/p' } },+ });++ const response = await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });++ expect(response.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ params: expect.objectContaining({ cleanC2PA, denoise: false }),+ }));+ });+it('local mode: body flags flow through into enqueued params', async () => {getSettings.mockResolvedValueOnce({imageGen: { mode: 'local', local: { pythonPath: '/p', cleanC2PA: false, denoise: false } },@@ -1037,14 +1052,15 @@ describe('Image Gen Routes', () => {expect(call[0].params.denoise).toBe(true);});- it('codex mode: body denoise=false overrides saved setting=true on enqueued params', async () => {+ it('codex mode: explicit false overrides enabled cleaner settings', async () => {getSettings.mockResolvedValueOnce({imageGen: { mode: 'codex', codex: { enabled: true, cleanC2PA: true, denoise: true } },});- await request(app).post('/api/image-gen/generate').send({ prompt: 'p', denoise: false });+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', cleanC2PA: false, denoise: false });const [call] = mediaJobQueue.enqueueJob.mock.calls;+ expect(call[0].params.cleanC2PA).toBe(false);expect(call[0].params.denoise).toBe(false);});