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

add character reference sheet variants via registry-driven SHEET_VARIANTS (#430)

[._.]/ Adam Eivy0dc458725fbd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1472afd95f..5d81d90d67 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- **Character reference sheets can now render in multiple styles.** Alongside the existing illustrated turnaround, characters can now also render a "Blueprint concept sheet" — annotated front/back/side/3-quarter views with close-ups of facial features, costume details, and accessories, on a clean white background with glowing accent linework over a structured base color (both colors auto-picked from the character's palette). The panel under each character in Universe Builder now shows one render row per registered variant, with its own Generate / Regenerate / Delete buttons and thumbnail. Adding a new style ("noir", "isometric", etc.) is a one-entry change in the server-side `SHEET_VARIANTS` registry plus a prompt-builder function — the UI catalog endpoint (`GET /api/universe-builder/reference-sheet-variants`) surfaces every registered variant automatically, so no new routes, schema fields, or storage shape changes are needed per variant. Storage stays back-compat: the legacy `referenceSheetImageRef` field continues to hold the illustrated turnaround, every other variant lands in a new `referenceSheets[<id>]` map. Shared `readSheetPointer` / `listSheetPointers` / `applySheetPointerToCharacter` helpers (mirrored client + server in `lib/sheetPointers.js` / `storyBible.js`) encapsulate the dual-shape read/write so every prune, purge, exporter, asset collector, and UI callback routes through one place.
- **[codex5-client-error-reporter] Browser-side errors and unhandled promise rejections surface in Review Hub.** Crashes that used to vanish into the browser console now land as Review Hub alerts so they can be triaged alongside server errors and CoS work. Repeats of the same error within a day aggregate into a single entry, and bursty render storms are throttled so the hub stays readable.
- **[codex5-dashboard-intent-layouts] Dashboard layouts for Deep Work, Health, and Agent Watch — plus a time-window "morning default."** Three new built-in layouts ship alongside Everything / Focus / Morning Review / Ops, picked for task-focus, health framing, and CoS monitoring respectively. Any layout can now carry an auto-activate window (e.g. 06:00–11:00) — when the dashboard opens during that window it loads with the matching layout selected, unless you manually picked something else today. The layout editor adds a one-click "Set as morning default" toggle and a custom time-window picker. The dashboard also surfaces inline "Add &lt;Widget&gt;?" suggestion chips when a layout omits a widget whose data is populated (e.g. Quick Stats shows up once you have apps registered).
- **[versioning-diff-view-per-stage-persist-last-n] Pipeline text stages now keep a version history.** Each regenerate snapshots the prior draft (up to five back) and a new "History" button on the Idea / Prose / Comic Script / Teleplay editors opens a side-by-side word diff against the current version with one-click restore.
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index a90f762650..405a0f825f 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -21,6 +21,7 @@ import {
getHfTokenStatus, saveHfToken, clearHfToken,
} from '../../services/api';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
+import { resolveCleanersFromConfig } from '../../lib/imageCleaners';
const SDAPI_TOOL_ID = 'sdapi';
const CODEX_TOOL_ID = 'codex-imagegen';
@@ -49,14 +50,19 @@ 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 [autoCleanByMode, setAutoCleanByMode] = useState({ external: false, local: false, codex: false });
- const setAutoCleanFor = (m) => (v) => setAutoCleanByMode((p) => ({ ...p, [m]: v }));
+ // Per-provider cleaner toggles. Both run after the PNG lands and before
+ // the SSE complete event so subscribers see the cleaned bytes. SynthID
+ // (the gpt-image / Imagen / Gemini pixel-level watermark) is unaffected
+ // by either of these — a future "Clean SynthID" diffusion option will
+ // address it separately.
+ // - cleanC2PA (default ON): byte-level strip of the gpt-image `caBX`
+ // provenance chunk. Lossless — pixels untouched.
+ // - denoise (default OFF): median(3) + sharpen pass for AI-artifact
+ // reduction. LOSSY: blurs annotation text and small details.
+ const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true });
+ const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false });
+ const setCleanC2PAFor = (m) => (v) => setCleanC2PAByMode((p) => ({ ...p, [m]: v }));
+ const setDenoiseFor = (m) => (v) => setDenoiseByMode((p) => ({ ...p, [m]: v }));
// 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');
@@ -74,7 +80,8 @@ export function ImageGenTab() {
const [saved, setSaved] = useState({
mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', exposeA1111: false,
codexEnabled: false, codexPath: '', codexModel: '', codexParallelLimit: 1,
- autoCleanByMode: { external: false, local: false, codex: false },
+ cleanC2PAByMode: { external: true, local: true, codex: true },
+ denoiseByMode: { external: false, local: false, codex: false },
});
const [status, setStatus] = useState(null);
@@ -147,11 +154,14 @@ export function ImageGenTab() {
: PARALLEL_FALLBACK;
setParallelBounds(bounds);
const cxParallel = clampParallel(cx.parallelLimit, bounds);
- const ac = {
- codex: cx.autoClean === true,
- local: ig.local?.autoClean === true,
- external: ig.external?.autoClean === true,
- };
+ // Per-mode cleaner reads via the shared helper (mirrored from
+ // server/lib/imageClean.js). Handles the legacy `autoClean: true` →
+ // both-flags migration for users upgrading from before the split.
+ const codexClean = resolveCleanersFromConfig(cx);
+ const localClean = resolveCleanersFromConfig(ig.local);
+ const externalClean = resolveCleanersFromConfig(ig.external);
+ const c2 = { codex: codexClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };
+ const dn = { codex: codexClean.denoise, local: localClean.denoise, external: externalClean.denoise };
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -161,12 +171,13 @@ export function ImageGenTab() {
setCodexModel(cxModel);
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
- setAutoCleanByMode(ac);
+ setCleanC2PAByMode(c2);
+ setDenoiseByMode(dn);
setSaved({
mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel,
codexParallelLimit: cxParallel,
- autoCleanByMode: ac,
+ cleanC2PAByMode: c2, denoiseByMode: dn,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
@@ -191,9 +202,12 @@ export function ImageGenTab() {
|| codexPath !== saved.codexPath
|| codexModel !== saved.codexModel
|| codexParallelLimit !== saved.codexParallelLimit
- || autoCleanByMode.codex !== saved.autoCleanByMode.codex
- || autoCleanByMode.local !== saved.autoCleanByMode.local
- || autoCleanByMode.external !== saved.autoCleanByMode.external;
+ || cleanC2PAByMode.codex !== saved.cleanC2PAByMode.codex
+ || cleanC2PAByMode.local !== saved.cleanC2PAByMode.local
+ || cleanC2PAByMode.external !== saved.cleanC2PAByMode.external
+ || denoiseByMode.codex !== saved.denoiseByMode.codex
+ || denoiseByMode.local !== saved.denoiseByMode.local
+ || denoiseByMode.external !== saved.denoiseByMode.external;
const handleSave = async () => {
setSaving(true);
@@ -204,11 +218,11 @@ export function ImageGenTab() {
const patch = {
imageGen: {
mode,
- external: { sdapiUrl: url, autoClean: autoCleanByMode.external },
- local: { pythonPath: pythonPath || undefined, autoClean: autoCleanByMode.local },
+ external: { sdapiUrl: url, cleanC2PA: cleanC2PAByMode.external, denoise: denoiseByMode.external },
+ local: { pythonPath: pythonPath || undefined, cleanC2PA: cleanC2PAByMode.local, denoise: denoiseByMode.local },
codex: {
enabled: codexEnabled, codexPath: cxPath, model: cxModel, parallelLimit: cxParallel,
- autoClean: autoCleanByMode.codex,
+ cleanC2PA: cleanC2PAByMode.codex, denoise: denoiseByMode.codex,
},
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
@@ -226,7 +240,7 @@ export function ImageGenTab() {
mode, sdapiUrl: url || '', pythonPath, exposeA1111,
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '',
codexParallelLimit: cxParallel,
- autoCleanByMode,
+ cleanC2PAByMode, denoiseByMode,
});
if (cxParallel !== codexParallelLimit) {
setCodexParallelLimit(cxParallel);
@@ -427,7 +441,12 @@ 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={autoCleanByMode.external} onChange={setAutoCleanFor(IMAGE_GEN_MODE.EXTERNAL)} />
+ <CleanersToggles
+ cleanC2PA={cleanC2PAByMode.external}
+ denoise={denoiseByMode.external}
+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.EXTERNAL)}
+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.EXTERNAL)}
+ />
</div>
)}
@@ -441,7 +460,12 @@ 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={autoCleanByMode.local} onChange={setAutoCleanFor(IMAGE_GEN_MODE.LOCAL)} />
+ <CleanersToggles
+ cleanC2PA={cleanC2PAByMode.local}
+ denoise={denoiseByMode.local}
+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.LOCAL)}
+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.LOCAL)}
+ />
</div>
)}
@@ -536,7 +560,12 @@ export function ImageGenTab() {
)}
</p>
</div>
- <AutoCleanToggle checked={autoCleanByMode.codex} onChange={setAutoCleanFor(IMAGE_GEN_MODE.CODEX)} />
+ <CleanersToggles
+ cleanC2PA={cleanC2PAByMode.codex}
+ denoise={denoiseByMode.codex}
+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.CODEX)}
+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.CODEX)}
+ />
</div>
)}
</div>
@@ -740,28 +769,45 @@ 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 }) {
+// Per-provider post-render cleaner toggles. Both 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. A future "Clean SynthID"
+// diffusion option will join this group when ready.
+function CleanersToggles({ cleanC2PA, denoise, onCleanC2PAChange, onDenoiseChange }) {
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.
+ <div className="space-y-2 pt-1">
+ <label className="flex items-start gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={cleanC2PA}
+ onChange={(e) => onCleanC2PAChange(e.target.checked)}
+ className="rounded mt-0.5"
+ />
+ <span className="text-sm text-gray-300">
+ Clean C2PA
+ <span className="block text-xs text-gray-500 mt-0.5">
+ Strip the gpt-image <code>caBX</code> provenance chunk. Lossless — pixels untouched, only metadata removed. Safe to leave on; recommended for renders you'll share publicly.
+ </span>
</span>
- </span>
- </label>
+ </label>
+ <label className="flex items-start gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={denoise}
+ onChange={(e) => onDenoiseChange(e.target.checked)}
+ className="rounded mt-0.5"
+ />
+ <span className="text-sm text-gray-300">
+ Denoise (median + sharpen)
+ <span className="block text-xs text-gray-500 mt-0.5">
+ Smooths AI-generation artifacts with a median filter + sharpen pass. <span className="text-port-warning">Warning: lossy — blurs annotation text, small labels, and fine detail.</span> Implicitly also strips C2PA. Skip this for renders with text (concept sheets, infographics, comic panels).
+ </span>
+ </span>
+ </label>
+ <p className="text-[11px] text-gray-500 italic mt-1">
+ Neither option defeats SynthID — gpt-image / Imagen renders stay detectable by their vendor watermark checkers. A "Clean SynthID" diffusion option is planned separately.
+ </p>
+ </div>
);
}
diff --git a/client/src/components/universe/CharacterReferenceSheetPanel.jsx b/client/src/components/universe/CharacterReferenceSheetPanel.jsx
index 168d6ed3e5..e7a11e3983 100644
--- a/client/src/components/universe/CharacterReferenceSheetPanel.jsx
+++ b/client/src/components/universe/CharacterReferenceSheetPanel.jsx
@@ -1,33 +1,40 @@
/**
* Character Reference Sheet panel — embeds inside the universe Cast section.
*
- * Shows the existing sheet (if any) as a thumbnail that opens a lightbox, plus
- * a Generate / Regenerate button that kicks off the render. The renderer is
- * text-template-based and works across codex + local image-gen modes (the
- * user's current Image Gen setting decides). Subscribes to media-job SSE
- * for live progress; calls `onSheetCompleted(entryId, filename)` so the
- * parent can drop the new filename into the universe draft without needing
- * a fresh GET (the server has already persisted it).
+ * The panel reads the server's variant catalog (`GET /reference-sheet-variants`)
+ * on mount and renders one self-contained row per variant. Each row tracks
+ * its own in-flight render job, HEAD-poll, and completion callback so a
+ * blueprint render can be in flight while a standard sheet is showing, etc.
+ * Adding a new variant on the server (e.g. 'noir') lights up a new row here
+ * automatically — no client code changes needed.
+ *
+ * Storage shape on `entry`:
+ * - `entry.referenceSheetImageRef` → legacy 'standard' variant
+ * - `entry.referenceSheets[<id>]` → every other variant
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Camera, Loader2, RefreshCcw, ExternalLink, Trash2 } from 'lucide-react';
import {
renderCharacterReferenceSheet,
deleteCharacterReferenceSheet,
+ fetchReferenceSheetVariants,
} from '../../services/apiUniverseBuilder';
import useMediaJobProgress from '../../hooks/useMediaJobProgress';
import useMounted from '../../hooks/useMounted';
+import { readSheetPointer, LEGACY_SHEET_VARIANT_ID } from '../../lib/sheetPointers';
import toast from '../ui/Toast';
// HEAD-poll for the rendered sheet at its destination URL, with backoff. The
// server-side onSheetComplete listener copies the gallery PNG into
// /data/image-refs/ AFTER the SSE 'completed' event fires (the listener is
// async, the event was sync), so claiming the file exists at SSE-completion
-// time races and shows a 404 thumbnail. Returns true once the file is
-// reachable, false after ~3s of polling, or `null` when the signal aborts
-// (so the caller can distinguish "give up + warn the user" from "navigated
-// away, ignore").
+// time races and shows a 404 thumbnail. Returns true once reachable, false
+// after the budget elapses, or `null` when the caller aborts (lets the
+// caller distinguish "give up + warn" from "navigated away, ignore").
+//
+// `cache: 'no-store'` is load-bearing — without it, the browser caches a
+// transient 404 and poisons subsequent <img> requests for the same URL.
async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150, signal } = {}) {
if (!filename) return false;
if (signal?.aborted) return null;
@@ -35,9 +42,6 @@ async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150, signa
const deadline = Date.now() + maxMs;
while (Date.now() < deadline) {
if (signal?.aborted) return null;
- // cache: 'no-store' so a transient 404 isn't cached by the browser and
- // poisoning subsequent <img> tags. `signal` aborts the in-flight HEAD too
- // (not just the inter-attempt sleep).
const res = await fetch(url, { method: 'HEAD', cache: 'no-store', signal })
.catch(() => null);
if (signal?.aborted) return null;
@@ -50,30 +54,31 @@ async function waitForImageRef(filename, { maxMs = 3000, intervalMs = 150, signa
return false;
}
-export default function CharacterReferenceSheetPanel({
- universeId, entry, locked, onSheetCompleted, onSheetDeleted, onOpenLightbox,
+// One self-contained render row per variant — owns its jobId + HEAD-poll
+// so a render in this variant cannot collide with a parallel render of a
+// different variant for the same character. Local to this module.
+function VariantRow({
+ variant, universeId, entry, locked, onSheetCompleted, onSheetDeleted, onOpenLightbox,
}) {
- const existing = entry?.referenceSheetImageRef || null;
+ const existing = useMemo(() => readSheetPointer(entry, variant.id), [entry, variant.id]);
const [jobId, setJobId] = useState(null);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [deleting, setDeleting] = useState(false);
- // destFilename for the in-flight render — captured from the route response
- // so the SSE-completion handler can pass the real refs-dir filename up to
- // the parent without a universe refetch.
+ // Captured at render-start so the SSE-completion handler can pass the
+ // image-refs filename up to the parent — the SSE event itself names the
+ // gallery copy in /data/images/, which is a different path.
const destFilenameRef = useRef(null);
- // Prevent the completion callback from firing twice under React 18 StrictMode
- // dev double-mount.
+ // Prevent the completion callback from firing twice under React 18
+ // StrictMode dev double-mount.
const settledRef = useRef(null);
// mountedRef gates the post-completion HEAD-poll callback so an unmount
- // (universe switch, parent collapsing the section, etc.) mid-poll doesn't
- // fire `onSheetCompleted` against a stale entry/universe. useMounted resets
- // the ref to true on every effect setup — a plain `useRef(true)` plus a
- // cleanup-only effect leaves the ref permanently false after React 18
- // StrictMode's mount→cleanup→remount cycle in dev.
+ // (universe switch, parent collapse) mid-poll doesn't fire onSheetCompleted
+ // against a stale entry/universe. useMounted resets on every effect setup —
+ // a plain useRef(true) + cleanup-only effect leaves it false after
+ // StrictMode's mount→cleanup→remount dev cycle.
const mountedRef = useMounted();
- // Cancels the in-flight `waitForImageRef` HEAD-poll loop on unmount or on
- // a new render kicking off. Without this the loop keeps issuing requests
- // against a dead component for the full ~3s budget.
+ // Cancels the in-flight HEAD-poll loop on unmount or new render kicking off;
+ // without it the loop keeps issuing requests against a dead component.
const pollAbortRef = useRef(null);
const { status, filename, error, progress } = useMediaJobProgress(jobId);
@@ -87,19 +92,14 @@ export default function CharacterReferenceSheetPanel({
const entryId = entry?.id;
destFilenameRef.current = null;
setJobId(null);
- // The SSE 'completed' event fires when the image-gen child exits —
- // BEFORE the server-side onSheetComplete listener has copied the
- // gallery PNG into /data/image-refs/ and stamped the character.
- // Verify the file is actually reachable before flipping the UI;
- // otherwise the <img> renders a 404 that the browser caches.
pollAbortRef.current?.abort();
const controller = new AbortController();
pollAbortRef.current = controller;
waitForImageRef(dest, { signal: controller.signal }).then((ok) => {
if (pollAbortRef.current === controller) pollAbortRef.current = null;
if (!mountedRef.current) return;
- if (ok === null) return; // aborted — caller already moved on
- if (ok) onSheetCompleted?.(entryId, dest);
+ if (ok === null) return;
+ if (ok) onSheetCompleted?.(entryId, dest, variant.id);
else toast.error('Sheet render finished but the image never appeared — refresh to see it');
});
} else if (status === 'failed' || status === 'canceled') {
@@ -108,40 +108,34 @@ export default function CharacterReferenceSheetPanel({
toast.error(`Sheet render failed: ${error || status}`);
setJobId(null);
}
- }, [jobId, status, filename, error, entry?.id, onSheetCompleted]);
+ }, [jobId, status, filename, error, entry?.id, variant.id, onSheetCompleted, mountedRef]);
- // Abort any in-flight HEAD poll when the panel unmounts.
useEffect(() => () => { pollAbortRef.current?.abort(); }, []);
const handleDelete = async () => {
if (deleting || !universeId || !entry?.id || !existing) return;
setDeleting(true);
- const result = await deleteCharacterReferenceSheet(universeId, entry.id, { silent: true })
+ const result = await deleteCharacterReferenceSheet(universeId, entry.id, {
+ variant: variant.id, silent: true,
+ })
.catch((err) => { toast.error(err.message || 'Failed to delete reference sheet'); return null; })
.finally(() => { setDeleting(false); });
if (!result) return;
setConfirmingDelete(false);
- onSheetDeleted?.(entry.id);
- toast.success(`Deleted reference sheet for ${entry.name}`);
+ onSheetDeleted?.(entry.id, variant.id);
+ toast.success(`Deleted ${variant.label} for ${entry.name}`);
};
const handleGenerate = async () => {
if (jobId || !universeId || !entry?.id) return;
- const queued = await renderCharacterReferenceSheet(universeId, entry.id)
+ const queued = await renderCharacterReferenceSheet(universeId, entry.id, { variant: variant.id })
.catch((err) => { toast.error(err.message || 'Sheet render failed to start'); return null; });
if (!queued?.jobId) return;
- // Abort the previous render's in-flight HEAD poll ONLY after the new
- // render is successfully queued. Aborting up-front would discard the
- // previous render's `onSheetCompleted` call if the new render-start
- // failed; aborting here only sacrifices it when we're about to replace
- // the displayed filename anyway. This also closes the supersede race —
- // a poll that fires after we've moved on can't call back with a stale
- // filename the server-side check refused to stamp.
pollAbortRef.current?.abort();
pollAbortRef.current = null;
destFilenameRef.current = queued.destFilename || null;
setJobId(queued.jobId);
- toast.success(`Rendering reference sheet for ${entry.name}…`);
+ toast.success(`Rendering ${variant.label.toLowerCase()} for ${entry.name}…`);
};
const inFlight = !!jobId;
@@ -150,11 +144,11 @@ export default function CharacterReferenceSheetPanel({
: '';
return (
- <div className="mt-2 rounded border border-port-border bg-port-bg/50 p-2">
+ <div className="rounded border border-port-border bg-port-bg/50 p-2">
<div className="flex items-center justify-between gap-2">
- <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-gray-500">
+ <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-gray-500" title={variant.description || ''}>
<Camera size={11} />
- Reference sheet
+ {variant.label}
</div>
<div className="flex items-center gap-1">
{confirmingDelete ? (
@@ -174,7 +168,7 @@ export default function CharacterReferenceSheetPanel({
className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-error/60 text-port-error hover:bg-port-error/15 disabled:opacity-40"
>
{deleting ? <Loader2 size={10} className="animate-spin" /> : <Trash2 size={10} />}
- {deleting ? 'Deleting' : 'Delete sheet'}
+ {deleting ? 'Deleting' : 'Delete'}
</button>
</>
) : (
@@ -185,10 +179,10 @@ export default function CharacterReferenceSheetPanel({
onClick={() => setConfirmingDelete(true)}
disabled={locked}
title={locked
- ? `Unlock ${entry.name} to delete the reference sheet`
- : 'Delete the current reference sheet'}
+ ? `Unlock ${entry.name} to delete this sheet`
+ : `Delete the ${variant.label.toLowerCase()}`}
className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-400 hover:border-port-error/60 hover:text-port-error disabled:opacity-40"
- aria-label={`Delete reference sheet for ${entry.name}`}
+ aria-label={`Delete ${variant.label} for ${entry.name}`}
>
<Trash2 size={10} />
</button>
@@ -198,8 +192,8 @@ export default function CharacterReferenceSheetPanel({
onClick={handleGenerate}
disabled={inFlight || locked}
title={locked
- ? `Unlock ${entry.name} to render a reference sheet`
- : (existing ? 'Regenerate the character reference sheet' : 'Generate a character reference sheet')}
+ ? `Unlock ${entry.name} to render this sheet`
+ : (existing ? `Regenerate the ${variant.label.toLowerCase()}` : `Generate a ${variant.label.toLowerCase()}`)}
className="inline-flex items-center gap-1 px-2 py-1 text-[10px] rounded border border-port-border text-gray-300 hover:bg-port-border/40 hover:text-white disabled:opacity-40"
>
{inFlight
@@ -207,7 +201,7 @@ export default function CharacterReferenceSheetPanel({
: (existing ? <RefreshCcw size={10} /> : <Camera size={10} />)}
{inFlight
? `Rendering${pctLabel}`
- : (existing ? 'Regenerate sheet' : 'Generate sheet')}
+ : (existing ? 'Regenerate' : 'Generate')}
</button>
</>
)}
@@ -222,7 +216,7 @@ export default function CharacterReferenceSheetPanel({
>
<img
src={`/data/image-refs/${existing}`}
- alt={`${entry.name} reference sheet`}
+ alt={`${entry.name} ${variant.label}`}
className="w-full h-auto block"
loading="lazy"
/>
@@ -230,11 +224,77 @@ export default function CharacterReferenceSheetPanel({
<ExternalLink size={10} /> {existing}
</span>
</button>
- ) : !inFlight ? (
+ ) : !inFlight && variant.description ? (
<p className="mt-1.5 text-[11px] text-gray-500 italic">
- No reference sheet yet. Click <span className="text-gray-300">Generate sheet</span> to render a multi-view turnaround, expression progression, color palette, wardrobe + prop cards, and hand gestures — all in the universe's style.
+ {variant.description}
</p>
) : null}
</div>
);
}
+
+// Module-level catalog cache + in-flight fetch promise so the GET fires once
+// per page session — every character row reads the same variant list. Without
+// this, opening a 30-character cast would hammer the catalog endpoint 30
+// times on initial render.
+let _variantCache = null;
+let _variantInflight = null;
+function getVariantCatalog() {
+ if (_variantCache) return Promise.resolve(_variantCache);
+ if (_variantInflight) return _variantInflight;
+ _variantInflight = fetchReferenceSheetVariants({ silent: true })
+ .then((res) => {
+ _variantCache = Array.isArray(res?.variants) ? res.variants : [];
+ return _variantCache;
+ })
+ .catch((err) => {
+ console.error('Failed to load reference-sheet variant catalog', err);
+ // Fallback to the legacy standard-only catalog so the panel still
+ // works against an older server that hasn't shipped the registry yet.
+ _variantCache = [{ id: LEGACY_SHEET_VARIANT_ID, label: 'Reference sheet', description: '' }];
+ return _variantCache;
+ })
+ .finally(() => { _variantInflight = null; });
+ return _variantInflight;
+}
+
+export default function CharacterReferenceSheetPanel({
+ universeId, entry, locked, onSheetCompleted, onSheetDeleted, onOpenLightbox,
+}) {
+ const [variants, setVariants] = useState(() => _variantCache);
+ const mountedRef = useMounted();
+
+ useEffect(() => {
+ if (variants) return undefined;
+ let alive = true;
+ getVariantCatalog().then((list) => {
+ if (alive && mountedRef.current) setVariants(list);
+ });
+ return () => { alive = false; };
+ }, [variants, mountedRef]);
+
+ if (!variants || variants.length === 0) {
+ return (
+ <div className="mt-2 rounded border border-port-border bg-port-bg/50 p-2 text-[11px] text-gray-500 italic">
+ Loading reference sheet variants…
+ </div>
+ );
+ }
+
+ return (
+ <div className="mt-2 space-y-2">
+ {variants.map((variant) => (
+ <VariantRow
+ key={variant.id}
+ variant={variant}
+ universeId={universeId}
+ entry={entry}
+ locked={locked}
+ onSheetCompleted={onSheetCompleted}
+ onSheetDeleted={onSheetDeleted}
+ onOpenLightbox={onOpenLightbox}
+ />
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsx
index cc9d50cad9..6b2db9a191 100644
--- a/client/src/components/universe/UniverseCanonSection.jsx
+++ b/client/src/components/universe/UniverseCanonSection.jsx
@@ -36,6 +36,7 @@ import CanonCard from '../pipeline/CanonCard';
import { pipelineImageCfgToRenderOpts } from '../../lib/pipelineImageDefaults';
import { universeStylePreset } from '../../lib/universeStylePreset';
import { descriptorForCanonEntry } from '../../lib/canonPrompt';
+import { applySheetPointer } from '../../lib/sheetPointers';
import { BIBLE_LIMITS } from '../../lib/bibleLimits';
const capImageRefs = (refs) => (
@@ -323,26 +324,22 @@ export default function UniverseCanonSection({
// Read from `latestUniverseRef` (not closed-over `universe`) so an edit
// that landed during the panel's HEAD-poll wait isn't clobbered by an
// older snapshot. No deps on `universe` keeps the callback stable.
- const handleSheetCompleted = useCallback((entryId, destFilename) => {
+ const handleSheetCompleted = useCallback((entryId, destFilename, variant) => {
const latest = latestUniverseRef.current;
if (!latest || !destFilename) return;
const nextCharacters = (latest.characters || []).map((c) =>
- c.id === entryId ? { ...c, referenceSheetImageRef: destFilename } : c,
+ c.id === entryId ? applySheetPointer(c, variant, destFilename) : c,
);
onUniverseChange({ ...latest, characters: nextCharacters });
const entryName = nextCharacters.find((c) => c.id === entryId)?.name || 'Character';
toast.success(`${entryName} reference sheet ready`);
}, [onUniverseChange]);
- // Server already deleted the file + purged the pointer via the DELETE
- // route. Mirror the change into the local draft so the thumbnail clears
- // without a refetch. Reads from `latestUniverseRef` for the same staleness
- // reason as `handleSheetCompleted`.
- const handleSheetDeleted = useCallback((entryId) => {
+ const handleSheetDeleted = useCallback((entryId, variant) => {
const latest = latestUniverseRef.current;
if (!latest) return;
const nextCharacters = (latest.characters || []).map((c) =>
- c.id === entryId ? { ...c, referenceSheetImageRef: null } : c,
+ c.id === entryId ? applySheetPointer(c, variant, null) : c,
);
onUniverseChange({ ...latest, characters: nextCharacters });
}, [onUniverseChange]);
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index ec2cfa3dec..8ad48ade15 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -28,8 +28,10 @@ grep -i "what you want to do" client/src/lib/README.md
| `composeStyledPrompt.js` | Compose user prompt + negative with an optional style preset. |
| `cleanPlatePrompt.js` | Clean-plate prompt builder for setting canon entries (Cluster A — A4). |
| `seasonStructure.js` | Mirror of `server/lib/seasonStructure.js`. |
+| `sheetPointers.js` | Mirror of the character-sheet pointer helpers from `server/lib/storyBible.js`. `LEGACY_SHEET_VARIANT_ID` + `readSheetPointer` / `listSheetPointers` / `applySheetPointer` for traversing both the legacy `referenceSheetImageRef` field and the `referenceSheets` map. |
| `universeStylePreset.js` | Build the client-side style preset that `composeStyledPrompt` layers on top. |
| `bibleLimits.js` | Mirror of `server/lib/storyBible.js` `BIBLE_LIMITS`. |
+| `imageCleaners.js` | Mirror of `resolveCleanersFromConfig` from `server/lib/imageClean.js`. Reads `{cleanC2PA, denoise}` off a per-mode settings record + handles the legacy `autoClean: true` migration. |
| `runnerFamilies.js` | Mirror of `server/lib/runners.js`. |
| `issueLength.js` | Mirror of `server/lib/issueLength.js`. |
diff --git a/client/src/lib/imageCleaners.js b/client/src/lib/imageCleaners.js
new file mode 100644
index 0000000000..23507b93a5
--- /dev/null
+++ b/client/src/lib/imageCleaners.js
@@ -0,0 +1,14 @@
+// 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,
+// including the legacy `autoClean: true` → both-flags migration.
+
+export function resolveCleanersFromConfig(modeCfg) {
+ const cfg = modeCfg || {};
+ const legacy = cfg.autoClean === true;
+ return {
+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,
+ denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : legacy,
+ };
+}
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 65571f90d8..530ab20b4e 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -8,10 +8,12 @@ export * from './cleanPlatePrompt.js';
export * from './composeStyledPrompt.js';
export * from './scenePrompt.js';
export * from './seasonStructure.js';
+export * from './sheetPointers.js';
export * from './universeStylePreset.js';
// === Pipeline / image-gen defaults ===
export * from './bibleLimits.js';
+export * from './imageCleaners.js';
export * from './imageGenBackends.js';
export * from './imageGenResolutions.js';
export * from './issueLength.js';
diff --git a/client/src/lib/sheetPointers.js b/client/src/lib/sheetPointers.js
new file mode 100644
index 0000000000..5a7d80a1f8
--- /dev/null
+++ b/client/src/lib/sheetPointers.js
@@ -0,0 +1,51 @@
+// Client mirror of the sheet-pointer storage helpers from
+// `server/lib/storyBible.js`. The server is authoritative — when the storage
+// shape changes (legacy `referenceSheetImageRef` field vs `referenceSheets`
+// map slots), update both sides verbatim.
+
+export const LEGACY_SHEET_VARIANT_ID = 'standard';
+
+const isPlainObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
+
+export function readSheetPointer(character, variant) {
+ if (!character) return null;
+ if (variant === LEGACY_SHEET_VARIANT_ID) return character.referenceSheetImageRef || null;
+ if (!isPlainObject(character.referenceSheets)) return null;
+ return character.referenceSheets[variant] || null;
+}
+
+export function listSheetPointers(character) {
+ if (!character) return [];
+ const out = [];
+ if (character.referenceSheetImageRef) {
+ out.push({ variant: LEGACY_SHEET_VARIANT_ID, filename: character.referenceSheetImageRef });
+ }
+ if (isPlainObject(character.referenceSheets)) {
+ for (const [variant, filename] of Object.entries(character.referenceSheets)) {
+ if (filename) out.push({ variant, filename });
+ }
+ }
+ return out;
+}
+
+// Returns the same character reference when the slot already holds the target
+// value, so React subscribers downstream of `setUniverse` can short-circuit
+// the re-render — a duplicate SSE 'completed' under StrictMode dev double-mount
+// (or a poll-then-server-stamp race) would otherwise churn the canon list.
+export function applySheetPointer(character, variant, filename) {
+ if (!character) return character;
+ const v = variant || LEGACY_SHEET_VARIANT_ID;
+ if (v === LEGACY_SHEET_VARIANT_ID) {
+ const next = filename || null;
+ if ((character.referenceSheetImageRef || null) === next) return character;
+ return { ...character, referenceSheetImageRef: next };
+ }
+ const existing = isPlainObject(character.referenceSheets) ? character.referenceSheets : {};
+ if (filename) {
+ if (existing[v] === filename) return character;
+ return { ...character, referenceSheets: { ...existing, [v]: filename } };
+ }
+ if (!(v in existing)) return character;
+ const { [v]: _dropped, ...rest } = existing;
+ return { ...character, referenceSheets: rest };
+}
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index e644d91917..55dd1fcff9 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -34,6 +34,7 @@ import {
} from 'lucide-react';
import { composeStyledPrompt } from '../lib/composeStyledPrompt';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
+import { resolveCleanersFromConfig } from '../lib/imageCleaners';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import { useImageGenProgress } from '../hooks/useImageGenProgress';
@@ -156,18 +157,19 @@ 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);
- // Saved per-mode default — keeps the "(overrides saved default)" hint
+ // Per-render cleaner overrides. Seeded from
+ // `settings.imageGen.{mode}.{cleanC2PA,denoise}` whenever the active mode
+ // changes; the user can flip the checkboxes to override the saved defaults
+ // for this submit. The server's /generate route stamps the resolved values
+ // into the payload so all three dispatch paths see the same booleans.
+ const [cleanC2PA, setCleanC2PA] = useState(true);
+ const [denoise, setDenoise] = useState(false);
+ // Saved per-mode defaults — keeps the "(overrides saved default)" hint
// reactive to settings reloads. Held as state (not a ref) so when the user
// edits a saved default in the Settings drawer and closes it, the hint
- // re-evaluates even if `autoClean` happens to match the new saved value.
- const [savedAutoCleanByMode, setSavedAutoCleanByMode] = useState({});
+ // re-evaluates even if the local state happens to match the new saved value.
+ const [savedCleanC2PAByMode, setSavedCleanC2PAByMode] = useState({});
+ const [savedDenoiseByMode, setSavedDenoiseByMode] = useState({});
const [generating, setGenerating] = useState(false);
const [statusMsg, setStatusMsg] = useState('');
@@ -240,11 +242,17 @@ export default function ImageGen() {
const reloadBackends = useCallback(() => {
return getSettings().then((s) => {
const backends = deriveAvailableBackends(s);
- const savedMap = {
- external: s?.imageGen?.external?.autoClean === true,
- local: s?.imageGen?.local?.autoClean === true,
- codex: s?.imageGen?.codex?.autoClean === true,
+ // Per-mode saved defaults via the shared helper (mirrored from
+ // server/lib/imageClean.js). Handles the legacy `autoClean: true` →
+ // both-flags migration. One pass per mode, then split into the
+ // parallel cleanC2PA / denoise maps the UI binds to.
+ const perMode = {
+ external: resolveCleanersFromConfig(s?.imageGen?.external),
+ local: resolveCleanersFromConfig(s?.imageGen?.local),
+ codex: resolveCleanersFromConfig(s?.imageGen?.codex),
};
+ const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA };
+ const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise };
const saved = s?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
// If the user just disabled the currently-selected backend, fall
// through to the first viable one — a just-toggled provider should
@@ -257,19 +265,22 @@ export default function ImageGen() {
: backends.length ? backends[0].id
: saved;
setAvailableBackends(backends);
- setSavedAutoCleanByMode(savedMap);
+ setSavedCleanC2PAByMode(c2);
+ setSavedDenoiseByMode(dn);
setSelectedMode(next);
- setAutoClean(savedMap[next] === true);
+ setCleanC2PA(c2[next] === true);
+ setDenoise(dn[next] === true);
}).catch(() => {});
}, []);
- // Re-seed the autoClean checkbox when the user manually picks a different
+ // Re-seed the cleaner checkboxes when the user manually picks a different
// backend chip — without this, switching external→local would leave the
- // external autoClean value in the form.
+ // external values in the form.
const handleSelectMode = useCallback((next) => {
setSelectedMode(next);
- setAutoClean(savedAutoCleanByMode[next] === true);
- }, [savedAutoCleanByMode]);
+ setCleanC2PA(savedCleanC2PAByMode[next] === true);
+ setDenoise(savedDenoiseByMode[next] === true);
+ }, [savedCleanC2PAByMode, savedDenoiseByMode]);
useEffect(() => {
listImageModels().then((m) => {
@@ -586,7 +597,7 @@ export default function ImageGen() {
negativePrompt: composed.negativePrompt || undefined,
width, height,
mode: IMAGE_GEN_MODE.CODEX,
- autoClean,
+ cleanC2PA, denoise,
} : {
prompt: composed.prompt,
negativePrompt: composed.negativePrompt || undefined,
@@ -599,7 +610,7 @@ export default function ImageGen() {
loraFilenames: selectedLoras.map((l) => l.filename),
loraScales: selectedLoras.map((l) => l.scale),
mode: IMAGE_GEN_MODE.LOCAL,
- autoClean,
+ cleanC2PA, denoise,
};
const hasInitImage = isLocalMode && initImage.source != null;
// Multi-reference editing is FLUX.2-only; gate the slot read so it can't
@@ -743,7 +754,7 @@ export default function ImageGen() {
steps: steps ? Number(steps) : 25,
cfgScale,
mode: IMAGE_GEN_MODE.EXTERNAL,
- autoClean,
+ cleanC2PA, denoise,
};
if (seed && Number(seed) >= 0) payload.seed = Number(seed);
const data = await generateImage(payload);
@@ -1168,23 +1179,42 @@ 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>
+ <div className="flex flex-col gap-1 text-xs text-gray-400">
+ <label
+ className="flex items-center gap-2 cursor-pointer select-none"
+ title="Lossless strip of the gpt-image C2PA provenance chunk. Pixels untouched. Overrides the saved Settings → Image Gen default for this render only."
+ >
+ <input
+ type="checkbox"
+ checked={cleanC2PA}
+ onChange={(e) => setCleanC2PA(e.target.checked)}
+ className="rounded"
+ />
+ <span>
+ Clean C2PA
+ {savedCleanC2PAByMode[effectiveMode] !== undefined && cleanC2PA !== savedCleanC2PAByMode[effectiveMode] && (
+ <span className="ml-1 text-port-warning">(overrides saved default)</span>
+ )}
+ </span>
+ </label>
+ <label
+ className="flex items-center gap-2 cursor-pointer select-none"
+ title="Median + sharpen pass for AI-artifact reduction. WARNING: blurs annotation text and small details. Skip for sheets, infographics, comic panels."
+ >
+ <input
+ type="checkbox"
+ checked={denoise}
+ onChange={(e) => setDenoise(e.target.checked)}
+ className="rounded"
+ />
+ <span>
+ Denoise <span className="text-port-warning">(blurs text)</span>
+ {savedDenoiseByMode[effectiveMode] !== undefined && denoise !== savedDenoiseByMode[effectiveMode] && (
+ <span className="ml-1 text-port-warning">(overrides saved default)</span>
+ )}
+ </span>
+ </label>
+ </div>
{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">
diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsx
index 005c88669a..632534fd37 100644
--- a/client/src/pages/UniverseBuilder.jsx
+++ b/client/src/pages/UniverseBuilder.jsx
@@ -47,6 +47,7 @@ import TabPills from '../components/ui/TabPills';
import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';
import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';
import { hasCanonDescriptorContent, descriptorForCanonEntry } from '../lib/canonPrompt';
+import { listSheetPointers } from '../lib/sheetPointers';
import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';
import { BIBLE_LIMITS } from '../lib/bibleLimits';
import {
@@ -726,10 +727,10 @@ export default function UniverseBuilder() {
const fallbackLabel = `${entry.name}${descriptor ? `: ${descriptor}` : ''}`;
const refs = Array.isArray(entry?.imageRefs) ? entry.imageRefs : [];
for (const f of refs) pushFilename(f, fallbackLabel);
- if (kind.key === 'characters' && typeof entry.referenceSheetImageRef === 'string' && entry.referenceSheetImageRef) {
- const filename = entry.referenceSheetImageRef;
- const sheetKey = `canon-sheet:${filename}`;
- if (!seen.has(sheetKey)) {
+ if (kind.key === 'characters') {
+ for (const { variant, filename } of listSheetPointers(entry)) {
+ const sheetKey = `canon-sheet:${variant}:${filename}`;
+ if (seen.has(sheetKey)) continue;
seen.add(sheetKey);
out.push({
key: sheetKey,
@@ -737,7 +738,7 @@ export default function UniverseBuilder() {
filename,
previewUrl: `/data/image-refs/${filename}`,
downloadUrl: `/data/image-refs/${filename}`,
- prompt: `${entry.name} — character reference sheet`,
+ prompt: `${entry.name} — character reference sheet (${variant})`,
});
}
}
@@ -764,14 +765,19 @@ export default function UniverseBuilder() {
// Generic filename → preview opener used by every clickable thumb on the
// page (variation grids, composite sheets, canon entries, character
// reference sheets). `opts.isSheet` forces a key match against the
- // `canon-sheet:` prefix so a basename collision with a gallery image
- // can't route the lightbox to `/data/images/` instead of
- // `/data/image-refs/`.
+ // `canon-sheet:<variant>:` prefix so a basename collision with a gallery
+ // image can't route the lightbox to `/data/images/` instead of
+ // `/data/image-refs/`. The exact variant id isn't known at this callsite
+ // (the panel reads the field; the variant only lives inside the key),
+ // so match on the `canon-sheet:` prefix + filename suffix instead of an
+ // exact equality compare. Pre-variant keys (`canon-sheet:<filename>`)
+ // still match this prefix check.
const openPreviewByFilename = useCallback((filename, opts) => {
if (!filename) return;
- const targetKey = opts?.isSheet ? `canon-sheet:${filename}` : null;
- const match = (targetKey && previewItems.find((i) => i.key === targetKey))
- || previewItems.find((i) => i.filename === filename);
+ const sheetMatch = opts?.isSheet
+ ? previewItems.find((i) => typeof i.key === 'string' && i.key.startsWith('canon-sheet:') && i.filename === filename)
+ : null;
+ const match = sheetMatch || previewItems.find((i) => i.filename === filename);
if (match) setPreview(match);
}, [previewItems, setPreview]);
// Legacy name retained for the variation/composite call sites that pass a
diff --git a/client/src/services/apiUniverseBuilder.js b/client/src/services/apiUniverseBuilder.js
index 778dc8d16b..d2870091ae 100644
--- a/client/src/services/apiUniverseBuilder.js
+++ b/client/src/services/apiUniverseBuilder.js
@@ -181,27 +181,34 @@ export const expandUniverseCharacter = (universeId, entryId, { providerId, model
body: JSON.stringify({ providerId, model }),
});
-// Kick off a character reference sheet render. Returns immediately with
-// `{ jobId, generationId, filename, path }`; the caller subscribes to media-job
-// SSE for live progress. Server-side completion handler stamps the resulting
-// filename onto `character.referenceSheetImageRef` automatically.
+// Catalog of every registered reference-sheet variant. The panel iterates
+// this on mount to render one row per variant. New variants light up
+// automatically once they're registered in the server-side SHEET_VARIANTS.
+export const fetchReferenceSheetVariants = (options = {}) =>
+ request('/universe-builder/reference-sheet-variants', options);
+
+// Kick off a character reference sheet render. `variant` selects which
+// registered style to render (defaults server-side to 'standard'); the server
+// stamps the resulting filename into the matching pointer slot
+// (`referenceSheetImageRef` for legacy 'standard', `referenceSheets[<id>]`
+// for everything else). Returns `{ jobId, generationId, variant, ... }`.
export const renderCharacterReferenceSheet = (universeId, entryId, {
- overridePrompt, overrideNegativePrompt, modelId,
+ variant, overridePrompt, overrideNegativePrompt, modelId,
} = {}) =>
request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/render-reference-sheet`, {
method: 'POST',
- body: JSON.stringify({ overridePrompt, overrideNegativePrompt, modelId }),
+ body: JSON.stringify({ variant, overridePrompt, overrideNegativePrompt, modelId }),
});
-// Delete the character's current reference sheet (file + pointer). Server
-// unlinks the PNG from /data/image-refs/ and clears every matching
-// `referenceSheetImageRef` across all universes. Returns
-// `{ filename, fileDeleted, cleared }`.
-export const deleteCharacterReferenceSheet = (universeId, entryId, options = {}) =>
- request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet`, {
+// Delete the character's reference sheet of the given variant. Variant
+// defaults server-side to 'standard'. Returns `{ filename, fileDeleted, cleared }`.
+export const deleteCharacterReferenceSheet = (universeId, entryId, { variant, ...requestOpts } = {}) => {
+ const qs = variant ? `?variant=${encodeURIComponent(variant)}` : '';
+ return request(`/universe-builder/${encodeURIComponent(universeId)}/characters/${encodeURIComponent(entryId)}/reference-sheet${qs}`, {
method: 'DELETE',
- ...options,
+ ...requestOpts,
});
+};
// Cast-wide differentiate — single LLM call rewrites every character so the
// whole cast has no visually-colliding pairs.
diff --git a/server/lib/imageClean.js b/server/lib/imageClean.js
index 2fa5f0a1a3..35b71efe20 100644
--- a/server/lib/imageClean.js
+++ b/server/lib/imageClean.js
@@ -17,6 +17,29 @@ import { basename } from 'node:path';
import { ServerError } from './errorHandler.js';
import { tryReadFile, safeJSONParse, atomicWrite } 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).
+ *
+ * Migration: legacy `autoClean: true` (single boolean, pre-split) maps to
+ * BOTH new flags. Users who opted into denoising before the split don't
+ * silently lose it on upgrade. `cleanC2PA` defaults to true (safe, lossless);
+ * `denoise` defaults to false (lossy, blurs text).
+ *
+ * Mirrored verbatim in `client/src/lib/imageCleaners.js` — keep the two
+ * copies in sync; the client tree can't import from server/lib.
+ */
+export function resolveCleanersFromConfig(modeCfg) {
+ const cfg = modeCfg || {};
+ const legacy = cfg.autoClean === true;
+ return {
+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,
+ denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : legacy,
+ };
+}
+
// 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
@@ -90,6 +113,64 @@ function pngHasC2PA(buf) {
return false;
}
+/**
+ * Lossless C2PA strip — walks PNG chunks and emits a NEW buffer containing
+ * every chunk except `caBX`. Pixels untouched, no decode, no re-encode.
+ * Output is byte-identical to input modulo the removed chunk(s).
+ *
+ * Returns `{ data, stripped, sizeBefore, sizeAfter }`:
+ * - `data` is the new buffer (or the input buffer when no strip happened).
+ * - `stripped` is true only when a `caBX` chunk was actually found and removed.
+ * - sizes reflect input vs output buffer lengths.
+ *
+ * Returns the input untouched (`stripped: false`) on non-PNG / malformed PNG /
+ * chunk-count overrun. Never throws — caller decides whether to write the
+ * result back or skip.
+ */
+export function stripPngC2PAChunk(buffer) {
+ const passThrough = { data: buffer, stripped: false, sizeBefore: buffer?.length || 0, sizeAfter: buffer?.length || 0 };
+ if (!Buffer.isBuffer(buffer) || buffer.length < 8 || detectFormat(buffer) !== 'png') {
+ return passThrough;
+ }
+ // First pass: locate every `caBX` chunk's start/end so we can splice them
+ // out into a single new buffer allocation. Real PNGs only carry one but the
+ // PNG spec doesn't forbid duplicates — handle it anyway so a defective
+ // producer can't leave provenance fragments behind.
+ const ranges = []; // [{ start, end }] of chunk bytes (length+type+data+crc) to drop
+ let offset = 8;
+ let count = 0;
+ let sawIEND = false;
+ while (offset + 8 <= buffer.length) {
+ if (++count > MAX_PNG_CHUNKS) return passThrough;
+ if (!isPngChunkType(buffer, offset + 4)) return passThrough;
+ const length = buffer.readUInt32BE(offset);
+ const chunkEnd = offset + 8 + length + 4;
+ if (chunkEnd > buffer.length) return passThrough;
+ const type = buffer.toString('ascii', offset + 4, offset + 8);
+ if (type === 'caBX') ranges.push({ start: offset, end: chunkEnd });
+ if (type === 'IEND') { sawIEND = true; break; }
+ offset = chunkEnd;
+ }
+ // If we never reached IEND the file is truncated — don't risk emitting a
+ // bad buffer. Pass through untouched and let the caller / downstream
+ // pipeline surface the corruption (e.g. via a separate decode).
+ if (!sawIEND) return passThrough;
+ if (ranges.length === 0) return passThrough;
+
+ const droppedBytes = ranges.reduce((sum, r) => sum + (r.end - r.start), 0);
+ const out = Buffer.allocUnsafe(buffer.length - droppedBytes);
+ let writeOffset = 0;
+ let readOffset = 0;
+ for (const { start, end } of ranges) {
+ buffer.copy(out, writeOffset, readOffset, start);
+ writeOffset += start - readOffset;
+ readOffset = end;
+ }
+ // Copy the tail after the last dropped chunk.
+ buffer.copy(out, writeOffset, readOffset);
+ return { data: out, stripped: true, sizeBefore: buffer.length, sizeAfter: out.length };
+}
+
const MIME_TYPES = {
png: 'image/png',
jpeg: 'image/jpeg',
@@ -159,20 +240,34 @@ export async function cleanImageBuffer(buffer) {
}
}
-// 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).
+// Post-generation cleaners. Reads the just-written PNG, applies the requested
+// passes (lossless C2PA chunk strip and/or lossy denoise), atomically
+// replaces the file in place, and patches the sidecar to record what ran.
+//
+// Two independent flags:
+// - `cleanC2PA: true` → strip the gpt-image `caBX` provenance chunk via
+// `stripPngC2PAChunk`. Pure byte-level metadata removal, no decode,
+// pixels untouched.
+// - `denoise: true` → median(3) + sharpen pass via `cleanImageBuffer`.
+// LOSSY: blurs annotation text, halos small details. Opt-in only.
//
-// `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 };
+// When `denoise` is on, C2PA is stripped implicitly by sharp's re-encode
+// regardless of `cleanC2PA` — both flags off short-circuits to a no-op.
+// `mode` is one of 'codex' | 'local' | 'external'; only used in log lines.
+// Logs and swallows errors — a clean failure must never fail the underlying
+// generation (the un-cleaned PNG stays on disk).
+export async function autoCleanGeneratedImage({ cleanC2PA = false, denoise = false, pngPath, sidecarPath, mode = 'unknown' }) {
+ if (!cleanC2PA && !denoise) return { cleaned: false };
+ // Backends that can't produce a `caBX` chunk (local FLUX, external SD-API)
+ // shouldn't pay readFile + walk on every render when the user enabled
+ // cleanC2PA defensively. Only codex (gpt-image-2) emits the chunk in
+ // current production. Denoise still has to run regardless because it's a
+ // pixel pass, not a metadata pass.
+ if (!denoise && cleanC2PA && mode !== 'codex') return { cleaned: false };
+
+ // Sidecar read has no data dependency on the PNG read/write — kick it off
+ // before the readFile so the two disk ops overlap.
+ const sidecarReadP = sidecarPath ? tryReadFile(sidecarPath) : Promise.resolve(null);
const buffer = await readFile(pngPath).catch(() => null);
if (!buffer) {
@@ -180,16 +275,38 @@ export async function autoCleanGeneratedImage({ enabled, pngPath, sidecarPath, m
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 };
+ let outputData = buffer;
+ let c2paStripped = false;
+ let denoised = false;
+ let sizeBefore = buffer.length;
+ let sizeAfter = buffer.length;
- // Sidecar read has no data dependency on the PNG write — kick it off in
- // parallel so the disk-read latency overlaps the encode/write window.
- const sidecarReadP = sidecarPath ? tryReadFile(sidecarPath) : Promise.resolve(null);
- const replaced = await atomicWrite(pngPath, result.data)
+ if (denoise) {
+ // Denoise re-encodes through sharp, which incidentally drops every
+ // ancillary chunk (including caBX). So a denoise pass implicitly
+ // satisfies the cleanC2PA flag too — no separate strip needed.
+ const result = await cleanImageBuffer(buffer).catch((err) => {
+ console.warn(`⚠️ Auto-clean denoise failed for ${basename(pngPath)}: ${err?.message || err}`);
+ return null;
+ });
+ if (!result || result.format !== 'png') return { cleaned: false };
+ outputData = result.data;
+ c2paStripped = result.c2paStripped;
+ denoised = true;
+ sizeAfter = result.sizeAfter;
+ } else if (cleanC2PA) {
+ // Lossless path: walk the PNG chunks and emit a new buffer with caBX
+ // removed. No decode, no re-encode, pixel-identical to input.
+ const result = stripPngC2PAChunk(buffer);
+ if (!result.stripped) {
+ // No-op (chunk absent / non-PNG / malformed) — leave the file as-is.
+ return { cleaned: false };
+ }
+ outputData = result.data;
+ c2paStripped = true;
+ sizeAfter = result.sizeAfter;
+ }
+ const replaced = await atomicWrite(pngPath, outputData)
.then(() => true)
.catch((err) => {
console.warn(`⚠️ Auto-clean write failed for ${basename(pngPath)}: ${err?.message || err}`);
@@ -204,12 +321,17 @@ export async function autoCleanGeneratedImage({ enabled, pngPath, sidecarPath, m
const patched = {
...safeJSONParse(raw, {}),
autoCleaned: true,
- cleanLevel: 'aggressive',
- c2paStripped: result.c2paStripped,
+ c2paStripped,
+ // Granular flags so MediaLightbox / sidecar consumers can show which
+ // passes ran. `cleanLevel` kept for back-compat with existing readers
+ // — 'aggressive' when denoise ran, 'metadata' when only the lossless
+ // strip ran.
+ denoised,
+ cleanLevel: denoised ? 'aggressive' : 'metadata',
};
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 };
+ console.log(`🧼 Cleaned ${basename(pngPath)} (mode=${mode}, ${sizeBefore}B → ${sizeAfter}B, c2pa=${c2paStripped}, denoise=${denoised})`);
+ return { cleaned: true, c2paStripped, denoised };
}
diff --git a/server/lib/imageClean.test.js b/server/lib/imageClean.test.js
index b2346d5a8a..b4f63aa56d 100644
--- a/server/lib/imageClean.test.js
+++ b/server/lib/imageClean.test.js
@@ -4,7 +4,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import sharp from 'sharp';
-import { autoCleanGeneratedImage } from './imageClean.js';
+import { autoCleanGeneratedImage, stripPngC2PAChunk } from './imageClean.js';
let sandbox;
let pngFixture;
@@ -39,21 +39,61 @@ describe('autoCleanGeneratedImage', () => {
}));
});
- it('no-ops when enabled=false (file + sidecar untouched)', async () => {
+ it('no-ops when both flags are 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',
+ cleanC2PA: false, denoise: 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('cleanC2PA=true on local/external mode short-circuits without reading the file (hot-path fast-path)', async () => {
+ // Local FLUX + external SD-API never emit caBX chunks. With cleanC2PA
+ // defaulting to true, every batch render would otherwise pay a wasted
+ // readFile + chunk walk. The mode gate skips both when denoise is off.
+ const beforeBytes = await readFile(pngPath);
+ const result = await autoCleanGeneratedImage({
+ cleanC2PA: true, denoise: false, pngPath, sidecarPath, mode: 'local',
+ });
+ expect(result.cleaned).toBe(false);
+ expect((await readFile(pngPath)).equals(beforeBytes)).toBe(true);
+
+ // External SD-API takes the same short-circuit.
+ const resultExt = await autoCleanGeneratedImage({
+ cleanC2PA: true, denoise: false, pngPath, sidecarPath, mode: 'external',
+ });
+ expect(resultExt.cleaned).toBe(false);
+ });
+
+ it('denoise on local/external still runs (only the cleanC2PA-only path is mode-gated)', async () => {
+ // The gate only skips the cleanC2PA-only case — denoise=true forces the
+ // pixel pass through regardless of mode, because the user explicitly
+ // asked for it.
+ const result = await autoCleanGeneratedImage({
+ cleanC2PA: false, denoise: true, pngPath, sidecarPath, mode: 'local',
+ });
+ expect(result.cleaned).toBe(true);
+ });
+
+ it('no-ops with cleanC2PA=true on a PNG that has no caBX chunk (pixels untouched)', async () => {
+ // The fixture has no caBX chunk, so the lossless strip path bails out
+ // and leaves the file as-is — proves the lossless path doesn't
+ // re-encode "just in case" and corrupt clean PNGs.
+ const beforeBytes = await readFile(pngPath);
+ const result = await autoCleanGeneratedImage({
+ cleanC2PA: true, denoise: false, pngPath, sidecarPath, mode: 'codex',
+ });
+ expect(result.cleaned).toBe(false);
+ expect((await readFile(pngPath)).equals(beforeBytes)).toBe(true);
+ });
+
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',
+ denoise: true, pngPath, sidecarPath, mode: 'local',
});
expect(result.cleaned).toBe(true);
@@ -62,20 +102,48 @@ describe('autoCleanGeneratedImage', () => {
const afterBytes = await readFile(pngPath);
expect(afterBytes.equals(beforeBytes)).toBe(false);
- // Sidecar gets autoCleaned + cleanLevel + c2paStripped, AND keeps the
- // pre-existing fields (lineage preserved).
+ // Sidecar gets autoCleaned + cleanLevel + c2paStripped + denoised, AND
+ // keeps the pre-existing fields (lineage preserved).
const sidecar = JSON.parse(await readFile(sidecarPath, 'utf-8'));
expect(sidecar.autoCleaned).toBe(true);
+ expect(sidecar.denoised).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('cleanC2PA=true with a real caBX chunk strips losslessly (sidecar marks metadata level)', async () => {
+ // Inject a synthetic caBX chunk before IEND to simulate a gpt-image render.
+ const png = await readFile(pngPath);
+ const caBXData = Buffer.alloc(120, 0xCA);
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(caBXData.length, 0);
+ const chunk = Buffer.concat([length, Buffer.from('caBX', 'ascii'), caBXData, Buffer.alloc(4)]);
+ const polluted = Buffer.concat([png.subarray(0, png.length - 12), chunk, png.subarray(png.length - 12)]);
+ await writeFile(pngPath, polluted);
+
+ const result = await autoCleanGeneratedImage({
+ cleanC2PA: true, denoise: false, pngPath, sidecarPath, mode: 'codex',
+ });
+ expect(result.cleaned).toBe(true);
+ expect(result.c2paStripped).toBe(true);
+ expect(result.denoised).toBe(false);
+
+ // Output bytes equal the ORIGINAL fixture — proves the strip is lossless.
+ const after = await readFile(pngPath);
+ expect(after.equals(png)).toBe(true);
+
+ const sidecar = JSON.parse(await readFile(sidecarPath, 'utf-8'));
+ expect(sidecar.cleanLevel).toBe('metadata');
+ expect(sidecar.denoised).toBe(false);
+ expect(sidecar.c2paStripped).toBe(true);
+ });
+
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',
+ denoise: true, pngPath, sidecarPath: null, mode: 'external',
});
expect(result.cleaned).toBe(true);
expect((await readFile(pngPath)).equals(beforeBytes)).toBe(false);
@@ -83,7 +151,7 @@ describe('autoCleanGeneratedImage', () => {
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'),
+ denoise: true, pngPath: join(sandbox, 'does-not-exist.png'),
sidecarPath: null, mode: 'local',
});
expect(result.cleaned).toBe(false);
@@ -97,7 +165,7 @@ describe('autoCleanGeneratedImage', () => {
Buffer.alloc(64),
]));
const result = await autoCleanGeneratedImage({
- enabled: true, pngPath: corruptPath, sidecarPath: null, mode: 'codex',
+ denoise: 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.
@@ -106,7 +174,7 @@ describe('autoCleanGeneratedImage', () => {
it('cleans atomically: a temp file is not left behind on success', async () => {
await autoCleanGeneratedImage({
- enabled: true, pngPath, sidecarPath, mode: 'codex',
+ denoise: true, pngPath, sidecarPath, mode: 'codex',
});
// Look for any orphaned `.tmp` files in the sandbox — the rename should
// have moved the temp over the original.
@@ -119,7 +187,7 @@ describe('autoCleanGeneratedImage', () => {
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',
+ denoise: true, pngPath, sidecarPath, mode: 'local',
});
const after = await stat(pngPath);
expect(after.size).toBeGreaterThan(0);
@@ -129,3 +197,81 @@ describe('autoCleanGeneratedImage', () => {
expect(after.size).toBeLessThan(before.size * 10);
});
});
+
+// Manually-constructed PNG chunk: `length(4) + type(4) + data(length) + crc(4)`.
+// Helper so we can splice a synthetic caBX chunk into the fixture before IEND.
+function makePngChunk(type, data) {
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(data.length, 0);
+ const typeBytes = Buffer.from(type, 'ascii');
+ // CRC value isn't validated by stripPngC2PAChunk (it walks structurally, not
+ // semantically), so use a zero CRC to keep the fixture builder simple.
+ const crc = Buffer.alloc(4);
+ return Buffer.concat([length, typeBytes, data, crc]);
+}
+
+// Inject a chunk into the PNG fixture just before its IEND chunk. IEND is the
+// last 12 bytes of a well-formed PNG, so splicing at length-12 produces a
+// valid chunk stream the walker can traverse end-to-end.
+function injectChunkBeforeIEND(png, chunk) {
+ return Buffer.concat([png.subarray(0, png.length - 12), chunk, png.subarray(png.length - 12)]);
+}
+
+describe('stripPngC2PAChunk', () => {
+ it('returns the input untouched when no caBX chunk is present', () => {
+ const result = stripPngC2PAChunk(pngFixture);
+ expect(result.stripped).toBe(false);
+ expect(result.data).toBe(pngFixture);
+ expect(result.sizeBefore).toBe(pngFixture.length);
+ expect(result.sizeAfter).toBe(pngFixture.length);
+ });
+
+ it('emits a NEW buffer that excludes the caBX chunk but keeps pixels byte-identical', async () => {
+ // Splice a synthetic 100-byte caBX chunk before IEND.
+ const caBXData = Buffer.alloc(100, 0xCA);
+ const caBXChunk = makePngChunk('caBX', caBXData);
+ const polluted = injectChunkBeforeIEND(pngFixture, caBXChunk);
+ expect(polluted.length).toBe(pngFixture.length + caBXChunk.length);
+
+ const result = stripPngC2PAChunk(polluted);
+ expect(result.stripped).toBe(true);
+ expect(result.sizeBefore).toBe(polluted.length);
+ expect(result.sizeAfter).toBe(pngFixture.length);
+ // The stripped buffer must equal the original fixture byte-for-byte —
+ // proves the operation is pixel-identical (no re-encode).
+ expect(result.data.equals(pngFixture)).toBe(true);
+ });
+
+ it('drops every caBX chunk when multiple are present (defensive against duplicates)', () => {
+ const c1 = makePngChunk('caBX', Buffer.alloc(40, 0x01));
+ const c2 = makePngChunk('caBX', Buffer.alloc(60, 0x02));
+ const polluted = injectChunkBeforeIEND(injectChunkBeforeIEND(pngFixture, c1), c2);
+ const result = stripPngC2PAChunk(polluted);
+ expect(result.stripped).toBe(true);
+ expect(result.data.equals(pngFixture)).toBe(true);
+ });
+
+ it('passes through unchanged for non-PNG input (JPEG/WebP/garbage)', () => {
+ // JPEG-ish signature: 0xFF 0xD8 0xFF followed by some random bytes.
+ const fakeJpeg = Buffer.concat([Buffer.from([0xFF, 0xD8, 0xFF, 0xE0]), Buffer.alloc(100, 0x99)]);
+ expect(stripPngC2PAChunk(fakeJpeg).stripped).toBe(false);
+ expect(stripPngC2PAChunk(fakeJpeg).data).toBe(fakeJpeg);
+
+ expect(stripPngC2PAChunk(Buffer.from('not even close')).stripped).toBe(false);
+ expect(stripPngC2PAChunk(Buffer.alloc(0)).stripped).toBe(false);
+ });
+
+ it('passes through unchanged for malformed PNG (truncated, no IEND)', () => {
+ // Real PNG header but chopped before IEND — the walker bails on missing IEND.
+ const truncated = pngFixture.subarray(0, pngFixture.length - 12);
+ const result = stripPngC2PAChunk(truncated);
+ expect(result.stripped).toBe(false);
+ expect(result.data).toBe(truncated);
+ });
+
+ it('passes through unchanged on non-buffer input', () => {
+ expect(stripPngC2PAChunk(null).stripped).toBe(false);
+ expect(stripPngC2PAChunk(undefined).stripped).toBe(false);
+ expect(stripPngC2PAChunk('a string').stripped).toBe(false);
+ });
+});
diff --git a/server/lib/storyBible.js b/server/lib/storyBible.js
index 6e90db8c31..f0a481fdeb 100644
--- a/server/lib/storyBible.js
+++ b/server/lib/storyBible.js
@@ -11,6 +11,7 @@ import { randomUUID } from 'crypto';
import { join } from 'path';
import { normalizeSlugline } from './scenePrompt.js';
import { PATHS, atomicWrite, ensureDir, readJSONFile, resolveImageRef } from './fileUtils.js';
+import { isPlainObject } from './objects.js';
import { ServerError } from './errorHandler.js';
// Re-export so callers (writers-room domain files) can import a single
@@ -270,11 +271,15 @@ export function findBibleEntryByName(list, name) {
export const CANON_CONTROL_FIELDS = Object.freeze([
'id', 'createdAt', 'updatedAt',
'locked', 'sourceSeriesId',
- 'imageRefs', 'primaryImageRef', 'referenceSheetImageRef',
+ 'imageRefs', 'primaryImageRef',
+ // Sheet pointers — see SHEET_VARIANTS in universeCharacterSheet.js for the
+ // catalog of styles; legacy 'standard' stays in `referenceSheetImageRef`,
+ // every other variant lives in `referenceSheets[<id>]`.
+ 'referenceSheetImageRef', 'referenceSheets',
]);
export const SERVER_OWNED_CHARACTER_FIELDS = Object.freeze([
- 'referenceSheetImageRef',
+ 'referenceSheetImageRef', 'referenceSheets',
]);
export function stripCanonControlFields(entry) {
@@ -332,29 +337,166 @@ function deriveReferenceSheetImageRef(raw) {
return trimmed;
}
+// The legacy 'standard' variant lives in `character.referenceSheetImageRef`;
+// every other variant lives in `character.referenceSheets[<id>]`. Exported so
+// every reader/writer of either slot uses the same constant — the alternative
+// is a magic string repeated in ~14 places.
+export const LEGACY_SHEET_VARIANT_ID = 'standard';
+
+// Variant-id rules for `referenceSheets` map keys: short kebab-case identifier,
+// no path separators, no dot-prefix. Cap of 48 chars matches the route schema.
+// The legacy id is rejected because it must stay in the legacy field, not in
+// the map (otherwise sanitize / prune / purge would have to pick which slot wins).
+const VARIANT_ID_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
+function isValidVariantId(id) {
+ return typeof id === 'string' && VARIANT_ID_RE.test(id) && id !== LEGACY_SHEET_VARIANT_ID;
+}
+
+/** Read the persisted reference-sheet filename for a variant. Returns the
+ * string filename or null. The single read-side helper every consumer
+ * (client + server) should use so storage-shape changes stay local. */
+export function readSheetPointer(character, variant) {
+ if (!character) return null;
+ if (variant === LEGACY_SHEET_VARIANT_ID) return character.referenceSheetImageRef || null;
+ const sheets = character.referenceSheets;
+ if (!isPlainObject(sheets)) return null;
+ return sheets[variant] || null;
+}
+
+/** Enumerate every reference-sheet pointer a character holds — yields one
+ * `{ variant, filename }` per non-empty slot. The single iteration-side
+ * helper for prune / purge / exporter / asset-collector. */
+export function listSheetPointers(character) {
+ if (!character) return [];
+ const out = [];
+ if (character.referenceSheetImageRef) {
+ out.push({ variant: LEGACY_SHEET_VARIANT_ID, filename: character.referenceSheetImageRef });
+ }
+ if (isPlainObject(character.referenceSheets)) {
+ for (const [variant, filename] of Object.entries(character.referenceSheets)) {
+ if (filename) out.push({ variant, filename });
+ }
+ }
+ return out;
+}
+
+/** Merge `prev`'s server-stamped sheet pointers into `patchChar`, keeping
+ * cur's value for every slot whose underlying file still exists on disk.
+ * Run by the `updateUniverse` literal-patch preservation guard so a stale
+ * client snapshot can't clobber a render-completion stamp that landed
+ * between GET and PATCH. Per-key for the map: each `referenceSheets[k]`
+ * is considered independently so a freshly-stamped 'blueprint' survives
+ * even when the patch carries an older `referenceSheets` (or omits it).
+ *
+ * `resolveExists(filename) → boolean` is injected so this helper stays
+ * pure with respect to the FS — callers wire `resolveImageRef(..., { mustExist: true })`
+ * in. Returns a new character object; callers should treat it as
+ * immutable-by-convention. */
+export function mergePreservedSheetPointers(prev, patchChar, resolveExists) {
+ if (!prev || !patchChar) return patchChar;
+ const out = { ...patchChar };
+
+ if (prev.referenceSheetImageRef && resolveExists(prev.referenceSheetImageRef)) {
+ out.referenceSheetImageRef = prev.referenceSheetImageRef;
+ }
+
+ const prevMap = isPlainObject(prev.referenceSheets) ? prev.referenceSheets : null;
+ if (prevMap) {
+ const patchMap = isPlainObject(patchChar.referenceSheets) ? patchChar.referenceSheets : {};
+ // Preserved keys win over the patch — same one-way precedence as the
+ // legacy field. Unresolvable cur values fall through so a deleted-then-
+ // PATCHed slot can clear.
+ const merged = { ...patchMap };
+ for (const [variant, filename] of Object.entries(prevMap)) {
+ if (filename && resolveExists(filename)) merged[variant] = filename;
+ }
+ out.referenceSheets = merged;
+ }
+
+ return out;
+}
+
+/** Apply (or clear, when `filename` is null) a variant's pointer on a
+ * character, returning a NEW character object — OR the same reference when
+ * the slot already holds the target value, so callers downstream of an
+ * `updateUniverse` mutator (and React subscribers on the client mirror)
+ * can short-circuit no-op writes/renders. Writes the legacy variant to
+ * `referenceSheetImageRef`; every other variant lands in / leaves from
+ * `referenceSheets[variant]`. */
+export function applySheetPointerToCharacter(character, variant, filename) {
+ if (!character) return character;
+ if (variant === LEGACY_SHEET_VARIANT_ID) {
+ const next = filename || null;
+ if ((character.referenceSheetImageRef || null) === next) return character;
+ return { ...character, referenceSheetImageRef: next };
+ }
+ const existing = isPlainObject(character.referenceSheets) ? character.referenceSheets : {};
+ if (filename) {
+ if (existing[variant] === filename) return character;
+ return { ...character, referenceSheets: { ...existing, [variant]: filename } };
+ }
+ if (!(variant in existing)) return character;
+ const { [variant]: _dropped, ...rest } = existing;
+ return { ...character, referenceSheets: rest };
+}
+
+/**
+ * Sanitize the `referenceSheets` map. Drops invalid variant ids, basename-
+ * validates every filename, returns a fresh frozen object with only valid
+ * entries. An LLM-extracted payload that somehow includes this field (it
+ * shouldn't — it's in CANON_CONTROL_FIELDS — but defense in depth) cannot
+ * smuggle a path traversal or an unknown sentinel into the persisted state.
+ *
+ * Always returns an object (possibly empty). The renderer treats absent
+ * keys as "no sheet rendered yet" and absent vs. empty map identically.
+ */
+function deriveReferenceSheets(raw) {
+ if (!isPlainObject(raw)) return {};
+ const out = {};
+ for (const [key, value] of Object.entries(raw)) {
+ if (!isValidVariantId(key)) continue;
+ const filename = deriveReferenceSheetImageRef(value);
+ if (!filename) continue;
+ out[key] = filename;
+ }
+ return out;
+}
+
/**
- * Walk a character list and null out any `referenceSheetImageRef` whose
+ * Walk a character list and null out any reference-sheet pointer whose
* underlying file no longer exists in PATHS.imageRefs. Returns a NEW list
* (cheap shallow copy per character) so callers can persist the cleaned
* state. Pure with respect to the sanitizer — no FS I/O during sanitize,
* just here at the "GET universe / verify before render" boundary.
*
- * `resolveImageRef(mustExist: true)` does the FS stat synchronously; for
- * a typical 5-50 character universe this is sub-millisecond.
- *
* CONVENTION: call from BOTH the GET universe route AND `updateUniverse`'s
* write path. GET alone is not sufficient — without the write-time call,
* stale values stay on disk and a later PATCH that omits `characters`
* (e.g. rename) resurfaces the stale filename in the response.
+ *
+ * Memoizes `resolveImageRef` per call so a 50-character × 5-variant cast
+ * doesn't fan out into 250 redundant sync `statSync`s — every distinct
+ * filename costs one stat, not one stat per slot it appears in.
*/
export function pruneStaleReferenceSheets(characters) {
if (!Array.isArray(characters)) return characters;
+ const resolvedCache = new Map();
+ const fileExists = (name) => {
+ if (resolvedCache.has(name)) return resolvedCache.get(name);
+ const ok = !!resolveImageRef(name, { mustExist: true });
+ resolvedCache.set(name, ok);
+ return ok;
+ };
let changed = false;
const out = characters.map((c) => {
- if (!c || !c.referenceSheetImageRef) return c;
- if (resolveImageRef(c.referenceSheetImageRef, { mustExist: true })) return c;
- changed = true;
- return { ...c, referenceSheetImageRef: null };
+ if (!c) return c;
+ let next = c;
+ for (const { variant, filename } of listSheetPointers(c)) {
+ if (fileExists(filename)) continue;
+ next = applySheetPointerToCharacter(next, variant, null);
+ changed = true;
+ }
+ return next;
});
return changed ? out : characters;
}
@@ -552,6 +694,12 @@ export function sanitizeCharacter(raw, { idPrefix = DEFAULT_ID_PREFIX.character,
// payload that snuck past stripCanonControlFields can't persist a path
// the UI would 404 on or that would escape PATHS.imageRefs at render time.
referenceSheetImageRef: deriveReferenceSheetImageRef(raw.referenceSheetImageRef),
+ // Variant-keyed pointers for non-legacy sheet styles (`blueprint`, etc.).
+ // Per-variant filenames live here; the legacy 'standard' variant keeps
+ // using `referenceSheetImageRef` above so existing data needs no
+ // migration. Sanitizer drops invalid keys and basename-validates every
+ // value with the same rules as the legacy field.
+ referenceSheets: deriveReferenceSheets(raw.referenceSheets),
// Wardrobes (A2): outfit/styling variants applied on top of
// physicalDescription. Empty array stays the legacy shape — every
// existing character keeps rendering through physicalDescription alone.
diff --git a/server/lib/storyBible.test.js b/server/lib/storyBible.test.js
index a2a6abc843..2681499c55 100644
--- a/server/lib/storyBible.test.js
+++ b/server/lib/storyBible.test.js
@@ -29,6 +29,7 @@ const {
BIBLE_KIND,
createBibleStore,
pruneStaleReferenceSheets,
+ mergePreservedSheetPointers,
stripCanonControlFields,
CANON_CONTROL_FIELDS,
SERVER_OWNED_CHARACTER_FIELDS,
@@ -442,6 +443,55 @@ tryReadFile: vi.fn().mockResolvedValue(null),
expect(sanitizeCharacter({ name: 'A' }).referenceSheetImageRef).toBeNull();
});
+ it('referenceSheets map keeps valid variant entries and basename-validates each filename', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ referenceSheetImageRef: 'std.png',
+ referenceSheets: {
+ blueprint: ' blueprint.png ',
+ noir: 'noir.png',
+ },
+ });
+ expect(out.referenceSheetImageRef).toBe('std.png');
+ expect(out.referenceSheets).toEqual({ blueprint: 'blueprint.png', noir: 'noir.png' });
+ });
+
+ it('referenceSheets defaults to an empty object when absent / non-object / null', () => {
+ expect(sanitizeCharacter({ name: 'A' }).referenceSheets).toEqual({});
+ expect(sanitizeCharacter({ name: 'A', referenceSheets: null }).referenceSheets).toEqual({});
+ expect(sanitizeCharacter({ name: 'A', referenceSheets: 'string' }).referenceSheets).toEqual({});
+ expect(sanitizeCharacter({ name: 'A', referenceSheets: [] }).referenceSheets).toEqual({});
+ });
+
+ it('referenceSheets drops invalid variant ids (path traversal, uppercase, dot prefix, "standard" sentinel)', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ referenceSheets: {
+ blueprint: 'ok.png',
+ // Invalid keys: traversal, uppercase, dot prefix, the reserved
+ // 'standard' sentinel (kept on the legacy field), empty string.
+ '../escape': 'attack.png',
+ 'BadCase': 'foo.png',
+ '.hidden': 'foo.png',
+ 'standard': 'should-stay-in-legacy-field.png',
+ '': 'foo.png',
+ },
+ });
+ expect(out.referenceSheets).toEqual({ blueprint: 'ok.png' });
+ });
+
+ it('referenceSheets drops entries whose filename fails basename validation', () => {
+ const out = sanitizeCharacter({
+ name: 'A',
+ referenceSheets: {
+ blueprint: '../escape.png',
+ noir: 'foo/bar.png',
+ steampunk: 'ok.png',
+ },
+ });
+ expect(out.referenceSheets).toEqual({ steampunk: 'ok.png' });
+ });
+
it('REGRESSION: referenceSheetImageRef rejects path separators + traversal', () => {
// Defense-in-depth against an LLM-extracted payload that bypassed
// stripCanonControlFields. The runtime route serves /data/image-refs/<x>
@@ -495,7 +545,9 @@ describe('storyBible — canon control + server-owned field invariants', () => {
it('SERVER_OWNED_CHARACTER_FIELDS lists exactly the render-completion-stamped pointers', () => {
// Pin the current set so a new server-owned addition is a deliberate
// change (update both this test AND the corresponding render flow).
- expect([...SERVER_OWNED_CHARACTER_FIELDS]).toEqual(['referenceSheetImageRef']);
+ expect([...SERVER_OWNED_CHARACTER_FIELDS]).toEqual([
+ 'referenceSheetImageRef', 'referenceSheets',
+ ]);
});
});
@@ -530,6 +582,102 @@ describe('storyBible — pruneStaleReferenceSheets', () => {
expect(pruneStaleReferenceSheets(undefined)).toBeUndefined();
expect(pruneStaleReferenceSheets('not array')).toBe('not array');
});
+
+ it('drops stale variant keys from referenceSheets without disturbing the rest of the map', () => {
+ // Two variants, one resolvable on disk one not — the gone one must be
+ // dropped but the still-resolvable entry must stay. The legacy field is
+ // untouched in this fixture.
+ const list = [{
+ name: 'A',
+ referenceSheets: {
+ blueprint: 'gone-blueprint.png',
+ // Pruner takes whatever's not on disk; this test doesn't care which
+ // entries survive — only that the map is pruned per-key, not wholesale.
+ steampunk: 'also-gone.png',
+ },
+ }];
+ const out = pruneStaleReferenceSheets(list);
+ expect(out).not.toBe(list);
+ expect(out[0].referenceSheets).toEqual({});
+ expect(out[0].name).toBe('A');
+ });
+
+ it('mergePreservedSheetPointers preserves legacy + map pointers from prev when files still resolve', () => {
+ // Inject a fake FS check so the test is hermetic.
+ const onDisk = new Set(['live-std.png', 'live-bp.png']);
+ const checkExists = (name) => onDisk.has(name);
+
+ // patch carries a stale legacy filename AND no map; prev has both.
+ const prev = {
+ id: 'c-1', name: 'Vex',
+ referenceSheetImageRef: 'live-std.png',
+ referenceSheets: { blueprint: 'live-bp.png' },
+ };
+ const patchOmits = { id: 'c-1', name: 'Vex' };
+ const merged1 = mergePreservedSheetPointers(prev, patchOmits, checkExists);
+ expect(merged1.referenceSheetImageRef).toBe('live-std.png');
+ expect(merged1.referenceSheets).toEqual({ blueprint: 'live-bp.png' });
+
+ // Map merge: prev's blueprint wins over the patch's stale blueprint; the
+ // patch's other variant ('noir') flows through.
+ const patchStale = {
+ id: 'c-1', name: 'Vex',
+ referenceSheetImageRef: 'old-std.png',
+ referenceSheets: { blueprint: 'old-bp.png', noir: 'patch-noir.png' },
+ };
+ const merged2 = mergePreservedSheetPointers(prev, patchStale, checkExists);
+ expect(merged2.referenceSheetImageRef).toBe('live-std.png');
+ expect(merged2.referenceSheets).toEqual({ blueprint: 'live-bp.png', noir: 'patch-noir.png' });
+ });
+
+ it('mergePreservedSheetPointers falls through to the patch when prev pointer no longer resolves', () => {
+ // GET-route pruner returns null when the file is gone; client PATCH
+ // carries that null back. Preservation MUST not re-introduce the stale
+ // pointer from cur — otherwise the UI 404s on the next render.
+ const onDisk = new Set(); // nothing resolves
+ const checkExists = (name) => onDisk.has(name);
+ const prev = {
+ id: 'c-1', name: 'A',
+ referenceSheetImageRef: 'dead-std.png',
+ referenceSheets: { blueprint: 'dead-bp.png' },
+ };
+ const patch = {
+ id: 'c-1', name: 'A',
+ referenceSheetImageRef: null,
+ referenceSheets: {},
+ };
+ const merged = mergePreservedSheetPointers(prev, patch, checkExists);
+ expect(merged.referenceSheetImageRef).toBeNull();
+ expect(merged.referenceSheets).toEqual({});
+ });
+
+ it('mergePreservedSheetPointers is a pass-through when prev or patchChar is missing', () => {
+ const checkExists = () => true;
+ expect(mergePreservedSheetPointers(null, { id: 'c-1' }, checkExists)).toEqual({ id: 'c-1' });
+ expect(mergePreservedSheetPointers({ id: 'c-1' }, null, checkExists)).toBeNull();
+ });
+
+ it('prunes legacy + map pointers together without blowing away unrelated fields', () => {
+ const list = [{
+ id: 'c-1', name: 'A', personality: 'alert',
+ referenceSheetImageRef: 'gone-std.png',
+ referenceSheets: { blueprint: 'gone-bp.png' },
+ }];
+ const out = pruneStaleReferenceSheets(list);
+ expect(out[0].referenceSheetImageRef).toBeNull();
+ expect(out[0].referenceSheets).toEqual({});
+ expect(out[0].name).toBe('A');
+ expect(out[0].personality).toBe('alert');
+ });
+
+ it('leaves an absent / empty referenceSheets untouched', () => {
+ const list = [
+ { name: 'A' }, // no map at all
+ { name: 'B', referenceSheets: {} }, // empty map
+ ];
+ const out = pruneStaleReferenceSheets(list);
+ expect(out).toBe(list);
+ });
});
describe('storyBible — sanitizePlace', () => {
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index bd47ba2cb7..254a31e613 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -19,7 +19,7 @@ import {
} from '../lib/validation.js';
import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
-import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveAutoClean } from '../services/imageGen/index.js';
+import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveImageCleaners } from '../services/imageGen/index.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { getSettings, saveSettings } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
@@ -75,10 +75,13 @@ 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.
+ // Per-render override of the cleaners. When omitted, the route inherits
+ // from `settings.imageGen.{mode}.{cleanC2PA,denoise}`. Explicit booleans
+ // here force the value for this one render. Legacy `autoClean` is still
+ // accepted (mapped to both flags) so older clients keep working through
+ // the deprecation window.
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
autoClean: z.boolean().optional(),
}).refine(refineImagePixelCap, { message: PIXEL_CAP_MESSAGE, path: ['width'] });
@@ -117,7 +120,17 @@ function coerceFormFields(body) {
}
// 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';
+ for (const f of ['cleanC2PA', 'denoise', 'autoClean']) {
+ if (typeof body[f] === 'string') body[f] = body[f] === 'true';
+ }
+ // Legacy single-flag clients: an explicit `autoClean` on the wire maps to
+ // BOTH new flags (preserves the pre-split behavior) only when the caller
+ // didn't also send the new fields. Modern clients that pass cleanC2PA /
+ // denoise explicitly win.
+ if (typeof body.autoClean === 'boolean') {
+ if (typeof body.cleanC2PA !== 'boolean') body.cleanC2PA = body.autoClean;
+ if (typeof body.denoise !== 'boolean') body.denoise = body.autoClean;
+ }
return body;
}
@@ -196,11 +209,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 || IMAGE_GEN_MODE.EXTERNAL;
- // Resolve autoClean ONCE at the route layer so all three dispatch paths
- // (synchronous external, codex queue, local queue) see the same value.
- // Stamp onto `data` so the value flows through the spread-into-params
- // calls below verbatim.
- data.autoClean = resolveAutoClean(data.autoClean, settings, mode);
+ // Resolve cleaners ONCE at the route layer so all three dispatch paths
+ // (synchronous external, codex queue, local queue) see the same values.
+ // Stamp onto `data` so they flow through the spread-into-params calls
+ // below verbatim.
+ const cleaners = resolveImageCleaners(data, settings, mode);
+ data.cleanC2PA = cleaners.cleanC2PA;
+ data.denoise = cleaners.denoise;
+ delete data.autoClean; // legacy field — already mapped into both flags above
// Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
// buildArgs only emits --reference-images/--reference-strengths inside the
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index c1a69240e0..446a5a7a75 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -11,11 +11,20 @@ vi.mock('../services/imageGen/index.js', () => ({
cancel: vi.fn(() => false),
IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },
IMAGE_GEN_MODES: ['external', 'local', 'codex'],
- // Mirror the real precedence so route-level resolution behaves correctly
- // under test: explicit body bool wins, otherwise fall back to settings.
- resolveAutoClean: (bodyValue, settings, mode) => (typeof bodyValue === 'boolean'
- ? bodyValue
- : settings?.imageGen?.[mode]?.autoClean === true),
+ // Mirror the real precedence by delegating to the same helper the prod
+ // resolver uses — keeps test mock and prod in lock-step automatically.
+ resolveImageCleaners: (body, settings, mode) => {
+ const cfg = settings?.imageGen?.[mode] || {};
+ const legacy = cfg.autoClean === true;
+ const saved = {
+ cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : true,
+ denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : legacy,
+ };
+ return {
+ cleanC2PA: typeof body?.cleanC2PA === 'boolean' ? body.cleanC2PA : saved.cleanC2PA,
+ denoise: typeof body?.denoise === 'boolean' ? body.denoise : saved.denoise,
+ };
+ },
local: {
listImageModels: vi.fn(() => []),
listLoraFilenames: vi.fn(async () => []),
@@ -331,69 +340,82 @@ 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 () => {
+ describe('cleaner resolution (body wins over saved setting)', () => {
+ it('external mode: body denoise=true overrides saved setting=false', async () => {
getSettings.mockResolvedValueOnce({
- imageGen: { mode: 'external', external: { autoClean: false } },
+ imageGen: { mode: 'external', external: { cleanC2PA: false, denoise: 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 });
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', denoise: true });
- expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ autoClean: true }));
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ denoise: true, cleanC2PA: false }));
});
- it('external mode: omitted body inherits saved setting=true', async () => {
+ it('external mode: omitted body inherits saved cleanC2PA=true + denoise=false', async () => {
getSettings.mockResolvedValueOnce({
- imageGen: { mode: 'external', external: { autoClean: true } },
+ imageGen: { mode: 'external', external: { cleanC2PA: true, denoise: false } },
});
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 }));
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ cleanC2PA: true, denoise: false }));
});
- it('local mode: body autoClean=true flows through into enqueued params (was previously dropped)', async () => {
+ it('local mode: body flags flow through into enqueued params', async () => {
getSettings.mockResolvedValueOnce({
- imageGen: { mode: 'local', local: { pythonPath: '/p', autoClean: false } },
+ imageGen: { mode: 'local', local: { pythonPath: '/p', cleanC2PA: false, denoise: false } },
});
- await request(app).post('/api/image-gen/generate').send({ prompt: 'p', autoClean: true });
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', cleanC2PA: true, denoise: true });
const [call] = mediaJobQueue.enqueueJob.mock.calls;
- expect(call[0].params.autoClean).toBe(true);
+ expect(call[0].params.cleanC2PA).toBe(true);
+ expect(call[0].params.denoise).toBe(true);
});
- it('local mode: omitted body inherits saved setting=true on enqueued params', async () => {
+ it('codex mode: body denoise=false overrides saved setting=true on enqueued params', async () => {
getSettings.mockResolvedValueOnce({
- imageGen: { mode: 'local', local: { pythonPath: '/p', autoClean: true } },
+ imageGen: { mode: 'codex', codex: { enabled: true, cleanC2PA: true, denoise: true } },
});
- await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', denoise: false });
const [call] = mediaJobQueue.enqueueJob.mock.calls;
- expect(call[0].params.autoClean).toBe(true);
+ expect(call[0].params.denoise).toBe(false);
+ });
+
+ it('defaults to cleanC2PA=true + denoise=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({ cleanC2PA: true, denoise: false }));
});
- it('codex mode: body autoClean=false overrides saved setting=true on enqueued params', async () => {
+ it('legacy autoClean=true on settings maps to BOTH new flags on read', async () => {
+ // Pre-split installs persisted `autoClean: true`. resolveImageCleaners
+ // maps that to cleanC2PA=true + denoise=true so the user's opt-in
+ // behavior is preserved through the upgrade.
getSettings.mockResolvedValueOnce({
- imageGen: { mode: 'codex', codex: { enabled: true, autoClean: true } },
+ 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', autoClean: false });
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p' });
- const [call] = mediaJobQueue.enqueueJob.mock.calls;
- expect(call[0].params.autoClean).toBe(false);
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ cleanC2PA: true, denoise: true }));
});
- it('defaults to false when neither body nor settings specify', async () => {
+ it('legacy autoClean=true on body maps to BOTH new flags via the coerceFormFields shim', 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' });
+ await request(app).post('/api/image-gen/generate').send({ prompt: 'p', autoClean: true });
- expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ autoClean: false }));
+ expect(imageGen.generateImage).toHaveBeenCalledWith(expect.objectContaining({ cleanC2PA: true, denoise: true }));
});
});
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 1c2d7d3605..a0258d82a9 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -19,7 +19,11 @@ import { validateRequest, optionalBooleanMap } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';
-import { renderCharacterReferenceSheet, deleteCharacterReferenceSheet } from '../services/universeCharacterSheet.js';
+import {
+ renderCharacterReferenceSheet,
+ deleteCharacterReferenceSheet,
+ listSheetVariants,
+} from '../services/universeCharacterSheet.js';
import { BIBLE_KINDS, BIBLE_LIMITS, pruneStaleReferenceSheets } from '../lib/storyBible.js';
import { getUniverseCanonUsage, listLinkedSeriesNames } from '../services/canonUsage.js';
import { expandWorldTemplate, generateCategoryVariations } from '../services/universeBuilderExpand.js';
@@ -32,7 +36,7 @@ import { findOrCreateUniverseCollection } from '../services/mediaCollections.js'
import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';
import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';
import { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/modes.js';
-import { resolveAutoClean } from '../services/imageGen/index.js';
+import { resolveImageCleaners } from '../services/imageGen/index.js';
import { getStylePresetById } from '../lib/writersRoomStylePresets.js';
const router = Router();
@@ -372,6 +376,13 @@ router.post('/refine-prompts', asyncHandler(async (req, res) => {
res.json(await refineWorldPrompts(body));
}));
+// Static-path GETs must register BEFORE `/:id` so they aren't swallowed by
+// the parametric route. The catalog lists every registered reference-sheet
+// variant — the client renders one row per entry in CharacterReferenceSheetPanel.
+router.get('/reference-sheet-variants', asyncHandler(async (_req, res) => {
+ res.json({ variants: listSheetVariants() });
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
const w = await svc.getUniverse(req.params.id).catch((err) => { throw mapServiceError(err); });
// Lazy stale-reference-sheet collapse: nulls out any character.referenceSheetImageRef
@@ -557,23 +568,23 @@ router.post('/:id/render', asyncHandler(async (req, res) => {
};
let queued;
// The queue dispatches directly to imageGen/{codex,local}.generateImage,
- // bypassing imageGen/index.js's dispatcher that resolves autoClean for
- // direct callers. Resolve here so saved settings.imageGen[mode].autoClean
- // applies to Universe Builder batch renders the same way it does for
- // /api/image-gen/generate and pipeline renders.
- const autoClean = resolveAutoClean(undefined, settings, mode);
+ // bypassing imageGen/index.js's dispatcher that resolves cleaners for
+ // direct callers. Resolve here so the per-mode cleanC2PA + denoise
+ // settings apply to Universe Builder batch renders the same way they
+ // do for /api/image-gen/generate and pipeline renders.
+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
if (mode === IMAGE_GEN_MODE.CODEX) {
const c = settings.imageGen?.codex || {};
queued = enqueueJob({
kind: 'image',
- params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, autoClean, ...params },
+ params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, cleanC2PA, denoise, ...params },
});
} else {
// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).
const py = settings.imageGen?.local?.pythonPath || null;
queued = enqueueJob({
kind: 'image',
- params: { pythonPath: py, modelId: body.modelId, autoClean, ...params },
+ params: { pythonPath: py, modelId: body.modelId, cleanC2PA, denoise, ...params },
});
}
jobIds.push(queued.jobId);
@@ -669,30 +680,36 @@ router.post('/:id/characters/:entryId/expand', asyncHandler(async (req, res) =>
res.json(result);
}));
-// Generate a single dense artist reference sheet (turnaround + expressions +
-// palette + wardrobe + props + hand gestures) from a structured TEXT prompt
-// — no init image required, so it works across codex / local backends.
-// Returns immediately with `{ jobId, generationId }`; client subscribes to
-// SSE for progress, and the server-side completion handler stamps
-// `character.referenceSheetImageRef` on success.
+// Generate one of the character reference-sheet variants from a structured
+// TEXT prompt — no init image required, so it works across codex / local
+// backends. The `variant` field selects which prompt-builder + storage slot
+// the render targets (defaults to 'standard' = illustrated turnaround).
+// Returns immediately with `{ jobId, generationId, variant }`; client
+// subscribes to SSE for progress, and the server-side completion handler
+// stamps the variant's pointer on success.
const renderReferenceSheetSchema = z.object({
+ variant: z.string().trim().min(1).max(48).optional(),
overridePrompt: z.string().trim().max(8000).optional(),
overrideNegativePrompt: z.string().trim().max(2000).optional(),
modelId: z.string().trim().max(64).optional(),
});
router.post('/:id/characters/:entryId/render-reference-sheet', asyncHandler(async (req, res) => {
- const body = validateRequest(renderReferenceSheetSchema, req.body ?? {});
- const result = await renderCharacterReferenceSheet(req.params.id, req.params.entryId, body)
+ const options = validateRequest(renderReferenceSheetSchema, req.body ?? {});
+ const result = await renderCharacterReferenceSheet(req.params.id, req.params.entryId, options)
.catch((err) => { throw mapServiceError(err); });
res.json(result);
}));
-// Delete the character's current reference sheet — unlinks the PNG from
-// `data/image-refs/` and nulls `referenceSheetImageRef` on every matching
-// character (via `purgeReferenceSheetFromAllUniverses`) so the UI clears
-// reactively without a refetch.
+// Delete a character's reference sheet — unlinks the PNG from
+// `data/image-refs/` and nulls the variant's pointer on every matching
+// character so the UI clears reactively without a refetch. `variant` is
+// passed via query string (DELETE bodies are awkward across HTTP clients).
+const deleteReferenceSheetQuerySchema = z.object({
+ variant: z.string().trim().min(1).max(48).optional(),
+});
router.delete('/:id/characters/:entryId/reference-sheet', asyncHandler(async (req, res) => {
- const result = await deleteCharacterReferenceSheet(req.params.id, req.params.entryId)
+ const opts = validateRequest(deleteReferenceSheetQuerySchema, req.query ?? {});
+ const result = await deleteCharacterReferenceSheet(req.params.id, req.params.entryId, opts)
.catch((err) => { throw mapServiceError(err); });
res.json(result);
}));
diff --git a/server/routes/universeBuilder.test.js b/server/routes/universeBuilder.test.js
index 0963694a36..a86e86bc7a 100644
--- a/server/routes/universeBuilder.test.js
+++ b/server/routes/universeBuilder.test.js
@@ -67,11 +67,16 @@ vi.mock('../services/universeCharacterExpand.js', () => ({
expandUniverseCharacter: (...args) => expandUniverseCharacterMock(...args),
}));
-// Stub the reference-sheet renderer — only the route contract is verified
-// here; the actual prompt builder is exercised in universeCharacterSheet.test.js.
+// Stub the reference-sheet renderer + sibling exports — only the route
+// contract is verified here; the actual prompt builder + delete plumbing are
+// exercised in universeCharacterSheet.test.js / universeCharacterSheetDelete.test.js.
const renderCharacterReferenceSheetMock = vi.fn();
+const deleteCharacterReferenceSheetMock = vi.fn();
+const listSheetVariantsMock = vi.fn();
vi.mock('../services/universeCharacterSheet.js', () => ({
renderCharacterReferenceSheet: (...args) => renderCharacterReferenceSheetMock(...args),
+ deleteCharacterReferenceSheet: (...args) => deleteCharacterReferenceSheetMock(...args),
+ listSheetVariants: (...args) => listSheetVariantsMock(...args),
}));
// Stub the LLM expander so the route test doesn't shell out to a real provider.
@@ -755,10 +760,10 @@ describe('universe-builder routes', () => {
.post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')
.send({ overridePrompt: 'custom prompt', modelId: 'flux2-klein-9b' });
expect(res.status).toBe(200);
- expect(renderCharacterReferenceSheetMock).toHaveBeenCalledWith('u-1', 'c-1', expect.objectContaining({
- overridePrompt: 'custom prompt',
- modelId: 'flux2-klein-9b',
- }));
+ expect(renderCharacterReferenceSheetMock).toHaveBeenCalledWith(
+ 'u-1', 'c-1',
+ expect.objectContaining({ overridePrompt: 'custom prompt', modelId: 'flux2-klein-9b' }),
+ );
expect(res.body.jobId).toBe('job-c-1');
// generationId is now an alias for jobId (client back-compat).
expect(res.body.generationId).toBe('job-c-1');
@@ -797,4 +802,68 @@ describe('universe-builder routes', () => {
expect(res.body.code).toBe('UNIVERSE_CHARACTER_SHEET_UNSUPPORTED_MODE');
});
});
+
+ describe('POST /:id/characters/:entryId/render-reference-sheet (variant routing)', () => {
+ // The route is single-entry — non-default variants are selected via the
+ // body's `variant` field and forwarded to the service as a 4th arg.
+ it('forwards a body-supplied variant onto the service call', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')
+ .send({ variant: 'blueprint' });
+ expect(res.status).toBe(200);
+ expect(renderCharacterReferenceSheetMock).toHaveBeenCalledWith(
+ 'u-1', 'c-1', { variant: 'blueprint' },
+ );
+ });
+
+ it('rejects a variant that exceeds the 48-char Zod cap', async () => {
+ const res = await request(buildApp())
+ .post('/api/universe-builder/u-1/characters/c-1/render-reference-sheet')
+ .send({ variant: 'x'.repeat(49) });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe('DELETE /:id/characters/:entryId/reference-sheet (variant query)', () => {
+ beforeEach(() => {
+ deleteCharacterReferenceSheetMock.mockReset();
+ deleteCharacterReferenceSheetMock.mockResolvedValue({
+ filename: 'universe-u-1-c-1-blueprint-job.png',
+ fileDeleted: true,
+ cleared: 1,
+ });
+ });
+
+ it('forwards no variant (default) when query is empty', async () => {
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/u-1/characters/c-1/reference-sheet');
+ expect(res.status).toBe(200);
+ expect(deleteCharacterReferenceSheetMock).toHaveBeenCalledWith('u-1', 'c-1', {});
+ });
+
+ it('forwards `variant` from the query string', async () => {
+ const res = await request(buildApp())
+ .delete('/api/universe-builder/u-1/characters/c-1/reference-sheet?variant=blueprint');
+ expect(res.status).toBe(200);
+ expect(deleteCharacterReferenceSheetMock).toHaveBeenCalledWith('u-1', 'c-1', { variant: 'blueprint' });
+ });
+ });
+
+ describe('GET /reference-sheet-variants', () => {
+ beforeEach(() => {
+ listSheetVariantsMock.mockReset();
+ listSheetVariantsMock.mockReturnValue([
+ { id: 'standard', label: 'Illustrated', description: '...' },
+ { id: 'blueprint', label: 'Blueprint', description: '...' },
+ ]);
+ });
+
+ it('returns the registry catalog as { variants: [...] }', async () => {
+ const res = await request(buildApp()).get('/api/universe-builder/reference-sheet-variants');
+ expect(res.status).toBe(200);
+ expect(res.body.variants).toHaveLength(2);
+ expect(res.body.variants[0].id).toBe('standard');
+ expect(res.body.variants[1].id).toBe('blueprint');
+ });
+ });
});
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 0a31542708..70f4f7ea4d 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -142,7 +142,8 @@ export async function generateImage({
codexPath, model, prompt, width, height, negativePrompt,
initImagePath, initImageStrength,
jobId: providedJobId = null,
- autoClean = false,
+ cleanC2PA = false,
+ denoise = false,
}) {
if (!prompt?.trim()) {
throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
@@ -163,8 +164,9 @@ export async function generateImage({
// Width/height/negative aren't first-class args for Codex's built-in
// image_gen tool — pass them as natural-language hints inside the prompt.
// Codex's imagegen skill is prompt-driven; the model decides resolution.
- // gpt-image-2 honors a quality hint to escape its 1024 default and render
- // at native hi-res (1024×1536 / 1536×1024 / 1536×1536).
+ // gpt-image-2 supports up to 4K output; the "(high quality)" suffix
+ // pushes it off its 1024 default toward whatever native size best fits
+ // the requested aspect ratio.
const sizeHint = (width && height) ? ` (${width}x${height})` : '';
const qualityHint = (width >= 1536 || height >= 1536) ? ' (high quality)' : '';
const avoidHint = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
@@ -200,7 +202,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, { autoClean }).catch((err) => {
+ runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA, denoise }).catch((err) => {
console.log(`❌ codex run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
});
@@ -213,7 +215,7 @@ export async function generateImage({
};
}
-async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { autoClean = false } = {}) {
+async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false } = {}) {
const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
@@ -311,11 +313,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { aut
// 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: IMAGE_GEN_MODE.CODEX });
+ // Cleaners run BEFORE the SSE complete + completed events so subscribers
+ // see the cleaned bytes. codex output is the highest-value target for
+ // C2PA stripping because gpt-image is the one provider that embeds
+ // provenance metadata.
+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_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 ea878a82c1..731ef8741a 100644
--- a/server/services/imageGen/external.js
+++ b/server/services/imageGen/external.js
@@ -104,7 +104,7 @@ function startProgressPolling(baseUrl, generationId) {
let activeJob = null;
export const getActiveJob = () => activeJob;
-export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, height, steps, cfgScale, seed, autoClean }) {
+export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, height, steps, cfgScale, seed, cleanC2PA = false, denoise = false }) {
const baseUrl = validateSdUrl(sdapiUrl);
const model = await detectModel(baseUrl);
const isFlux = model?.toLowerCase().includes('flux');
@@ -172,7 +172,7 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h
// 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: IMAGE_GEN_MODE.EXTERNAL });
+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath, sidecarPath: null, mode: IMAGE_GEN_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 37f3c7efcd..a3d92720dc 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -14,6 +14,7 @@
import { getSettings } from '../settings.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { resolveCleanersFromConfig } from '../../lib/imageClean.js';
import * as external from './external.js';
import * as local from './local.js';
import * as codex from './codex.js';
@@ -32,13 +33,18 @@ const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;
const pythonPath = (s) => cfg(s).local?.pythonPath || null;
const codexCfg = (s) => cfg(s).codex || {};
-// Body wins when explicit (per-render checkbox); otherwise inherit the saved
-// per-mode default. Shared by `/generate` (stamps the resolved value onto the
-// request so all three dispatch paths agree) and `generateImage()` (safety net
-// for direct callers like `generateAvatar`).
-export function resolveAutoClean(bodyValue, settings, mode) {
- if (typeof bodyValue === 'boolean') return bodyValue;
- return cfg(settings)[mode]?.autoClean === true;
+// Resolve the cleaner flags from body overrides + saved per-mode settings.
+// Body fields win when explicit (per-render checkbox); otherwise inherit
+// the saved per-mode defaults (which include the legacy `autoClean: true`
+// → both-flags migration handled by `resolveCleanersFromConfig`). Shared
+// by `/generate` and `generateImage()` (safety net for direct callers
+// like `generateAvatar`).
+export function resolveImageCleaners(body, settings, mode) {
+ const saved = resolveCleanersFromConfig(cfg(settings)[mode]);
+ return {
+ cleanC2PA: typeof body?.cleanC2PA === 'boolean' ? body.cleanC2PA : saved.cleanC2PA,
+ denoise: typeof body?.denoise === 'boolean' ? body.denoise : saved.denoise,
+ };
}
export async function getMode() {
@@ -84,13 +90,14 @@ export async function generateImage(params) {
delete normalized.initImagePath;
delete normalized.initImageStrength;
}
- // Auto-clean is per-provider-mode, opt-in. The route layer already resolves
- // this so the queue/route paths agree, but resolve here too for direct
- // callers (e.g. `generateAvatar`) that skip the route. Strip from
- // `normalized` so the explicit arg on each provider call isn't shadowed by
- // the spread.
- const autoClean = resolveAutoClean(normalized.autoClean, s, mode);
- delete normalized.autoClean;
+ // Cleaners are per-provider-mode. The route layer already resolves them so
+ // the queue/route paths agree, but resolve here too for direct callers
+ // (e.g. `generateAvatar`) that skip the route. Strip from `normalized`
+ // so the explicit args on each provider call aren't shadowed by the spread.
+ const { cleanC2PA, denoise } = resolveImageCleaners(normalized, s, mode);
+ delete normalized.cleanC2PA;
+ delete normalized.denoise;
+ delete normalized.autoClean; // legacy body field — accept-and-ignore
if (mode === IMAGE_GEN_MODE.CODEX) {
const c = codexCfg(s);
if (!c.enabled) {
@@ -99,12 +106,12 @@ export async function generateImage(params) {
{ status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },
);
}
- return codex.generateImage({ codexPath: c.codexPath, model: c.model, autoClean, ...normalized });
+ return codex.generateImage({ codexPath: c.codexPath, model: c.model, cleanC2PA, denoise, ...normalized });
}
if (mode === IMAGE_GEN_MODE.LOCAL) {
- return local.generateImage({ pythonPath: pythonPath(s), autoClean, ...normalized });
+ return local.generateImage({ pythonPath: pythonPath(s), cleanC2PA, denoise, ...normalized });
}
- return external.generateImage({ sdapiUrl: sdapiUrl(s), autoClean, ...normalized });
+ return external.generateImage({ sdapiUrl: sdapiUrl(s), cleanC2PA, denoise, ...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 fe4da2401b..c0c62c33c8 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -216,7 +216,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, autoClean = false }) {
+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, cleanC2PA = false, denoise = 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
@@ -558,9 +558,11 @@ 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: IMAGE_GEN_MODE.LOCAL });
+ // Cleaners run BEFORE the SSE complete + completed events so subscribers
+ // see the cleaned bytes. Local FLUX renders never carry C2PA chunks so
+ // cleanC2PA is a no-op on local — denoise is the only mode that does
+ // anything here.
+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_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 });
diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.js
index 3f68659278..428356e1cc 100644
--- a/server/services/pipeline/visualStages.js
+++ b/server/services/pipeline/visualStages.js
@@ -45,7 +45,7 @@ import { pickCanon } from './seriesCanon.js';
import { STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';
import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
-import { resolveAutoClean } from '../imageGen/index.js';
+import { resolveImageCleaners } from '../imageGen/index.js';
const joinStyleParts = (...parts) =>
parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');
@@ -181,15 +181,15 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),
};
// The queue dispatches directly to imageGen/{codex,local}.generateImage,
- // bypassing imageGen/index.js's dispatcher that resolves autoClean for
- // direct callers. The /api/image-gen/generate route resolves it at the
+ // bypassing imageGen/index.js's dispatcher that resolves cleaners for
+ // direct callers. The /api/image-gen/generate route resolves them at the
// route layer; pipeline renders need the same resolution here, otherwise
- // the saved settings.imageGen[mode].autoClean has no effect on storyboard,
- // comic-panel, or cover renders.
- const autoClean = resolveAutoClean(undefined, settings, mode);
+ // the saved settings.imageGen[mode].{cleanC2PA,denoise} would have no
+ // effect on storyboard, comic-panel, or cover renders.
+ const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
const params = mode === IMAGE_GEN_MODE.CODEX
- ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, autoClean, ...baseParams }
- : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, autoClean, ...baseParams };
+ ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, cleanC2PA, denoise, ...baseParams }
+ : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };
const { jobId } = enqueueJob({ kind: 'image', params, owner });
console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);
return jobId;
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 9c088e23fc..05d3e33826 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -30,7 +30,7 @@ import { getJob } from '../mediaJobQueue/index.js';
import { getInstanceId } from '../instances.js';
import { getSettings } from '../settings.js';
import { getProducedByVersion } from './version.js';
-import { isStr } from '../../lib/storyBible.js';
+import { isStr, listSheetPointers } from '../../lib/storyBible.js';
import { resolveBucketSourceName as resolveSourceName } from './annotationIdentity.js';
/**
@@ -264,7 +264,12 @@ function collectAssetReferences(record) {
if (Array.isArray(node.imageRefs)) {
for (const r of node.imageRefs) if (isStr(r)) directImageFilenames.add(r);
}
- if (isStr(node.referenceSheetImageRef)) directImageRefFilenames.add(node.referenceSheetImageRef);
+ // Every character-sheet variant the renderer produced — legacy + map.
+ // listSheetPointers yields one entry per non-empty pointer regardless of
+ // storage shape, so the export bundle includes every render.
+ for (const { filename } of listSheetPointers(node)) {
+ if (isStr(filename)) directImageRefFilenames.add(filename);
+ }
if (isStr(node.videoPath)) directVideoFilenames.add(basename(node.videoPath));
for (const k of Object.keys(node)) {
const v = node[k];
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 5581a89384..f8abfe7cff 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -33,8 +33,7 @@ import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';
import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../lib/canonPrompt.js';
import {
sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,
- SERVER_OWNED_CHARACTER_FIELDS,
- pruneStaleReferenceSheets,
+ pruneStaleReferenceSheets, mergePreservedSheetPointers,
normalizeBibleName, isStr, trimTo,
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
@@ -998,24 +997,19 @@ export async function updateUniverse(id, patchOrMutator = {}) {
&& Array.isArray(scalarPatch.characters)
&& Array.isArray(cur.characters)) {
const curById = new Map(cur.characters.filter((c) => c?.id).map((c) => [c.id, c]));
+ // Preserve cur's server-stamped sheet pointers ONLY when they still
+ // resolve on disk. Without the FS check, this guard reintroduces
+ // stale pointers that the GET route's lazy `pruneStaleReferenceSheets`
+ // already nulled out: GET → null (file gone) → client PATCH carries
+ // null → guard overwrites null with cur's stale filename → thumbnail
+ // 404s again. The map variant (`referenceSheets`) merges per-key so a
+ // freshly-stamped blueprint can't be clobbered by a patch that omits
+ // the field while a separately-rendered standard sheet survives.
+ const checkExists = (name) => !!resolveImageRef(name, { mustExist: true });
scalarPatch.characters = scalarPatch.characters.map((c) => {
const prev = c?.id ? curById.get(c.id) : null;
if (!prev) return c;
- const preserved = { ...c };
- // Preserve cur's value ONLY when it still resolves on disk. Without
- // the FS check, this guard reintroduces stale pointers that the
- // GET route's lazy `pruneStaleReferenceSheets` already nulled out:
- // GET → null (file gone) → client PATCH carries null → guard
- // overwrites null with cur's stale filename → thumbnail 404s
- // again. The pruner returns null for non-existent files, so we
- // skip preservation in that case and let the patch's value (the
- // pruned null) survive.
- for (const f of SERVER_OWNED_CHARACTER_FIELDS) {
- if (prev[f] && resolveImageRef(prev[f], { mustExist: true })) {
- preserved[f] = prev[f];
- }
- }
- return preserved;
+ return mergePreservedSheetPointers(prev, c, checkExists);
});
}
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index f7375f8eec..26449fc780 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -441,6 +441,41 @@ describe("universeBuilder service", () => {
refSheetFilesByName.delete("sheet-DEAD.png");
});
+ it("updateUniverse preserves server-owned referenceSheets[<variant>] map across literal PATCHes", async () => {
+ // Same multi-tab race, but for the map-stored variants (blueprint, etc.).
+ // A render-completion mutator stamps `referenceSheets.blueprint`; a stale
+ // client PATCH that round-trips a body with the field omitted (or with
+ // an older snapshot) must NOT lose the freshly-stamped variant. Per-key
+ // preservation means a separately-rendered legacy 'standard' sheet
+ // survives even when only blueprint is in the map.
+ const w = await seedWorld();
+ await svc.updateUniverse(w.id, (latest) => ({
+ characters: [...(latest.characters || []), {
+ id: "c-map", name: "Vex",
+ referenceSheetImageRef: "sheet-STD.png",
+ referenceSheets: { blueprint: "sheet-BP.png" },
+ }],
+ }));
+ // PATCH that omits referenceSheets entirely — guard must preserve both
+ // the legacy 'standard' field AND the blueprint map slot.
+ const afterOmit = await svc.updateUniverse(w.id, {
+ characters: [{ id: "c-map", name: "Vex" }],
+ });
+ const c1 = afterOmit.characters.find((c) => c.id === "c-map");
+ expect(c1?.referenceSheetImageRef).toBe("sheet-STD.png");
+ expect(c1?.referenceSheets).toEqual({ blueprint: "sheet-BP.png" });
+
+ // PATCH that carries an older map (a different variant set or stale
+ // filename). Cur's still-resolvable entries override the patch's same
+ // keys; the patch's other keys flow through.
+ const afterStale = await svc.updateUniverse(w.id, {
+ characters: [{ id: "c-map", name: "Vex", referenceSheets: { blueprint: "sheet-OLD.png", noir: "sheet-NOIR.png" } }],
+ });
+ const c2 = afterStale.characters.find((c) => c.id === "c-map");
+ expect(c2?.referenceSheets.blueprint).toBe("sheet-BP.png"); // cur wins (resolves)
+ expect(c2?.referenceSheets.noir).toBe("sheet-NOIR.png"); // patch-only key flows through
+ });
+
it("updateUniverse persists null for stale referenceSheetImageRef on the write path, not just GET", async () => {
// Reviewer-found bug: the GET-route pruner nulled the response but the
// on-disk record kept the stale filename, so a later PATCH that omitted
diff --git a/server/services/universeCanon.js b/server/services/universeCanon.js
index f1d1ee73b8..4979715d83 100644
--- a/server/services/universeCanon.js
+++ b/server/services/universeCanon.js
@@ -8,6 +8,7 @@ import { getUniverse, updateUniverse, listUniverses, joinInfluenceList } from '.
import { extractBible } from '../lib/bibleExtractor.js';
import {
BIBLE_KIND, BIBLE_KINDS, BIBLE_FIELD, BIBLE_KEYS, BIBLE_SOURCE, mergeExtractedBible,
+ listSheetPointers, applySheetPointerToCharacter,
} from '../lib/storyBible.js';
import { runStagedLLM } from '../lib/stageRunner.js';
import { runPromptRefine } from './pipeline/refineHelpers.js';
@@ -362,40 +363,49 @@ export async function purgeImageRefFromAllUniverses(filename) {
}
/**
- * Null out `character.referenceSheetImageRef` on every character (across every
- * universe) whose pointer matches `filename`. Mirrors `purgeImageRefFromAllUniverses`
- * but targets the single-string sheet pointer rather than the `imageRefs[]` array.
+ * Null out any server-stamped sheet pointer (legacy `referenceSheetImageRef`
+ * field OR any key in the `referenceSheets` map) whose value matches
+ * `filename`, on every character across every universe. Mirrors
+ * `purgeImageRefFromAllUniverses` but targets per-variant sheet pointers and
+ * is variant-agnostic — the filename is the lookup key, the storage slot it
+ * happens to live in is implementation detail.
*
* Wired into the sheet-delete route so the eager pointer-clear lands the same
* moment the file is unlinked. The GET-time lazy `pruneStaleReferenceSheets`
* is still the safety net for files deleted out-of-band (filesystem cleanup,
* sample-data resets) — this helper is the eager path.
*
- * Uses `updateUniverse`'s mutator form because `referenceSheetImageRef` is in
- * `SERVER_OWNED_CHARACTER_FIELDS` — a literal-object PATCH would be guarded
- * against clobbering the server-stamped pointer (the guard preserves cur's
- * value when its file still resolves on disk). The purge IS the server-side
- * writer, so it has to bypass that guard via the mutator form.
+ * Uses `updateUniverse`'s mutator form because both `referenceSheetImageRef`
+ * and `referenceSheets` are in `SERVER_OWNED_CHARACTER_FIELDS` — a literal-
+ * object PATCH would be guarded against clobbering the server-stamped value
+ * (the guard preserves cur's value when its file still resolves on disk).
+ * The purge IS the server-side writer, so it has to bypass that guard via
+ * the mutator form.
*/
export async function purgeReferenceSheetFromAllUniverses(filename) {
if (!filename || typeof filename !== 'string') return { cleared: 0 };
const universes = await listUniverses();
let cleared = 0;
+ // No pre-check: the mutator returns null when no characters matched, so
+ // updateUniverse skips the write. Single pass per universe instead of two.
for (const universe of universes) {
- const characters = Array.isArray(universe.characters) ? universe.characters : null;
- if (!characters) continue;
- if (!characters.some((entry) => entry?.referenceSheetImageRef === filename)) continue;
+ if (!Array.isArray(universe.characters)) continue;
await updateUniverse(universe.id, (cur) => {
const list = Array.isArray(cur.characters) ? cur.characters : [];
let touched = false;
const nextList = list.map((entry) => {
- if (entry?.referenceSheetImageRef !== filename) return entry;
- cleared += 1;
- touched = true;
- return { ...entry, referenceSheetImageRef: null };
+ let next = entry;
+ for (const { variant, filename: f } of listSheetPointers(entry)) {
+ if (f !== filename) continue;
+ next = applySheetPointerToCharacter(next, variant, null);
+ cleared += 1;
+ touched = true;
+ }
+ return next;
});
return touched ? { characters: nextList } : null;
});
}
return { cleared };
}
+
diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.js
index 94249a969f..c8a6e41eca 100644
--- a/server/services/universeCanon.test.js
+++ b/server/services/universeCanon.test.js
@@ -318,6 +318,29 @@ describe('universeCanon — purgeReferenceSheetFromAllUniverses', () => {
expect(await canonSvc.purgeReferenceSheetFromAllUniverses(null)).toEqual({ cleared: 0 });
expect(await canonSvc.purgeReferenceSheetFromAllUniverses(undefined)).toEqual({ cleared: 0 });
});
+
+ it('also clears matching variant keys inside referenceSheets map (blueprint, etc.)', async () => {
+ // Mixed-shape fixture: Alex has the filename in the map slot, Beth has
+ // the same filename in the legacy field — purge must clear both in one
+ // call, regardless of which storage shape a given character used.
+ const w1 = await seedUniverseWithCharacters([
+ { name: 'Alex', physicalDescription: 'a', referenceSheets: { blueprint: 'shared.png' } },
+ { name: 'Beth', physicalDescription: 'b', referenceSheetImageRef: 'shared.png' },
+ { name: 'Cara', physicalDescription: 'c', referenceSheets: { blueprint: 'other.png', noir: 'shared.png' } },
+ ]);
+ const result = await canonSvc.purgeReferenceSheetFromAllUniverses('shared.png');
+ expect(result.cleared).toBe(3);
+
+ const reread = await svc.getUniverse(w1.id);
+ const alex = reread.characters.find((c) => c.name === 'Alex');
+ const beth = reread.characters.find((c) => c.name === 'Beth');
+ const cara = reread.characters.find((c) => c.name === 'Cara');
+ expect(alex.referenceSheets).toEqual({});
+ expect(beth.referenceSheetImageRef).toBeNull();
+ // Cara only loses the 'noir' key; 'blueprint' (pointing at a different
+ // file) survives the purge.
+ expect(cara.referenceSheets).toEqual({ blueprint: 'other.png' });
+ });
});
describe('universeCanon — purgeImageRefFromAllUniverses', () => {
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index 5643a81605..91ecb6d9ef 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -25,20 +25,39 @@ import { getImageModels } from '../lib/mediaModels.js';
import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';
import { findOrCreateUniverseCollection } from './mediaCollections.js';
import { IMAGE_GEN_MODE } from './imageGen/modes.js';
-import { resolveAutoClean } from './imageGen/index.js';
import {
flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,
} from '../lib/canonPrompt.js';
+import {
+ LEGACY_SHEET_VARIANT_ID, readSheetPointer, applySheetPointerToCharacter,
+} from '../lib/storyBible.js';
import {
claimPendingSheetSlot, getPendingSheetSlot, releasePendingSheetSlot,
} from './universeCharacterSheetSlot.js';
-// 2048×1536 keeps panel labels legible while still rendering in a single
-// pass on Apple Silicon local backends. Codex / nano-banana ignore the
-// hint past 1536 max edge but still honor the aspect ratio.
+// Local FLUX backend: 2048×1536 keeps panel labels legible while still
+// rendering in a single pass on Apple Silicon.
const DEFAULT_WIDTH = 2048;
const DEFAULT_HEIGHT = 1536;
+// Codex (gpt-image-2) renders up to 4K. For a character concept sheet with
+// annotation callouts + close-up panels + multi-view turnaround, text is
+// the legibility bottleneck — annotations need enough pixels per glyph to
+// stay readable when the user zooms in. Request 4096×3072 (4:3 landscape,
+// same aspect as the FLUX default so the template layout stays consistent
+// across backends) so the model has room for the panel grid AND the text.
+const CODEX_WIDTH = 4096;
+const CODEX_HEIGHT = 3072;
+
+// Resolve the (width, height) hint per backend mode. The prompt builders
+// return the FLUX-tuned defaults; the renderer overrides for codex so the
+// text annotations land at codex's native hi-res instead of being downsampled
+// from a smaller request.
+function resolveSheetDimensions(mode, builtWidth, builtHeight) {
+ if (mode === IMAGE_GEN_MODE.CODEX) return { width: CODEX_WIDTH, height: CODEX_HEIGHT };
+ return { width: builtWidth || DEFAULT_WIDTH, height: builtHeight || DEFAULT_HEIGHT };
+}
+
// Resolve the local-mode model id. With pure text-template rendering we no
// longer depend on FLUX.2-specific init-image / multi-ref flags, so any
// registered model is fair game. Order:
@@ -64,6 +83,35 @@ const DEFAULT_HAND_GESTURES = Object.freeze([
const trim = (s) => (typeof s === 'string' ? s.trim() : '');
+// Shared field bag used by every variant's prompt builder. Centralizes the
+// trim/flatten calls so a new variant only writes the style-specific layout
+// sentences. Pure — caller decides which fields to weave into its prompt.
+function extractCharacterPromptCommon(character) {
+ return {
+ name: trim(character.name) || 'Unnamed',
+ aliases: Array.isArray(character.aliases) ? character.aliases.filter(Boolean).join(', ') : '',
+ role: trim(character.role),
+ pronouns: trim(character.pronouns),
+ age: trim(character.age),
+ personality: trim(character.personality),
+ speechAccent: trim(character.speechAccent),
+ speechPattern: trim(character.speechPattern),
+ coreTheme: trim(character.coreTheme),
+ visualNotes: trim(character.visualNotes),
+ physical: trim(character.physicalDescription),
+ silhouette: trim(character.silhouetteNotes),
+ posture: trim(character.postureNotes),
+ special: trim(character.specialTraits),
+ visualIdentity: trim(character.visualIdentity),
+ statsLine: flattenStats(character.stats),
+ paletteLine: flattenPalette(character.colorPalette),
+ wardrobeLine: flattenWardrobes(character.wardrobes),
+ propsLine: flattenProps(character.props),
+ expressionsLine: flattenNamedList(character.expressions, DEFAULT_EXPRESSIONS),
+ gesturesLine: flattenNamedList(character.handGestures, DEFAULT_HAND_GESTURES),
+ };
+}
+
/**
* Build the prompt + render options for one character's reference sheet.
* Pure function — does no I/O, doesn't enqueue anything. The route handler
@@ -84,16 +132,11 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
const styleClause = buildStyleClause(universe);
const styleBits = styleClause.startsWith('(none provided') ? '' : styleClause;
- const name = trim(character.name) || 'Unnamed';
- const aliases = Array.isArray(character.aliases) ? character.aliases.filter(Boolean).join(', ') : '';
- const role = trim(character.role);
- const pronouns = trim(character.pronouns);
- const age = trim(character.age);
- const personality = trim(character.personality);
- const speechAccent = trim(character.speechAccent);
- const speechPattern = trim(character.speechPattern);
- const coreTheme = trim(character.coreTheme);
- const visualNotes = trim(character.visualNotes);
+ const {
+ name, aliases, role, pronouns, age, personality, speechAccent, speechPattern,
+ coreTheme, visualNotes, physical, silhouette, posture, special, visualIdentity,
+ statsLine, paletteLine, wardrobeLine, propsLine, expressionsLine, gesturesLine,
+ } = extractCharacterPromptCommon(character);
const headerBits = [
`Name: ${name}.`,
@@ -108,19 +151,6 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
visualNotes ? `Visual notes: ${visualNotes}.` : '',
].filter(Boolean).join(' ');
- const physical = trim(character.physicalDescription);
- const silhouette = trim(character.silhouetteNotes);
- const posture = trim(character.postureNotes);
- const special = trim(character.specialTraits);
- const visualIdentity = trim(character.visualIdentity);
-
- const statsLine = flattenStats(character.stats);
- const paletteLine = flattenPalette(character.colorPalette);
- const wardrobeLine = flattenWardrobes(character.wardrobes);
- const propsLine = flattenProps(character.props);
- const expressionsLine = flattenNamedList(character.expressions, DEFAULT_EXPRESSIONS);
- const gesturesLine = flattenNamedList(character.handGestures, DEFAULT_HAND_GESTURES);
-
// Order matters: the model honors earliest tokens most reliably, so style +
// header lead, then the per-zone layout enumeration.
const promptParts = [
@@ -160,11 +190,156 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
};
}
+/**
+ * Pick the two colors that drive the blueprint sheet's "glowing accents" +
+ * "structured base" aesthetic from the character's canonical palette. Prefers
+ * the human-readable name (`teal`, `cobalt`) for prompt legibility, falls
+ * back to hex when name is missing, and finally to a safe cyan/navy pair so
+ * the prompt always has two concrete tokens. Pure — no I/O, no settings.
+ *
+ * Returned as `{ accent, base }`; both are non-empty strings.
+ */
+export function pickBlueprintColors(palette) {
+ const cleaned = Array.isArray(palette)
+ ? palette
+ .map((c) => trim(c?.name) || trim(c?.hex))
+ .filter(Boolean)
+ : [];
+ const accent = cleaned[0] || 'cyan';
+ // Avoid collapsing the two color tokens onto the same string — if the
+ // palette only has one entry, fall back to a contrasting default for the
+ // base so the prompt's "glowing X on structured Y" reads as two colors.
+ const base = (cleaned[1] && cleaned[1] !== accent) ? cleaned[1] : 'navy';
+ return { accent, base };
+}
+
+/**
+ * Blueprint variant — professional character concept sheet aesthetic.
+ *
+ * The "blueprint" here is the PRESENTATION (annotation callouts, schematic
+ * line drawings, technical labels arranged around the figure), NOT a literal
+ * blueprint-paper rendering. The character itself is fully illustrated in
+ * the universe's own art style — only the surrounding annotation framework
+ * and callout lines pick up the accent/base palette colors. This matches
+ * the "professional concept art turnaround" look (fully-illustrated
+ * character on a clean white sheet, with technical annotations + close-up
+ * studies framing the multi-view turnaround), not a cyanotype.
+ */
+export function buildCharacterBlueprintSheetPrompt(universe, character) {
+ if (!universe || !character) {
+ throw new ServerError('buildCharacterBlueprintSheetPrompt: universe and character are required', {
+ status: 400, code: 'VALIDATION_ERROR',
+ });
+ }
+
+ const styleClause = buildStyleClause(universe);
+ const styleBits = styleClause.startsWith('(none provided') ? '' : styleClause;
+
+ const {
+ name, role, physical, silhouette, special, visualNotes,
+ wardrobeLine, propsLine, paletteLine,
+ } = extractCharacterPromptCommon(character);
+ const { accent, base } = pickBlueprintColors(character.colorPalette);
+
+ const subject = role ? `${name} — ${role}` : name;
+ // Concrete label strings (vs abstract "annotations"): gpt-image-2 renders
+ // explicit short tokens much more reliably than invented-on-the-fly text.
+ // Mirrors the standard sheet's per-zone enumeration where the canon
+ // populates each label literally.
+ const turnaroundLabels = '"01 FRONT", "02 THREE-QUARTER", "03 SIDE", "04 BACK"';
+ const headStudyLabels = '"FACE FRONT", "PROFILE", "THREE-QUARTER", "EXPRESSION"';
+
+ // Lead with the user's exact prompt template (load-bearing phrasing the
+ // model anchors on), then layer in canon details with concrete label
+ // strings so the model has explicit text to render verbatim — not vague
+ // "labels" that come out as gibberish glyphs.
+ const promptParts = [
+ `A character concept sheet of ${subject}, featuring detailed front, back, and side views, along with close-up sketches of facial features, costume details, and accessories. Annotated design notes and clearly labeled components are arranged across the layout, rendered in a refined blueprint style with glowing ${accent} accents and a structured ${base} base design, presented on a clean white background with a polished professional character design presentation.`,
+ styleBits || 'Style: contemporary illustrated character design with confident line work and saturated, intentional color.',
+ `Header banner across the top of the sheet reads, in bold legible typography: "${name.toUpperCase()}${role ? ` — ${role.toUpperCase()}` : ''}".`,
+ `Main turnaround zone (large, fills the left two-thirds of the sheet): four full-body views of ${name} at consistent scale — FRONT, 3/4, SIDE, BACK — all fully illustrated in the universe's color palette. Each view sits over a small caption strip; the four caption strips read, left to right: ${turnaroundLabels}.`,
+ physical ? `Physical description (annotation paragraph next to the turnaround): ${physical}` : '',
+ visualNotes ? `Visual notes annotation: ${visualNotes}` : '',
+ silhouette ? `Silhouette annotation: ${silhouette}` : '',
+ special ? `Special traits annotation: ${special}` : '',
+ `Facial feature sketches (top-right zone): four close-up sketches of ${name}'s face from different angles, in a 2×2 grid, each below a caption reading one of: ${headStudyLabels}.`,
+ wardrobeLine
+ ? `Costume detail sketches (right margin column): labeled close-up sketches of distinctive wardrobe pieces. Caption labels read literally: ${wardrobeLine}.`
+ : 'Costume detail sketches (right margin column): three labeled close-up sketches of signature garments. Caption labels read literally: "FABRIC", "FASTENINGS", "LAYERING".',
+ propsLine
+ ? `Accessory sketches (bottom margin row): labeled close-up sketches of the character's signature props. Caption labels read literally: ${propsLine}.`
+ : 'Accessory sketches (bottom margin row): three labeled close-up sketches of signature accessories. Caption labels read literally: "ACCESSORY", "GEAR", "PROP".',
+ paletteLine
+ ? `Color palette swatch row (under the turnaround captions): horizontal row of color chips, each labeled with its swatch name in legible type — ${paletteLine}.`
+ : '',
+ `Annotation framework: thin guide lines connect each margin sketch to its detail on the figure. Numbered tags ("01", "02", "03", "04") index the four turnaround captions. Margin sketch captions use bold uppercase typography at large size — readable at a glance without zooming.`,
+ `Blueprint accent scope: the "refined blueprint style with glowing ${accent} accents and a structured ${base} base design" applies to the ANNOTATION LAYER — guide lines, caption strips, dimension marks, schematic linework, numbered index tags, and frame borders. The CHARACTER and its costume/props stay rendered in the universe's full color palette in a fully illustrated style. Do NOT render the character as a cyanotype, blueprint-paper line drawing, or monochrome wireframe.`,
+ 'Typography requirement: every caption, label, and header above is rendered as legible, bold, properly-letterformed text — not abstract scribbles, not faux-Latin gibberish, not blurred glyphs. Treat the caption strings as real text strings the viewer will read.',
+ ].filter(Boolean);
+
+ const prompt = promptParts.join('\n\n');
+ const negativePrompt = 'cyanotype, blueprint paper background, blue paper background, line-art-only character, monochrome character, wireframe character, multiple different characters in the same panel, photograph, painterly background, watercolor wash, dark background, cluttered background, watermark, signature, blurry, distorted anatomy, illegible text, scribbled labels, faux-latin gibberish, blurred caption text, garbled lettering';
+
+ return {
+ prompt,
+ negativePrompt,
+ width: DEFAULT_WIDTH,
+ height: DEFAULT_HEIGHT,
+ modelId: null,
+ };
+}
+
// Per-generation filename so re-renders don't trample prior versions; the
-// "live" sheet pointer on the character (`referenceSheetImageRef`) always
-// names the newest, but older files stay on disk for rollback.
-const sheetFilename = (universeId, characterId, generationId) =>
- `universe-${shortId(universeId)}-${shortId(characterId)}-sheet-${shortId(generationId)}.png`;
+// "live" sheet pointer on the character always names the newest, but older
+// files stay on disk for rollback. The variant token in the middle keeps
+// different-style renders from colliding for the same character + jobId pair.
+const sheetFilename = (universeId, characterId, generationId, variantToken = 'sheet') =>
+ `universe-${shortId(universeId)}-${shortId(characterId)}-${variantToken}-${shortId(generationId)}.png`;
+
+// Catalog of renderable sheet styles. Adding a new variant = entry here +
+// a prompt-builder function. Storage routing (legacy field vs map slot) is
+// owned by `applySheetPointerToCharacter` / `readSheetPointer` in storyBible.js
+// based on the variant id, so new variants need no schema or routing changes.
+const SHEET_VARIANTS = Object.freeze({
+ [LEGACY_SHEET_VARIANT_ID]: Object.freeze({
+ id: LEGACY_SHEET_VARIANT_ID,
+ build: buildCharacterReferenceSheetPrompt,
+ filenameToken: 'sheet',
+ label: 'Illustrated turnaround',
+ description: 'Dense multi-zone reference sheet — front/back/side views, expression progression, color palette, wardrobe + props, hand gestures. Renders in the universe\'s defined illustrated style.',
+ collectionCategory: 'character-sheet',
+ }),
+ blueprint: Object.freeze({
+ id: 'blueprint',
+ build: buildCharacterBlueprintSheetPrompt,
+ filenameToken: 'blueprint',
+ label: 'Blueprint concept sheet',
+ description: 'Annotated character concept sheet on a clean white background with glowing accent linework over a structured base color. Both colors auto-pick from the character\'s palette.',
+ collectionCategory: 'character-blueprint',
+ }),
+});
+
+function getVariantConfig(variant = LEGACY_SHEET_VARIANT_ID) {
+ // Own-property check so `variant=constructor` / `toString` / `hasOwnProperty`
+ // from an unfiltered request body can't return an inherited Object.prototype
+ // member and have downstream `.build()` / `.storage` access crash with a 500.
+ if (!Object.prototype.hasOwnProperty.call(SHEET_VARIANTS, variant)) {
+ throw new ServerError(`Unknown character sheet variant "${variant}"`, {
+ status: 400, code: 'VALIDATION_ERROR',
+ });
+ }
+ return SHEET_VARIANTS[variant];
+}
+
+// Catalog for the UI — pure, no I/O. The client renders one panel row per
+// entry. New entries here become available everywhere without further wiring.
+export function listSheetVariants() {
+ return Object.values(SHEET_VARIANTS).map((v) => ({
+ id: v.id,
+ label: v.label,
+ description: v.description,
+ }));
+}
// `(universeId, characterId) → latest generationId requested` is owned by
// `./universeCharacterSheetSlot.js` (extracted so universeBuilder.js can
@@ -200,8 +375,14 @@ function subscribeToSheetJob(jobId, handlers) {
* Returns immediately with `{ jobId, generationId, filename, path }`.
* Deferred copy + character stamp run when imageGenEvents emits 'completed';
* any failure there is logged (the client tracks the render via SSE).
+ *
+ * `variant` selects the sheet style ('standard' = illustrated turnaround,
+ * 'blueprint' = annotated concept sheet on white). Defaults to 'standard'
+ * so existing callers (and the legacy route) stay unchanged.
*/
export async function renderCharacterReferenceSheet(universeId, entryId, options = {}) {
+ const variant = options.variant || LEGACY_SHEET_VARIANT_ID;
+ const variantConfig = getVariantConfig(variant);
const universe = await getUniverse(universeId);
const list = Array.isArray(universe.characters) ? universe.characters : [];
const character = list.find((c) => c.id === entryId);
@@ -220,7 +401,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
);
}
- const built = buildCharacterReferenceSheetPrompt(universe, character);
+ const built = variantConfig.build(universe, character);
const prompt = typeof options.overridePrompt === 'string' && options.overridePrompt.trim()
? options.overridePrompt.trim()
@@ -235,19 +416,26 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// first-class. External SD-API has no multi-zone layout support, so it
// gets a clear remediation rather than a silently-degraded render.
const activeMode = settings.imageGen?.mode || IMAGE_GEN_MODE.LOCAL;
- // The queue dispatches directly to imageGen/{codex,local}.generateImage,
- // bypassing imageGen/index.js's dispatcher that resolves autoClean for
- // direct callers. Resolve here so saved settings.imageGen[mode].autoClean
- // applies to character reference-sheet renders the same way it does for
- // /api/image-gen/generate, pipeline, and Universe Builder batch renders.
- const autoClean = resolveAutoClean(undefined, settings, activeMode);
+ // Sheet renders hard-code cleanC2PA=true (lossless metadata strip — gpt-image
+ // adds a caBX provenance chunk we don't want to ship) and denoise=false
+ // (the median+sharpen pass blurs annotation text; sheets ship with their
+ // text labels AS the product so that pass is never acceptable here).
+ // Other render paths still honor the user's per-mode settings.
+ const cleanC2PA = true;
+ const denoise = false;
+ // Codex's image_gen tool can render up to 4K — asking for FLUX's 2048×1536
+ // under-uses the available headroom and pixelates annotation text when the
+ // user zooms. resolveSheetDimensions bumps codex up to 4K landscape while
+ // local FLUX keeps its memory-tuned 2048×1536 defaults.
+ const { width, height } = resolveSheetDimensions(activeMode, built.width, built.height);
const baseParams = {
mode: activeMode,
prompt,
negativePrompt,
- width: built.width,
- height: built.height,
- autoClean,
+ width,
+ height,
+ cleanC2PA,
+ denoise,
};
let modelId = null;
@@ -299,7 +487,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
runId: randomUUID(),
universeId: universe.id,
collectionId: collection.id,
- category: 'character-sheet',
+ category: variantConfig.collectionCategory,
label: character.name,
};
}
@@ -309,10 +497,12 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// dispatches by `params.mode` (codex → codex lane, local → GPU lane).
const queued = enqueueJob({ kind: 'image', params });
const jobId = queued.jobId;
- // Claim the latest-pending slot for this character. onSheetComplete checks
- // it before stamping — guards against an older-but-slower render finishing
- // after a newer one and overwriting the newer pointer.
- claimPendingSheetSlot(universeId, entryId, jobId);
+ // Claim the latest-pending slot for this character + variant. onSheetComplete
+ // checks it before stamping — guards against an older-but-slower render
+ // finishing after a newer one and overwriting the newer pointer. The variant
+ // key keeps standard and blueprint slots independent so a blueprint render
+ // can't be superseded by an illustrated one or vice versa.
+ claimPendingSheetSlot(universeId, entryId, jobId, variant);
// Subscribe to the queue's completion bus via the shared sheet
// dispatcher (NOT imageGenEvents directly — the queue mediates the
@@ -341,7 +531,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
const armTimeout = (ms, reason) => {
if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(() => {
- console.log(`⏱️ Character sheet render ${reason} [${shortId(jobId)}] — detaching`);
+ console.log(`⏱️ ${variantConfig.label} render ${reason} [${shortId(jobId)}] — detaching`);
detach();
}, ms);
timeoutHandle.unref?.();
@@ -355,15 +545,15 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
onCompleted: async (job) => {
detach();
const sourceFilename = job.result?.filename;
- await onSheetComplete({ universeId, entryId, jobId, sourceFilename }).catch((err) => {
- console.error(`❌ Character sheet post-completion failed [${shortId(jobId)}]: ${err?.message}`);
+ await onSheetComplete({ universeId, entryId, jobId, sourceFilename, variant }).catch((err) => {
+ console.error(`❌ ${variantConfig.label} post-completion failed [${shortId(jobId)}]: ${err?.message}`);
});
},
onFailed: (job) => {
detach();
// Release the slot so a retry render doesn't get superseded by this dead one.
- releasePendingSheetSlot(universeId, entryId, jobId);
- console.log(`⚠️ Character sheet render ${job.status} [${shortId(jobId)}]: ${job.error || 'unknown'}`);
+ releasePendingSheetSlot(universeId, entryId, jobId, variant);
+ console.log(`⚠️ ${variantConfig.label} render ${job.status} [${shortId(jobId)}]: ${job.error || 'unknown'}`);
},
});
armTimeout(QUEUE_WAIT_MS, 'queue-wait timeout');
@@ -371,13 +561,17 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// Deterministic destination filename — uses the queue's jobId so the client
// can patch optimistically on SSE completion without a universe refetch.
// onSheetComplete derives the same filename from the same inputs.
- const destFilename = sheetFilename(universeId, entryId, jobId);
- console.log(`🎨 Universe character sheet render — universe=${shortId(universeId)} entry=${shortId(entryId)} job=${shortId(jobId)} mode=${activeMode} model=${modelId} position=${queued.position}`);
+ const destFilename = sheetFilename(universeId, entryId, jobId, variantConfig.filenameToken);
+ console.log(`🎨 ${variantConfig.label} render — universe=${shortId(universeId)} entry=${shortId(entryId)} job=${shortId(jobId)} mode=${activeMode} model=${modelId} position=${queued.position}`);
return {
jobId,
// `generationId` retained for client back-compat (older clients keyed
// SSE attachment on this name); it's now an alias for `jobId`.
generationId: jobId,
+ // Echo the resolved variant so the client can route the post-render
+ // callback to the right `referenceSheets[<id>]` slot without parsing the
+ // filename. Always set, even for the legacy 'standard' variant.
+ variant: variantConfig.id,
queuePosition: queued.position,
destFilename,
destPath: `/data/image-refs/${destFilename}`,
@@ -385,42 +579,43 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
};
}
-export async function onSheetComplete({ universeId, entryId, jobId, sourceFilename }) {
+export async function onSheetComplete({ universeId, entryId, jobId, sourceFilename, variant = LEGACY_SHEET_VARIANT_ID }) {
if (!sourceFilename) return null;
+ const variantConfig = getVariantConfig(variant);
await ensureDir(PATHS.imageRefs);
- const destFilename = sheetFilename(universeId, entryId, jobId);
+ const destFilename = sheetFilename(universeId, entryId, jobId, variantConfig.filenameToken);
const srcPath = join(PATHS.images, basename(sourceFilename));
const destPath = join(PATHS.imageRefs, destFilename);
// ALWAYS copy the file — even superseded renders are kept on disk for
- // rollback/comparison (they live at `data/image-refs/<...>-sheet-<job>.png`
+ // rollback/comparison (they live at `data/image-refs/<...>-<token>-<job>.png`
// with a unique per-job filename).
await copyFile(srcPath, destPath);
- console.log(`📸 Character sheet copied to image-refs: ${destFilename}`);
-
- // If a newer render has been started for this character while ours was in
- // flight (OR the character was deleted, which clears the slot), the slot
- // no longer holds our jobId. Skip the stamp — the newer render will stamp
- // its own filename when it finishes, and a deleted character would
- // re-introduce an orphaned pointer. Without this, an older-but-slower
- // render could overwrite a newer-but-finished pointer.
- if (getPendingSheetSlot(universeId, entryId) !== jobId) {
- console.log(`⏭️ Character sheet [${shortId(jobId)}] superseded by newer render — file saved, pointer not stamped`);
+ console.log(`📸 ${variantConfig.label} copied to image-refs: ${destFilename}`);
+
+ // If a newer render has been started for this character+variant while ours
+ // was in flight (OR the character was deleted, which clears all variants'
+ // slots), the slot no longer holds our jobId. Skip the stamp — the newer
+ // render will stamp its own filename when it finishes, and a deleted
+ // character would re-introduce an orphaned pointer. Without this, an
+ // older-but-slower render could overwrite a newer-but-finished pointer.
+ if (getPendingSheetSlot(universeId, entryId, variant) !== jobId) {
+ console.log(`⏭️ ${variantConfig.label} [${shortId(jobId)}] superseded by newer render — file saved, pointer not stamped`);
return { filename: destFilename, path: destPath, superseded: true };
}
- // Stamp ONLY `referenceSheetImageRef` inside the write queue against the
- // freshest persisted universe so a concurrent user edit (or sibling render
- // landing close in time) can't clobber unrelated character fields. The
- // sheet lives in data/image-refs/, distinct from `imageRefs[]` (gallery,
- // /data/images/) — polluting imageRefs would 404 the CanonCard thumbnail.
+ // Stamp ONLY the variant's pointer (legacy field OR `referenceSheets` map
+ // slot) inside the write queue against the freshest persisted universe so
+ // a concurrent user edit (or sibling render landing close in time) can't
+ // clobber unrelated character fields. The sheet file lives in
+ // data/image-refs/, distinct from `imageRefs[]` (gallery, /data/images/) —
+ // polluting imageRefs would 404 the CanonCard thumbnail.
let stamped = false;
await updateUniverse(universeId, (latest) => {
const latestList = Array.isArray(latest.characters) ? latest.characters : [];
const latestIdx = latestList.findIndex((c) => c.id === entryId);
if (latestIdx < 0) return null;
- const nextList = latestList.map((e, i) => (i === latestIdx ? {
- ...e,
- referenceSheetImageRef: destFilename,
- } : e));
+ const nextList = latestList.map((e, i) => (
+ i === latestIdx ? applySheetPointerToCharacter(e, variant, destFilename) : e
+ ));
stamped = true;
return { characters: nextList };
});
@@ -432,27 +627,31 @@ export async function onSheetComplete({ universeId, entryId, jobId, sourceFilena
// and skip its own stamp — leaving the older filename persisted. A
// failed stamp leaves the slot owned by us so the next render-start
// cleanly overwrites it.
- releasePendingSheetSlot(universeId, entryId, jobId);
+ releasePendingSheetSlot(universeId, entryId, jobId, variant);
if (!stamped) {
- console.log(`⚠️ Character ${entryId} not found post-render — sheet saved but not linked`);
+ console.log(`⚠️ Character ${entryId} not found post-render — ${variantConfig.label.toLowerCase()} saved but not linked`);
return null;
}
- console.log(`📌 Character ${shortId(entryId)}.referenceSheetImageRef = ${destFilename}`);
- return { filename: destFilename, path: destPath };
+ console.log(`📌 Character ${shortId(entryId)} [${variant}] = ${destFilename}`);
+ return { filename: destFilename, path: destPath, variant };
}
/**
- * Delete the character's current reference sheet — unlinks the file from
- * `PATHS.imageRefs` and clears `referenceSheetImageRef` on every matching
- * character via `purgeReferenceSheetFromAllUniverses`. Returns
+ * Delete a character's reference sheet of the given variant — unlinks the
+ * file from `PATHS.imageRefs` and clears the variant's pointer (legacy field
+ * OR `referenceSheets` map slot) on every matching character. Returns
* `{ filename, fileDeleted, cleared }`; a missing file is not an error
* (the lazy `pruneStaleReferenceSheets` may have already nulled the pointer
* out-of-band) — `fileDeleted: false` distinguishes that case.
*
* Mirrors the renderer's lock check so a locked character's sheet stays
* delete-protected alongside its other AI-managed fields.
+ *
+ * `variant` defaults to 'standard' so the existing route + client callers
+ * stay unchanged.
*/
-export async function deleteCharacterReferenceSheet(universeId, entryId) {
+export async function deleteCharacterReferenceSheet(universeId, entryId, { variant = LEGACY_SHEET_VARIANT_ID } = {}) {
+ const variantConfig = getVariantConfig(variant);
const universe = await getUniverse(universeId);
const list = Array.isArray(universe.characters) ? universe.characters : [];
const character = list.find((c) => c.id === entryId);
@@ -467,7 +666,7 @@ export async function deleteCharacterReferenceSheet(universeId, entryId) {
{ status: 409, code: 'UNIVERSE_CANON_LOCKED' },
);
}
- const filename = character.referenceSheetImageRef;
+ const filename = readSheetPointer(character, variant);
if (!filename) {
return { filename: null, fileDeleted: false, cleared: 0 };
}
@@ -486,7 +685,7 @@ export async function deleteCharacterReferenceSheet(universeId, entryId) {
throw err;
});
const { cleared } = await purgeReferenceSheetFromAllUniverses(filename);
- console.log(`🗑️ Deleted character sheet ${filename} (file=${fileDeleted}, pointers cleared=${cleared})`);
+ console.log(`🗑️ Deleted ${variantConfig.label.toLowerCase()} ${filename} (file=${fileDeleted}, pointers cleared=${cleared})`);
return { filename, fileDeleted, cleared };
}
diff --git a/server/services/universeCharacterSheet.test.js b/server/services/universeCharacterSheet.test.js
index 1e4d173a1d..64806562c8 100644
--- a/server/services/universeCharacterSheet.test.js
+++ b/server/services/universeCharacterSheet.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildCharacterReferenceSheetPrompt, REFERENCE_SHEET_CONSTANTS, resolveSheetModelId } from './universeCharacterSheet.js';
+import { buildCharacterReferenceSheetPrompt, REFERENCE_SHEET_CONSTANTS, resolveSheetModelId, listSheetVariants } from './universeCharacterSheet.js';
const baseUniverse = {
id: 'u-123',
@@ -196,3 +196,32 @@ describe('universeCharacterSheet — resolveSheetModelId', () => {
expect(out).toBeNull();
});
});
+
+describe('universeCharacterSheet — variant catalog + prototype-pollution guard', () => {
+ // Renderer/delete read the registry by string key. Without an own-property
+ // check, an attacker can send `variant=constructor` (or any Object.prototype
+ // member) through the route's `.string().min(1).max(48)` schema — bracket
+ // access returns Object.prototype.constructor and the renderer crashes 500.
+ // Verify the registry lookup rejects every Object.prototype name.
+ it('listSheetVariants exposes the two registered variants', () => {
+ const variants = listSheetVariants();
+ const ids = variants.map((v) => v.id);
+ expect(ids).toContain('standard');
+ expect(ids).toContain('blueprint');
+ for (const v of variants) {
+ expect(v).toHaveProperty('label');
+ expect(v).toHaveProperty('description');
+ }
+ });
+
+ it('renderCharacterReferenceSheet rejects inherited Object.prototype member names with 400', async () => {
+ // Lazy import so we can call without setting up the full universe stack;
+ // the lookup error fires before any I/O.
+ const { renderCharacterReferenceSheet } = await import('./universeCharacterSheet.js');
+ for (const variant of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) {
+ await expect(
+ renderCharacterReferenceSheet('u-1', 'c-1', { variant }),
+ ).rejects.toMatchObject({ status: 400, code: 'VALIDATION_ERROR' });
+ }
+ });
+});
diff --git a/server/services/universeCharacterSheetSlot.js b/server/services/universeCharacterSheetSlot.js
index cd9f06fc8e..8552409535 100644
--- a/server/services/universeCharacterSheetSlot.js
+++ b/server/services/universeCharacterSheetSlot.js
@@ -1,39 +1,54 @@
/**
* Character reference-sheet "latest pending render" slot map.
- * `${universeId}:${characterId} → jobId` of the most recently started
- * render; supersede-aware stamping in onSheetComplete relies on slot
- * identity. Extracted from universeCharacterSheet.js so universeBuilder.js
- * can clear slots on delete without an import cycle.
+ * `${universeId}:${characterId}:${variant} → jobId` of the most recently
+ * started render. The variant key isolates parallel renders on the same
+ * character so a standard-style render and a blueprint-style render can't
+ * supersede each other. Extracted from universeCharacterSheet.js so
+ * universeBuilder.js can clear slots on delete without an import cycle.
*/
+import { LEGACY_SHEET_VARIANT_ID } from '../lib/storyBible.js';
+
const _latestPendingByCharacter = new Map();
-const pendingKey = (universeId, characterId) => `${universeId}:${characterId}`;
+const pendingKey = (universeId, characterId, variant) =>
+ `${universeId}:${characterId}:${variant || LEGACY_SHEET_VARIANT_ID}`;
-export function claimPendingSheetSlot(universeId, characterId, jobId) {
- _latestPendingByCharacter.set(pendingKey(universeId, characterId), jobId);
+export function claimPendingSheetSlot(universeId, characterId, jobId, variant = LEGACY_SHEET_VARIANT_ID) {
+ _latestPendingByCharacter.set(pendingKey(universeId, characterId, variant), jobId);
}
-export function getPendingSheetSlot(universeId, characterId) {
- return _latestPendingByCharacter.get(pendingKey(universeId, characterId));
+export function getPendingSheetSlot(universeId, characterId, variant = LEGACY_SHEET_VARIANT_ID) {
+ return _latestPendingByCharacter.get(pendingKey(universeId, characterId, variant));
}
// Conditional release — only deletes when the slot still belongs to the
// caller's jobId. Used by render-completion / render-failure paths where a
// newer render may have already claimed the slot in parallel.
-export function releasePendingSheetSlot(universeId, characterId, jobId) {
- const key = pendingKey(universeId, characterId);
+export function releasePendingSheetSlot(universeId, characterId, jobId, variant = LEGACY_SHEET_VARIANT_ID) {
+ const key = pendingKey(universeId, characterId, variant);
if (_latestPendingByCharacter.get(key) === jobId) {
_latestPendingByCharacter.delete(key);
}
}
// Unconditional release for a single character — used by delete paths where
-// the character is going away regardless of what render is in flight. Any
-// pending render's onSheetComplete will see the empty slot, treat itself as
+// the character is going away regardless of what render is in flight. Clears
+// ALL variants in one call so a character delete doesn't leak blueprint
+// slots when only the standard one was tracked, and vice versa. Any pending
+// render's onSheetComplete will see the empty slot, treat itself as
// superseded, and skip stamping a now-orphaned pointer.
export function clearPendingSheetSlot(universeId, characterId) {
- return _latestPendingByCharacter.delete(pendingKey(universeId, characterId));
+ if (!universeId || !characterId) return false;
+ const prefix = `${universeId}:${characterId}:`;
+ let cleared = false;
+ for (const key of _latestPendingByCharacter.keys()) {
+ if (key.startsWith(prefix)) {
+ _latestPendingByCharacter.delete(key);
+ cleared = true;
+ }
+ }
+ return cleared;
}
// Universe-wide release — used when an entire universe is deleted. Walks
diff --git a/server/services/universeCharacterSheetSlot.test.js b/server/services/universeCharacterSheetSlot.test.js
index 3c5d1cf903..d7afc9c664 100644
--- a/server/services/universeCharacterSheetSlot.test.js
+++ b/server/services/universeCharacterSheetSlot.test.js
@@ -58,6 +58,38 @@ describe('universeCharacterSheetSlot — clearPendingSheetSlot (per-character)',
it('is a no-op when the slot is already empty', () => {
expect(clearPendingSheetSlot('u-a', 'never-claimed')).toBe(false);
});
+
+ it('clears every variant for the character (deleting a character should drop both sheet renders)', () => {
+ claimPendingSheetSlot('u-a', 'char-1', 'job-std', 'standard');
+ claimPendingSheetSlot('u-a', 'char-1', 'job-bp', 'blueprint');
+ clearPendingSheetSlot('u-a', 'char-1');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'standard')).toBeUndefined();
+ expect(getPendingSheetSlot('u-a', 'char-1', 'blueprint')).toBeUndefined();
+ });
+});
+
+describe('universeCharacterSheetSlot — variant isolation', () => {
+ it('different variants on the same character are independent slots', () => {
+ claimPendingSheetSlot('u-a', 'char-1', 'job-std', 'standard');
+ claimPendingSheetSlot('u-a', 'char-1', 'job-bp', 'blueprint');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'standard')).toBe('job-std');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'blueprint')).toBe('job-bp');
+ });
+
+ it('releasing one variant does not touch the other', () => {
+ claimPendingSheetSlot('u-a', 'char-1', 'job-std', 'standard');
+ claimPendingSheetSlot('u-a', 'char-1', 'job-bp', 'blueprint');
+ releasePendingSheetSlot('u-a', 'char-1', 'job-std', 'standard');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'standard')).toBeUndefined();
+ expect(getPendingSheetSlot('u-a', 'char-1', 'blueprint')).toBe('job-bp');
+ });
+
+ it('variant defaults to standard for back-compat with single-variant callers', () => {
+ claimPendingSheetSlot('u-a', 'char-1', 'job-1');
+ expect(getPendingSheetSlot('u-a', 'char-1')).toBe('job-1');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'standard')).toBe('job-1');
+ expect(getPendingSheetSlot('u-a', 'char-1', 'blueprint')).toBeUndefined();
+ });
});
describe('universeCharacterSheetSlot — clearPendingSheetSlotsForUniverse', () => {