Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
resolve the record render-pin ladder for single-image renders
[._.]/ Adam Eivy06510ea55df3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e676bd9fdd..2e6ea807e0 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -49,6 +49,9 @@## Fixed+- **A universe's chosen render engine now governs its cast, place, and object renders — not just batch runs.** Setting "This universe's default" on the Render tab persisted the pin correctly, and batch renders and character reference sheets obeyed it, but rendering a single reference from a Cast (or Places/Objects) card went to whatever the install-wide default resolved to — Codex on any Codex-enabled install — because those rows built their request from global image-gen settings and sent an explicit backend, which outranks a record pin server-side. Every render a universe queues now resolves the same ladder the batch path already used: the universe's own pin, then the "Universe Bible & canon renders" pin under Settings → Image Gen, then the install default — with the pinned model routed to the knob that backend actually reads. That covers the canon rows, clean plates, the base-style probe, the Story Builder characters step, and the pipeline Nouns stage, which previously ignored both pins. A pin naming a backend the install has since disabled falls through to the next rung instead of queueing a doomed job. Renders that arrive with no backend at all — from the API or an agent — resolve the owning universe's pin server-side too, from a pin-only read rather than a full record load.+- **An unset seed no longer renders the same image every time.** Blank seed and guidance fields were coerced with `Number('')`, which is `0` rather than "absent", so single-image renders shipped a hard `seed: 0` that the local runner honors as a fixed seed — repeat renders of one prompt came back identical, and `guidance: 0` disabled CFG. Blank now means absent; an explicitly typed `0` is still sent.+- **Foundation structure repair now keeps the safest verified checkpoint, not merely the one with the fewest findings.** The bounded verifier loop ranked candidates by raw blocker count, so a live repair that eliminated every high-severity authorization and climax failure was discarded because its deeper pass surfaced six medium/low follow-ups while an earlier four-finding checkpoint still contained two highs. Checkpoints are now ordered lexicographically by high, medium, low, then total count: one unresolved high can never be hidden by any number of polish findings, while equal-severity sets still prefer the smaller residual. The retained-progress message reports the complete severity profile so a partial repair is auditable.- **The prompt-drift baseline caught up with the arc-resolve migration, un-reddening `main`.** Migration 254 shipped a new `pipeline-arc-resolve.md` and correctly recorded the prior default as an accepted-old hash, but the independent baseline in `scripts/setup-data-drift.test.js` still named the superseded hash as current — so the drift sweep disagreed with the migrations it mirrors and the suite failed on every commit after it landed. The baseline now carries the shipped hash and lists the previous one among the accepted-old set. The guard itself is unchanged and still fails when a migration ships a hash it doesn't export.diff --git a/client/src/components/pipeline/stages/NounsStage.jsx b/client/src/components/pipeline/stages/NounsStage.jsxindex e190b4445a..b37846d1e5 100644--- a/client/src/components/pipeline/stages/NounsStage.jsx+++ b/client/src/components/pipeline/stages/NounsStage.jsx@@ -42,7 +42,9 @@ import CanonCard from '../CanonCard';import MediaPreview from '../../media/MediaPreview';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';-import { deriveAvailableBackends } from '../../../lib/imageGenBackends';+import {+ applyRecordRenderPin, deriveAvailableBackends, renderTargetPin, RENDER_TARGET,+} from '../../../lib/imageGenBackends';import {PIPELINE_IMAGE_DEFAULTS,readPipelineImageSettings,@@ -142,10 +144,31 @@ export default function NounsStage({ issue, series, onStageUpdate }) {[sysSettings],);+ // Reference renders here are UNIVERSE canon renders (same records, same+ // `universeRun` tag as the Universe Builder's cast rows), so they resolve the+ // same render-pin ladder: the linked universe's pin, then the Universe Bible+ // `renderDefaults` pin, then this stage's saved config. `imageCfg` stays the+ // raw saved config so the settings drawer keeps editing the install-wide+ // default rather than a value the pin overrode. Backends pass as `null` until+ // settings land — `[]` means "loaded, nothing enabled" and would suppress the+ // pin entirely (see renderPinLadder).+ const renderCfg = useMemo(+ () => applyRecordRenderPin(+ imageCfg,+ [universe, renderTargetPin(sysSettings, RENDER_TARGET.UNIVERSE_BIBLE)],+ sysSettings ? availableBackends : null,+ ),+ [imageCfg, sysSettings, availableBackends, universe?.imageMode, universe?.imageModelId],+ );+useEffect(() => {let cancelled = false;Promise.all([- getSettings().catch(() => ({})),+ // `null` on failure, NOT `{}` — a `{}` stand-in derives an empty backend+ // list, which `renderPinLadder` reads as "loaded, nothing enabled" and+ // uses to suppress every pin. A settings fetch that failed must not look+ // like an install with no backends.+ getSettings().catch(() => null),listImageModels().catch(() => []),]).then(([s, modelList]) => {if (cancelled || !mountedRef.current) return;@@ -357,7 +380,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {toast.error(`Add a description before generating a reference for ${entry.name}`);return;}- const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const baseOpts = pipelineImageCfgToRenderOpts(renderCfg);// Inject the universe's stylePrompt as a prefix and merge negativePrompts so// ref images and comic pages share the same aesthetic (Codex doesn't// accept reference images, so style consistency comes from text alone).@@ -399,7 +422,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {toast.error(`Add a description, palette, or recurring details before generating a clean plate for ${entry.name}`);return;}- const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const baseOpts = pipelineImageCfgToRenderOpts(renderCfg);const plate = composeCleanPlatePrompt(entry, baseOpts.negativePrompt || '');const styled = composeStyledPrompt(plate.prompt,@@ -504,7 +527,7 @@ export default function NounsStage({ issue, series, onStageUpdate }) {type="button"onClick={openSettings}className="inline-flex items-center gap-1 px-2 py-1.5 rounded-lg bg-port-card border border-port-border text-gray-300 text-xs hover:border-port-accent/50 hover:text-white"- title={`Reference image gen settings — backend: ${imageCfg.mode}`}+ title={`Reference image gen settings — backend: ${renderCfg.mode}${renderCfg.mode === imageCfg.mode ? '' : ' (pinned by the linked universe)'}`}><SettingsIcon size={12} /> Image gen</button>diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsxindex aa73cb1fef..5e20b4570c 100644--- a/client/src/components/settings/ImageGenTab.test.jsx+++ b/client/src/components/settings/ImageGenTab.test.jsx@@ -263,7 +263,7 @@ describe('ImageGenTab — Agy CLI section', () => {});await renderTab(['/media/image?mediaTab=defaults']);// Existing pin loads into its select.- const bibleSelect = await screen.findByLabelText('Universe Bible batch renders');+ const bibleSelect = await screen.findByLabelText('Universe Bible & canon renders');expect(bibleSelect.value).toBe('codex');// Pin a model-capable backend on another surface → model input appears.const spriteSelect = screen.getByLabelText('Sprite references & anchors');diff --git a/client/src/components/universe/StyleProbeImage.jsx b/client/src/components/universe/StyleProbeImage.jsxindex f72cc6218b..be5882df6f 100644--- a/client/src/components/universe/StyleProbeImage.jsx+++ b/client/src/components/universe/StyleProbeImage.jsx@@ -20,6 +20,7 @@ import { useRef } from 'react';import { Sparkles } from 'lucide-react';import { updateUniverse } from '../../services/api';import { universeStylePreset } from '../../lib/universeStylePreset';+import { RENDER_TARGET } from '../../lib/imageGenBackends';import useImageRenderSettings from '../../hooks/useImageRenderSettings';import useSingleImageRender from '../../hooks/useSingleImageRender';import EntryThumbSlot from './EntryThumbSlot';@@ -61,7 +62,8 @@ export const shouldPersistProbe = ({ styleDirty, capturedKey, currentKey }) =>!styleDirty && capturedKey !== null && currentKey === capturedKey;export default function StyleProbeImage({ universe, onUniverseChange, canRender = true, styleDirty = false, onPreview = null, onRenderComplete = null }) {- const { imageCfg } = useImageRenderSettings();+ // A universe render, so it resolves the universe's pin ladder (see renderPinLadder).+ const { imageCfg } = useImageRenderSettings({ record: universe, target: RENDER_TARGET.UNIVERSE_BIBLE });// The style key the in-flight probe was queued against, captured at render// time so the async completion can detect mid-render style drift. Keyed by// universe so this component can stay mounted across a universe switch (nodiff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsxindex 887a3d2e30..38c6fec69c 100644--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx@@ -111,9 +111,9 @@ export default function UniverseBuilder() {availableBackends,availableLoras,clearPendingCanonAdditions,- defaultMode,draft,draftRef,+ effectiveDefaultMode,flushDraftIfDirty,handleCanonChange,handleCreateNamed,@@ -151,17 +151,6 @@ export default function UniverseBuilder() {updateCompositeSheets,updateDraft,} = useUniverseDraft({ selectedId, goToWorld });- // Universe render pin (#3231 Phase 3): the record's pinned backend becomes- // the page's default mode when that backend is available, so an untouched- // batch form actually renders on the pin (the client always sends an- // explicit body.mode once settings load — without this, the pin would only- // ever apply to mode-less API callers). An explicit renderOpts.mode still- // wins, and an unavailable pinned backend degrades to the install default- // (mirroring the server ladder's usability gate).- const effectiveDefaultMode = draft?.imageMode- && availableBackends.some((b) => b.id === draft.imageMode)- ? draft.imageMode- : defaultMode;const {canRender,clearPendingForEntry,diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 5789a0c704..ba670fcecd 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -66,7 +66,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useClonedGltf` | Clones a drei-cached GLTF scene with skeleton bindings intact and wires its animations; the colocated `GltfPrimitive` prevents R3F from disposing shared cache resources. Accepts an optional animation transform for derived clip sets. | Any skinned GLTF rendered from `useGLTF`; render its scene through `GltfPrimitive` so remounts cannot inherit disposed geometry or materials. || `usePreviewRoute` | URL-driven `[preview, setPreview]` via `?preview=<filename>`. | Any page hosting `<MediaPreview>` — gives the preview a deep-link. || `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. |-| `useImageRenderSettings` | Load the pipeline image-gen config once (`getSettings → readPipelineImageSettings`), failing open to `PIPELINE_IMAGE_DEFAULTS`; returns `{ imageCfg }`. | A single-image render slot that needs the render config and doesn't already load the full settings blob. |+| `useImageRenderSettings` | Load the pipeline image-gen config once (`getSettings → readPipelineImageSettings`), failing open to `PIPELINE_IMAGE_DEFAULTS`; takes `{ record }` to fold that record's `imageMode`/`imageModelId` pin over the install default; returns `{ imageCfg, availableBackends }`. | A single-image render slot that needs the render config and doesn't already load the full settings blob. Pass `record` whenever the render belongs to a pinnable record (universe, series, sprite). || `useUserTimezone` | Resolve the user's configured IANA timezone (`settings.timezone`) once, falling back to the browser zone then UTC; returns the tz string. | A date-scoped surface that must derive "today" the same way the server does (POST launcher/history day keys, #2681). || `useSingleImageRender` | Queue-one-render / wait-for-completion jobId lifecycle: builds opts from `imageCfg`, calls `buildPrompt`, POSTs `generateImage`, tracks the `jobId` head, and runs a once-per-`(key, filename)` completion guard before `onComplete`. | Single-image render slots driven by `EntryThumbSlot`/`MediaJobThumb` (style probe, characters step). Completion SSE stays in the thumb. |diff --git a/client/src/hooks/useImageRenderSettings.js b/client/src/hooks/useImageRenderSettings.jsindex 72e4d714c3..20fcce0c11 100644--- a/client/src/hooks/useImageRenderSettings.js+++ b/client/src/hooks/useImageRenderSettings.js@@ -1,6 +1,9 @@-import { useState, useEffect } from 'react';+import { useState, useEffect, useMemo } from 'react';import { getSettings } from '../services/api';import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';+import {+ applyRecordRenderPin, deriveAvailableBackends, renderTargetPin,+} from '../lib/imageGenBackends';/*** Load the pipeline image-gen render config once on mount and expose it as a@@ -14,16 +17,36 @@ import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipel* the Universe Builder reads loras + models from the same fetch) should keep* deriving `imageCfg` from that shared fetch rather than double-fetching here.*+ * Pass `record` + `target` to resolve the render-pin ladder over the install+ * default — see `renderPinLadder` for why the client has to do this at all.+ *+ * @param {object} [opts]+ * @param {object|null} [opts.record] - Record whose `imageMode`/`imageModelId` pin wins.+ * @param {string|null} [opts.target] - RENDER_TARGET id whose `renderDefaults` pin is next.* @returns {{ imageCfg: object }}*/-export default function useImageRenderSettings() {- const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);+export default function useImageRenderSettings({ record = null, target = null } = {}) {+ // `null` = not fetched yet (or the fetch failed), which is NOT the same as a+ // settings blob with no backends enabled — an empty backend list suppresses+ // every pin, so collapsing the two would silently drop the record's pin+ // whenever /api/settings is slow or down.+ const [settings, setSettings] = useState(null);useEffect(() => {- getSettings({ silent: true })- .then((s) => setImageCfg(readPipelineImageSettings(s)))- .catch(() => {});+ getSettings({ silent: true }).then(setSettings).catch(() => {});}, []);- return { imageCfg };+ // Depend on the pin fields rather than the record identity — callers hand us+ // a freshly-fetched draft object on every save, and re-deriving an identical+ // cfg would churn the render opts for every consumer downstream.+ return useMemo(() => {+ if (!settings) return { imageCfg: PIPELINE_IMAGE_DEFAULTS };+ return {+ imageCfg: applyRecordRenderPin(+ readPipelineImageSettings(settings),+ [record, renderTargetPin(settings, target)],+ deriveAvailableBackends(settings, { excludeExternal: true }),+ ),+ };+ }, [settings, target, record?.imageMode, record?.imageModelId]);}diff --git a/client/src/hooks/useImageRenderSettings.test.jsx b/client/src/hooks/useImageRenderSettings.test.jsxindex 13c2a53f1b..11774c9aa4 100644--- a/client/src/hooks/useImageRenderSettings.test.jsx+++ b/client/src/hooks/useImageRenderSettings.test.jsx@@ -35,4 +35,38 @@ describe('useImageRenderSettings', () => {await waitFor(() => expect(getSettings).toHaveBeenCalled());expect(result.current.imageCfg).toEqual(PIPELINE_IMAGE_DEFAULTS);});++ // Wiring only — the ladder's own matrix is covered by `renderPinLadder`'s+ // unit tests. Codex + agy both enabled means `readPipelineImageSettings`+ // picks codex, so an agy result can only have come from a pin.+ describe('render pin ladder', () => {+ const CLOUD_ON = { codex: { enabled: true }, agy: { enabled: true } };++ it('resolves the record pin, then the target pin, then the install default', async () => {+ getSettings.mockResolvedValue({ imageGen: CLOUD_ON });+ const { result, rerender } = renderHook(+ (props) => useImageRenderSettings(props),+ { initialProps: { record: { imageMode: 'agy' }, target: 'universe-bible' } },+ );+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('agy'));++ getSettings.mockResolvedValue({+ imageGen: CLOUD_ON, renderDefaults: { 'universe-bible': { imageMode: 'agy' } },+ });+ const target = renderHook(() => useImageRenderSettings({ record: {}, target: 'universe-bible' }));+ await waitFor(() => expect(target.result.current.imageCfg.mode).toBe('agy'));++ rerender({ record: {}, target: 'universe-bible' });+ expect(result.current.imageCfg.mode).toBe('codex');+ });++ it('keeps the pin when the settings fetch fails rather than suppressing it', async () => {+ // `[]` backends would gate every pin away; the hook must not conflate+ // "settings not loaded" with "no backend enabled".+ getSettings.mockRejectedValue(new Error('offline'));+ const { result } = renderHook(() => useImageRenderSettings({ record: { imageMode: 'agy' } }));+ await waitFor(() => expect(getSettings).toHaveBeenCalled());+ expect(result.current.imageCfg).toEqual(PIPELINE_IMAGE_DEFAULTS);+ });+ });});diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.jsindex a81630883a..fb348f10b9 100644--- a/client/src/hooks/useUniverseDraft.js+++ b/client/src/hooks/useUniverseDraft.js@@ -17,7 +17,10 @@ import {WORLD_LOCKABLE_FIELDS,ensureInfluences,} from '../services/api';-import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';+import {+ applyRecordRenderPin, deriveAvailableBackends, renderPinLadder, renderTargetPin,+ IMAGE_GEN_MODE, RENDER_TARGET,+} from '../lib/imageGenBackends';import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings } from '../lib/pipelineImageDefaults';import { sameJsonShape } from '../lib/sameJsonShape';import { upsertByIdPrepend } from '../lib/upsertByIdPrepend';@@ -87,7 +90,11 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {const [availableLoras, setAvailableLoras] = useState([]);const [availableBackends, setAvailableBackends] = useState([]);const [defaultMode, setDefaultMode] = useState(null);- const [imageCfg, setImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);+ const [settingsImageCfg, setSettingsImageCfg] = useState(PIPELINE_IMAGE_DEFAULTS);+ // The Universe Bible target's own `settings.renderDefaults` pin — the rung+ // between this universe's pin and the install default. Held as the normalized+ // pin rather than the whole settings blob so the memo below has a stable dep.+ const [targetPin, setTargetPin] = useState(null);const [draft, setDraft] = useState(createEmptyUniverseDraft);const [runs, setRuns] = useState([]);const [pendingDeleteId, setPendingDeleteId] = useState(null);@@ -198,7 +205,8 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {setAvailableBackends(backends);const saved = settings?.imageGen?.mode;setDefaultMode(backends.find((backend) => backend.id === saved)?.id || backends[0]?.id || IMAGE_GEN_MODE.LOCAL);- setImageCfg(readPipelineImageSettings(settings));+ setSettingsImageCfg(readPipelineImageSettings(settings));+ setTargetPin(renderTargetPin(settings, RENDER_TARGET.UNIVERSE_BIBLE));}setLoading(false);};@@ -653,6 +661,25 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {savedStyleSnapshotRef.current,ensureInfluences(draft.influences),);+ // The render-pin ladder's inputs (see `renderPinLadder`), resolved here at the+ // source — this hook owns every rung — rather than at each consumer, so a new+ // render affordance on this page inherits the pin instead of re-introducing+ // the bug. `targetPin` doubles as the "settings loaded" sentinel: it is only+ // ever set from a successful read, and the backend list must be passed as+ // `null` (not the initial `[]`, which reads as "loaded, nothing enabled" and+ // would suppress every pin) until then.+ const pinSources = [draft, targetPin];+ const pinBackends = targetPin ? availableBackends : null;+ // What every SINGLE-image render on this page uses: cast / places / objects+ // reference renders and clean plates.+ const imageCfg = useMemo(+ () => applyRecordRenderPin(settingsImageCfg, pinSources, pinBackends),+ [settingsImageCfg, targetPin, draft.imageMode, draft.imageModelId, availableBackends],+ );+ // The same ladder for the BATCH form's default mode. The client always sends+ // an explicit body.mode once settings load, so without resolving it here the+ // pins would only ever apply to mode-less API callers.+ const effectiveDefaultMode = renderPinLadder(pinSources, pinBackends).mode || defaultMode;return {activeProviderId,@@ -665,6 +692,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {defaultMode,draft,draftRef,+ effectiveDefaultMode,flushDraftIfDirty,handleCanonChange,handleCreateNamed,diff --git a/client/src/hooks/useUniverseDraft.test.jsx b/client/src/hooks/useUniverseDraft.test.jsxindex 701e94402b..546e4b27ac 100644--- a/client/src/hooks/useUniverseDraft.test.jsx+++ b/client/src/hooks/useUniverseDraft.test.jsx@@ -1264,3 +1264,65 @@ describe('useUniverseDraft', () => {});});});++// The universe's own backend pin (Render tab → "This universe's default") has to+// reach the per-entry render config, not just the batch form: the cast / places /+// objects rows POST `/api/image-gen/generate` with an EXPLICIT `mode` taken from+// `imageCfg`, and an explicit mode outranks the record pin on the server ladder.+// Before this, an agy-pinned universe rendered its cast on the install default.+describe('imageCfg — universe render pin', () => {+ const CLOUD_ON = { codex: { enabled: true }, agy: { enabled: true } };++ it('folds the universe pin over the install-wide settings default', async () => {+ apiMocks.getSettings.mockResolvedValue({ imageGen: CLOUD_ON });+ apiMocks.listUniverses.mockResolvedValue([{ ...universe, imageMode: 'agy' }]);+ apiMocks.getUniverse.mockResolvedValue({ ...universe, imageMode: 'agy' });+ const { result } = renderDraft();+ // readPipelineImageSettings prefers codex when it's enabled, so 'agy' can+ // only come from the record pin.+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('agy'));+ });++ it('keeps the install-wide default for an unpinned universe', async () => {+ apiMocks.getSettings.mockResolvedValue({ imageGen: CLOUD_ON });+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.imageCfg.mode).toBe('codex');+ });++ // The batch form's default mode and the per-entry cfg must agree — they are+ // the same ladder, and a page that renders its cast on agy while its batch+ // form says codex is the inconsistency this whole change is about.+ it('resolves the batch form default mode through the same ladder', async () => {+ apiMocks.getSettings.mockResolvedValue({ imageGen: { mode: 'codex', ...CLOUD_ON } });+ apiMocks.listUniverses.mockResolvedValue([{ ...universe, imageMode: 'agy' }]);+ apiMocks.getUniverse.mockResolvedValue({ ...universe, imageMode: 'agy' });+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.effectiveDefaultMode).toBe('agy'));+ expect(result.current.imageCfg.mode).toBe('agy');+ });++ it('ignores a pin whose backend this install no longer has enabled', async () => {+ apiMocks.getSettings.mockResolvedValue({ imageGen: { codex: { enabled: true } } });+ apiMocks.listUniverses.mockResolvedValue([{ ...universe, imageMode: 'agy' }]);+ apiMocks.getUniverse.mockResolvedValue({ ...universe, imageMode: 'agy' });+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(result.current.imageCfg.mode).toBe('codex');+ });++ // The rung between the record pin and the install default. Batch renders and+ // character sheets already resolved it server-side, so omitting it here made+ // two surfaces on one page disagree about the backend.+ it("falls through an unpinned universe to the Universe Bible renderDefaults pin", async () => {+ apiMocks.getSettings.mockResolvedValue({+ imageGen: CLOUD_ON,+ renderDefaults: { 'universe-bible': { imageMode: 'agy', imageModel: 'gemini-3.5-pro' } },+ });+ const { result } = renderDraft();+ await waitFor(() => expect(result.current.imageCfg.mode).toBe('agy'));+ expect(result.current.imageCfg.cloudModel).toBe('gemini-3.5-pro');+ // The batch form's default mode runs the same ladder.+ expect(result.current.effectiveDefaultMode).toBe('agy');+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b7662a5425..35c2a8db7d 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -57,7 +57,7 @@ grep -i "what you want to do" client/src/lib/README.md| `reverseOutlineGrid.js` | `buildPlotlineGrid` (reverse-outline scenes + plotlines → plotline-by-sequence grid rows/cells) + `sceneComponentCount`. Used by the Reverse Outline page. || `wrImageDefaults.js` | Writers Room per-scene image-gen defaults + style discriminators. || `imageGenBackends.js` | Icon metadata + `deriveAvailableBackends` for the image-gen backends; re-exports everything from `imageGenModes.js` so consumers keep one import site. |-| `imageGenModes.js` | Node-safe (dependency-free) image/video backend constants + pure helpers: `IMAGE_GEN_MODE`, render-target mirror (`RENDER_TARGET_OPTIONS`, `normalizeRenderPinValue`), `VIDEO_RENDER_MODES`, `modeLabel`, cloud/model-override/i2i capability gating. Imported by the server-side parity suite — must stay importable without client packages. |+| `imageGenModes.js` | Node-safe (dependency-free) image/video backend constants + pure helpers: `IMAGE_GEN_MODE`, render-target mirror (`RENDER_TARGET_OPTIONS`, `normalizeRenderPinValue`, `applyRecordRenderPin` — fold a record's `imageMode`/`imageModelId` pin over a settings-derived cfg), `VIDEO_RENDER_MODES`, `modeLabel`, cloud/model-override/i2i capability gating. Imported by the server-side parity suite — must stay importable without client packages. || `imageGenDefaults.js` | Shared `DEFAULT_NEGATIVE_PROMPT` used by the Image Gen form and quick-submit entry points. Mirrors server-side default. || `imageGenResolutions.js` | Shared resolution presets for image generation. || `imageTo3dReasons.js` | Client mirror of the image-to-3D unavailable-reason labels in `server/services/imageTo3d/targets.js`: `UNAVAILABLE_REASONS` (reason code → user-facing label), `UNAVAILABLE_REASON_FALLBACK`, and `unavailableReasonLabel(code, fallback?)`. Use this anywhere a target's `unavailableReason` is rendered — never re-declare the codes. Parity + code coverage enforced by `server/services/imageTo3d/unavailableReasons.parity.test.js`. |diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.jsindex 5a6c066512..04b7bea3cb 100644--- a/client/src/lib/imageGenBackends.test.js+++ b/client/src/lib/imageGenBackends.test.js@@ -9,6 +9,9 @@ import {referenceSlotsFor,supportsReferenceStrength,deriveAvailableBackends,+ applyRecordRenderPin,+ renderPinLadder,+ renderTargetPin,} from './imageGenBackends';describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {@@ -104,3 +107,85 @@ describe('deriveAvailableBackends', () => {expect(deriveAvailableBackends(undefined)).toEqual([]);});});++describe('renderPinLadder', () => {+ const backends = [+ { id: IMAGE_GEN_MODE.LOCAL }, { id: IMAGE_GEN_MODE.CODEX }, { id: IMAGE_GEN_MODE.AGY },+ ];+ const record = (imageMode, imageModelId = null) => ({ imageMode, imageModelId });++ it('reports no pin when every source is empty', () => {+ expect(renderPinLadder([null, {}, record(null)])).toEqual({ mode: null, modelId: null });+ // 'auto' is the "no pin" sentinel, same as the server's normalizer.+ expect(renderPinLadder([record('auto')])).toEqual({ mode: null, modelId: null });+ });++ it('takes the highest-priority source that carries a pin', () => {+ expect(renderPinLadder([record(null), record('agy', 'm')], backends))+ .toEqual({ mode: IMAGE_GEN_MODE.AGY, modelId: 'm' });+ expect(renderPinLadder([record('codex'), record('agy')], backends).mode)+ .toBe(IMAGE_GEN_MODE.CODEX);+ });++ it('falls THROUGH a pin whose backend is not enabled, rather than giving up', () => {+ // The old behavior returned "no pin" here, so a stale record pin also+ // suppressed the target pin sitting below it.+ expect(renderPinLadder([record('grok'), record('agy')], backends).mode)+ .toBe(IMAGE_GEN_MODE.AGY);+ // A null backend list skips the usability gate entirely.+ expect(renderPinLadder([record('grok')], null).mode).toBe(IMAGE_GEN_MODE.GROK);+ // `[]` is "loaded, nothing enabled" — a real gate, not "unknown".+ expect(renderPinLadder([record('agy')], []).mode).toBeNull();+ });+});++describe('renderTargetPin', () => {+ it("re-keys settings.renderDefaults[target] to the flat record-pin shape", () => {+ const settings = { renderDefaults: { 'universe-bible': { imageMode: 'agy', imageModel: 'm' } } };+ expect(renderTargetPin(settings, 'universe-bible')).toEqual({ imageMode: 'agy', imageModelId: 'm' });+ expect(renderTargetPin(settings, 'music-video')).toEqual({ imageMode: null, imageModelId: null });+ expect(renderTargetPin(undefined, 'universe-bible')).toEqual({ imageMode: null, imageModelId: null });+ });+});++describe('applyRecordRenderPin', () => {+ const backends = [+ { id: IMAGE_GEN_MODE.LOCAL }, { id: IMAGE_GEN_MODE.CODEX }, { id: IMAGE_GEN_MODE.AGY },+ ];+ const cfg = { mode: IMAGE_GEN_MODE.CODEX, modelId: 'flux2-klein-4b', width: 1024 };++ it('returns the cfg BY IDENTITY when no pin applies', () => {+ // Identity matters: this cfg is a prop, so a fresh object every render+ // would churn every consumer for the common unpinned case.+ expect(applyRecordRenderPin(cfg, [null, {}], backends)).toBe(cfg);+ });++ it('overrides the settings-derived mode and keeps the untouched knobs', () => {+ const out = applyRecordRenderPin(cfg, [{ imageMode: 'agy' }], backends);+ expect(out.mode).toBe(IMAGE_GEN_MODE.AGY);+ expect(out.width).toBe(1024);+ });++ it('routes the pinned model to modelId for local and cloudModel for a cloud CLI', () => {+ const local = applyRecordRenderPin(cfg, [{ imageMode: 'local', imageModelId: 'flux-1' }], backends);+ expect(local.modelId).toBe('flux-1');+ expect(local.cloudModel).toBeNull();++ const cloud = applyRecordRenderPin(cfg, [{ imageMode: 'agy', imageModelId: 'gemini-3.5-pro' }], backends);+ expect(cloud.cloudModel).toBe('gemini-3.5-pro');+ // The settings-derived LOCAL model must not leak into a cloud render.+ expect(cloud.modelId).toBeNull();+ });++ it('drops a pinned model for a cloud CLI with no model knob (grok)', () => {+ const out = applyRecordRenderPin(cfg, [{ imageMode: 'grok', imageModelId: 'nope' }], null);+ expect(out.cloudModel).toBeNull();+ expect(out.modelId).toBeNull();+ });++ it('still applies a model-only pin when the pinned mode equals the settings mode', () => {+ const out = applyRecordRenderPin(cfg, [{ imageMode: 'codex', imageModelId: 'gpt-5.6-luna' }], backends);+ expect(out.mode).toBe(IMAGE_GEN_MODE.CODEX);+ expect(out.cloudModel).toBe('gpt-5.6-luna');+ });+});diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex 173d19d7d8..d8414f9a97 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -50,8 +50,14 @@ export const AGY_IMAGEGEN_IMAGE_MODEL = 'imagen-3.0-generate-002';// (supportsModelOverride: false) and local video models are picked on the// surface itself, so no video-model control is offered anywhere.export const RENDER_TARGET_BACKEND_AUTO = 'auto';+// Named ids for the targets the CLIENT resolves itself (via `renderTargetPin`),+// so a call site names the surface instead of retyping the string. The ids are+// bound to the server's RENDER_TARGETS by renderTargets.parity.test.js.+export const RENDER_TARGET = Object.freeze({+ UNIVERSE_BIBLE: 'universe-bible',+});export const RENDER_TARGET_OPTIONS = Object.freeze([- { id: 'universe-bible', label: 'Universe Bible batch renders' },+ { id: 'universe-bible', label: 'Universe Bible & canon renders' },{ id: 'universe-character-sheet', label: 'Universe character sheets' },{ id: 'series-first-pass', label: 'Series first-pass portraits & frames' },{ id: 'sprite-reference', label: 'Sprite references & anchors' },@@ -115,6 +121,79 @@ export const MODEL_OVERRIDE_CAPABLE_MODES = Object.freeze([]);export const supportsCloudModelOverride = (mode) => MODEL_OVERRIDE_CAPABLE_MODES.includes(mode);+/**+ * Client mirror of the server's `renderTargetDefaults`+ * (imageGen/cloudProviderConfig.js) — one surface's saved `settings.renderDefaults`+ * pin, re-keyed to the flat `imageMode`/`imageModelId` shape `renderPinLadder`+ * consumes so a target pin and a record pin are the same kind of thing.+ */+export const renderTargetPin = (settings, target) => ({+ imageMode: settings?.renderDefaults?.[target]?.imageMode ?? null,+ imageModelId: settings?.renderDefaults?.[target]?.imageModel ?? null,+});++/**+ * Resolve the effective render pin from an ordered ladder of pin sources — the+ * client mirror of the server's `resolveRenderTargetConfig` (#3231), minus the+ * explicit-per-request rung the caller owns. Pass sources highest-priority+ * first, which for every surface is: the record's own pin (`recordRenderPin`'s+ * `imageMode`/`imageModelId`), then the target's `renderTargetPin(settings, target)`.+ *+ * Why the client resolves this at all: single-image render call sites (a+ * universe cast reference, the base-style probe) send `mode` EXPLICITLY, and an+ * explicit mode outranks every pin on the server ladder — so a universe pinned+ * to agy rendered its cast on whatever the install-wide default resolved to+ * (codex, on a codex-enabled install) until the client folded the pin in itself.+ *+ * `availableBackends` (the `deriveAvailableBackends` shape) is a client-side+ * usability gate with no server counterpart: a pin naming a backend this install+ * no longer has enabled falls through to the next rung rather than queueing a+ * job that can only 400. Pass `null` when the backend list isn't loaded yet —+ * an empty array means "loaded, nothing enabled" and suppresses every pin.+ *+ * @param {Array<object|null>} sources - Pin sources, highest priority first.+ * @param {Array<{id:string}>|null} [availableBackends] - Enabled backends, or null.+ * @returns {{mode: string|null, modelId: string|null}} The first usable pin.+ */+export function renderPinLadder(sources, availableBackends = null) {+ for (const source of sources) {+ const mode = normalizeRenderPinValue(source?.imageMode);+ if (!mode) continue;+ if (Array.isArray(availableBackends) && !availableBackends.some((b) => b.id === mode)) continue;+ return { mode, modelId: normalizeRenderPinValue(source?.imageModelId) };+ }+ return { mode: null, modelId: null };+}++/**+ * Fold `renderPinLadder`'s result over a settings-derived per-render config.+ *+ * Returns `cfg` BY IDENTITY when no pin applies — every consumer passes this+ * cfg down as a prop, so an unconditional spread would churn a re-render for+ * every unpinned record.+ *+ * @param {object} cfg - Settings-derived config (`readPipelineImageSettings` shape).+ * @param {Array<object|null>} sources - Pin sources, highest priority first.+ * @param {Array<{id:string}>|null} [availableBackends] - Enabled backends, or null.+ * @returns {object} `cfg` unchanged when there's no usable pin, else a pinned copy.+ */+export function applyRecordRenderPin(cfg, sources, availableBackends = null) {+ const { mode, modelId } = renderPinLadder(sources, availableBackends);+ if (!mode) return cfg;+ const isLocal = mode === IMAGE_GEN_MODE.LOCAL;+ return {+ ...cfg,+ mode,+ // The pinned model lands on the knob that backend actually reads: local+ // diffusion takes `modelId`, an override-capable cloud CLI takes+ // `cloudModel`. The other is nulled rather than omitted — `cfg` arrives+ // spread in with a settings-derived local `modelId`, which would otherwise+ // ride along into a cloud render.+ modelId: isLocal ? (modelId || cfg?.modelId) : null,+ cloudModel: !isLocal && supportsCloudModelOverride(mode) ? modelId : null,+ };+}+// Human-facing name for a backend ('Local', 'Codex', 'Grok', 'Agy', 'External').// Shared so label ladders (`isCodex ? 'Codex model' : …`) don't re-type what// MODE_LABELS already holds and grow a branch per backend.diff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.jsindex 3d051a5c3c..c63f3943f4 100644--- a/client/src/lib/pipelineImageDefaults.js+++ b/client/src/lib/pipelineImageDefaults.js@@ -50,20 +50,31 @@ export function readPipelineImageSettings(settings) {};}+// "Unset" for the numeric knobs is the empty string. `Number('')` (and+// `Number(null)`) is 0, not NaN, so a plain coercion turns an unset knob into a+// HARD ZERO the server honors: `seed: 0` pins a fixed seed, making repeat+// renders of one prompt identical. Blank must reach the `Number.isFinite` gates+// below as NaN so they drop it.+const numericOrNaN = (v) => (String(v ?? '').trim() === '' ? NaN : Number(v));+// Strip empty strings + coerce numerics so the request body only carries// fields the server should act on. Empty strings would otherwise serialize// to "" and trip the zod number coercion.export function pipelineImageCfgToRenderOpts(cfg) {const opts = { mode: cfg.mode };if (cfg.mode === IMAGE_GEN_MODE.LOCAL && cfg.modelId) opts.modelId = cfg.modelId;+ // A record render pin can name the cloud CLI's model too (`applyRecordRenderPin`+ // routes it here); the dispatcher folds `cloudModel` into the provider's own+ // model for that one job. Local reads `modelId` above instead.+ if (isCloudCliMode(cfg.mode) && cfg.cloudModel) opts.cloudModel = cfg.cloudModel;if (Number.isFinite(cfg.width)) opts.width = cfg.width;if (Number.isFinite(cfg.height)) opts.height = cfg.height;if (!isCloudCliMode(cfg.mode)) {- const steps = Number(cfg.steps);+ const steps = numericOrNaN(cfg.steps);if (Number.isFinite(steps) && steps > 0) opts.steps = steps;- const guidance = Number(cfg.guidance);+ const guidance = numericOrNaN(cfg.guidance);if (Number.isFinite(guidance) && guidance >= 0) opts.guidance = guidance;- const seed = Number(cfg.seed);+ const seed = numericOrNaN(cfg.seed);if (Number.isFinite(seed) && seed >= 0) opts.seed = seed;}const neg = (cfg.negativePrompt || '').trim();diff --git a/client/src/lib/pipelineImageDefaults.test.js b/client/src/lib/pipelineImageDefaults.test.jsnew file mode 100644index 0000000000..09863c9b32--- /dev/null+++ b/client/src/lib/pipelineImageDefaults.test.js@@ -0,0 +1,55 @@+import { describe, it, expect } from 'vitest';+import { PIPELINE_IMAGE_DEFAULTS, readPipelineImageSettings, pipelineImageCfgToRenderOpts } from './pipelineImageDefaults';+import { IMAGE_GEN_MODE } from './imageGenBackends';++describe('readPipelineImageSettings', () => {+ it('prefers an enabled cloud backend over local, codex first', () => {+ expect(readPipelineImageSettings({ imageGen: { codex: { enabled: true }, agy: { enabled: true } } }).mode)+ .toBe(IMAGE_GEN_MODE.CODEX);+ expect(readPipelineImageSettings({ imageGen: { agy: { enabled: true } } }).mode)+ .toBe(IMAGE_GEN_MODE.AGY);+ expect(readPipelineImageSettings({}).mode).toBe(PIPELINE_IMAGE_DEFAULTS.mode);+ });++ it("lets a stored settings.pipeline.imageGen mode win over the cloud preference", () => {+ expect(readPipelineImageSettings({+ imageGen: { codex: { enabled: true } },+ pipeline: { imageGen: { mode: 'local' } },+ }).mode).toBe(IMAGE_GEN_MODE.LOCAL);+ });+});++describe('pipelineImageCfgToRenderOpts', () => {+ it('sends modelId only for local', () => {+ const local = pipelineImageCfgToRenderOpts({ mode: 'local', modelId: 'flux-1', width: 512 });+ expect(local.modelId).toBe('flux-1');+ const cloud = pipelineImageCfgToRenderOpts({ mode: 'agy', modelId: 'flux-1', width: 512 });+ expect(cloud.modelId).toBeUndefined();+ });++ // `Number('')` is 0 — an unset seed used to ride out as a HARD `seed: 0`,+ // which the local runner honors as a fixed seed, so every render of the same+ // prompt came back identical. Unset must mean absent.+ it('omits unset numeric knobs instead of coercing the blank to zero', () => {+ const opts = pipelineImageCfgToRenderOpts({+ ...PIPELINE_IMAGE_DEFAULTS, mode: 'local', modelId: 'flux-1', width: 512, height: 512,+ });+ expect(opts).toEqual({ mode: 'local', modelId: 'flux-1', width: 512, height: 512 });+ expect(pipelineImageCfgToRenderOpts({ mode: 'local', seed: ' ' }).seed).toBeUndefined();+ expect(pipelineImageCfgToRenderOpts({ mode: 'local' }).guidance).toBeUndefined();+ });++ it('still sends an explicit zero the user actually typed', () => {+ const opts = pipelineImageCfgToRenderOpts({ mode: 'local', seed: '0', guidance: '0' });+ expect(opts.seed).toBe(0);+ expect(opts.guidance).toBe(0);+ });++ it('forwards a cloud-CLI model as cloudModel, which is the knob the dispatcher reads', () => {+ expect(pipelineImageCfgToRenderOpts({ mode: 'agy', cloudModel: 'gemini-3.5-pro' }).cloudModel)+ .toBe('gemini-3.5-pro');+ // Local reads modelId instead — a cloudModel here would be dead weight.+ expect(pipelineImageCfgToRenderOpts({ mode: 'local', cloudModel: 'gemini-3.5-pro' }).cloudModel)+ .toBeUndefined();+ });+});diff --git a/client/src/pages/StoryBuilder.jsx b/client/src/pages/StoryBuilder.jsxindex 1ed7f74926..a5956a30cf 100644--- a/client/src/pages/StoryBuilder.jsx+++ b/client/src/pages/StoryBuilder.jsx@@ -5,6 +5,7 @@ import { filterSelectableModels } from '../utils/providers';import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';import { descriptorForCanonEntry } from '../lib/canonPrompt';import { pipelineImageCfgToRenderOpts } from '../lib/pipelineImageDefaults';+import { RENDER_TARGET } from '../lib/imageGenBackends';import { buildUniverseSectionRenderTag } from '../lib/universeRunTag';import { capImageRefs } from '../lib/bibleLimits';import useImageRenderSettings from '../hooks/useImageRenderSettings';@@ -927,7 +928,8 @@ function StepPanel({ session, universe, series, issues, stepId, locked, onChange// the universe canon entry's imageRefs.function StepCharacters({ session, universe, locked, onChanged, onUniverseCharRef }) {const cast = universe?.characters || [];- const { imageCfg } = useImageRenderSettings();+ // Universe canon renders, so they resolve the universe's pin ladder (see renderPinLadder).+ const { imageCfg } = useImageRenderSettings({ record: universe, target: RENDER_TARGET.UNIVERSE_BIBLE });const [refiningId, setRefiningId] = useState(null);const { start: startRefine, busy: refineBusy, phase: refinePhase } = useStepStream(session.id, 'characters');diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 5f4e6afaea..b7272c3894 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -35,8 +35,35 @@ import {} from './cloudProviderConfig.js';import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';+import { getUniverseRenderPin } from '../universeBuilder/crud.js';import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';+// The job tags that name the record owning a render, each mapped to the record+// loader and the render target whose `renderDefaults` pin backs it. A generate+// request carrying one of these and NO explicit mode resolves its backend+// through that record's pin — see the ladder below. Ordered by priority; the+// first tag present on the request wins.+//+// `load` runs on every mode-less tagged render and only two scalars are read+// off it, so prefer a projected pin-only read over a full record load for any+// record big enough to care — a universe carries its whole canon plus a+// sanitize pass, hence `getUniverseRenderPin`. A music-video project is small,+// so it still uses the ordinary getter.+const RECORD_PIN_SOURCES = Object.freeze([+ {+ tag: 'musicVideo',+ idKey: 'projectId',+ target: RENDER_TARGET.MUSIC_VIDEO,+ load: getMusicVideoProject,+ },+ {+ tag: 'universeRun',+ idKey: 'universeId',+ target: RENDER_TARGET.UNIVERSE_BIBLE,+ load: getUniverseRenderPin,+ },+]);+// Only the formats mflux can decode — mirrors the route's MIME_TO_EXT map// so the route never silently relabels (e.g. HEIC) bytes as ".png".const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp' };@@ -97,20 +124,24 @@ export async function prepareGenerateParams({ data, files, referenceImageFields// is cheap — it's already read again below for the per-mode dispatch.)const settings = await getSettings();let mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;- // #3231 Phase 4 — Music Video scene-frame renders resolve through the- // render-target ladder: the owning project's record pin- // (`imageMode`/`imageModelId`) → `renderDefaults['music-video']` → the- // install default above. The director board sends NO mode with its frame- // renders, so the record/target pins are live without any client seeding- // (unlike the universe batch form). An explicit per-request mode wins- // outright (and blocks the pinned model from leaking), so the project fetch- // is skipped entirely in that case. The layered model is stamped onto- // `data.cloudModel` so the route/dispatch resolution downstream picks it up;- // an explicit per-request cloudModel wins untouched.- if (!data.mode && data.musicVideo?.projectId) {- const project = await getMusicVideoProject(data.musicVideo.projectId).catch(() => null);- const pin = recordRenderPin(project || {});- const resolved = resolveRenderTargetConfig(settings, RENDER_TARGET.MUSIC_VIDEO, {+ // #3231 Phase 4 — a render tagged with the record that owns it resolves+ // through the render-target ladder: that record's pin+ // (`imageMode`/`imageModelId`) → `renderDefaults[target]` → the install+ // default above. An explicit per-request mode wins outright (and blocks the+ // pinned model from leaking), so the record fetch is skipped entirely in that+ // case. The layered model is stamped onto `data.cloudModel` so the+ // route/dispatch resolution downstream picks it up; an explicit per-request+ // cloudModel wins untouched.+ //+ // First matching tag wins — a payload carrying two tags would otherwise let+ // whichever branch ran last silently overwrite the other's mode while+ // inheriting its model. Adding a surface is one row here, matching the+ // "one entry + one resolve call" contract in lib/renderTargets.js.+ const source = data.mode ? null : RECORD_PIN_SOURCES.find((s) => data[s.tag]?.[s.idKey]);+ if (source) {+ const record = await source.load(data[source.tag][source.idKey]).catch(() => null);+ const pin = recordRenderPin(record || {});+ const resolved = resolveRenderTargetConfig(settings, source.target, {model: data.cloudModel || null,recordMode: pin.mode,recordModel: pin.modelId,diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.jsindex 11ed900797..144b7150f8 100644--- a/server/services/imageGen/prepareParams.test.js+++ b/server/services/imageGen/prepareParams.test.js@@ -1,11 +1,12 @@/**- * prepareGenerateParams — Music Video render-target resolution (#3231 Phase 4).+ * prepareGenerateParams — record render-target resolution (#3231 Phase 4).*- * Scene reference-frame renders arrive with a `musicVideo` tag and NO mode, so- * the mode must come from the render-target ladder (record pin →- * renderDefaults['music-video'] → install default) and the layered model must- * land on `data.cloudModel`, which is what the route's dispatch resolution- * reads. Only the ladder inputs are mocked; the resolver itself runs for real.+ * Scene reference-frame renders (`musicVideo` tag) and universe canon renders+ * (`universeRun` tag) can arrive with NO mode, so the mode must come from the+ * render-target ladder (record pin → renderDefaults[target] → install default)+ * and the layered model must land on `data.cloudModel`, which is what the+ * route's dispatch resolution reads. Only the ladder inputs are mocked; the+ * resolver itself runs for real.*/import { describe, it, expect, vi, beforeEach } from 'vitest';@@ -16,6 +17,9 @@ vi.mock('../settings.js', () => ({ getSettings: (...a) => getSettings(...a) }));const getProject = vi.fn(async () => null);vi.mock('../musicVideo/projects.js', () => ({ getProject: (...a) => getProject(...a) }));+const getUniverseRenderPin = vi.fn(async () => null);+vi.mock('../universeBuilder/crud.js', () => ({ getUniverseRenderPin: (...a) => getUniverseRenderPin(...a) }));+const { prepareGenerateParams } = await import('./prepareParams.js');const CODEX_ON = { codex: { enabled: true, codexPath: '/bin/codex' } };@@ -25,6 +29,7 @@ beforeEach(() => {vi.clearAllMocks();getSettings.mockResolvedValue({});getProject.mockResolvedValue(null);+ getUniverseRenderPin.mockResolvedValue(null);});describe('music-video render-target resolution (#3231 Phase 4)', () => {@@ -72,3 +77,65 @@ describe('music-video render-target resolution (#3231 Phase 4)', () => {expect(getProject).not.toHaveBeenCalled();});});++describe('universe render-target resolution', () => {+ const AGY_ON = { agy: { enabled: true, agyPath: '/bin/agy' } };+ const tag = { universeId: 'uni-1', universeName: 'Example Universe', category: 'characters' };++ it("resolves the owning universe's record pin for a mode-less canon render", async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', ...AGY_ON } });+ getUniverseRenderPin.mockResolvedValue({ id: 'uni-1', imageMode: 'agy', imageModelId: 'record-model' });+ const { data, mode } = await run({ prompt: 'p', universeRun: tag });+ expect(getUniverseRenderPin).toHaveBeenCalledWith('uni-1');+ expect(mode).toBe('agy');+ expect(data.cloudModel).toBe('record-model');+ });++ it("resolves renderDefaults['universe-bible'] when the universe has no pin", async () => {+ getSettings.mockResolvedValue({+ imageGen: { mode: 'local', ...AGY_ON },+ renderDefaults: { 'universe-bible': { imageMode: 'agy', imageModel: 'target-model' } },+ });+ getUniverseRenderPin.mockResolvedValue({ id: 'uni-1' });+ const { data, mode } = await run({ prompt: 'p', universeRun: tag });+ expect(mode).toBe('agy');+ expect(data.cloudModel).toBe('target-model');+ });++ it('an explicit request mode outranks the universe pin (and its model does not leak)', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'external', ...AGY_ON } });+ getUniverseRenderPin.mockResolvedValue({ id: 'uni-1', imageMode: 'agy', imageModelId: 'record-model' });+ const { data, mode } = await run({ prompt: 'p', mode: 'local', universeRun: tag });+ expect(mode).toBe('local');+ expect(data.cloudModel).toBeUndefined();+ expect(getUniverseRenderPin).not.toHaveBeenCalled();+ });++ it('falls through to the install default when the universe is gone', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });+ getUniverseRenderPin.mockRejectedValue(new Error('gone'));+ const { mode } = await run({ prompt: 'p', universeRun: { ...tag, universeId: 'uni-x' } });+ expect(mode).toBe('external');+ });++ it('renders without a universeRun tag never touch the universe store', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });+ await run({ prompt: 'p' });+ expect(getUniverseRenderPin).not.toHaveBeenCalled();+ });++ // Two tags on one payload used to run BOTH branches: the second overwrote the+ // first's mode while inheriting the model it had just stamped, producing a+ // mismatched mode/model pair and a wasted record read.+ it('resolves the first matching tag only when a payload carries two', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', ...AGY_ON, codex: { enabled: true } } });+ getProject.mockResolvedValue({ id: 'mv-1', imageMode: 'codex', imageModelId: 'mv-model' });+ getUniverseRenderPin.mockResolvedValue({ imageMode: 'agy', imageModelId: 'uni-model' });+ const { data, mode } = await run({+ prompt: 'p', musicVideo: { projectId: 'mv-1', sceneId: 's1' }, universeRun: tag,+ });+ expect(mode).toBe('codex');+ expect(data.cloudModel).toBe('mv-model');+ expect(getUniverseRenderPin).not.toHaveBeenCalled();+ });+});diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.jsindex dd404e8e41..75ce5389a2 100644--- a/server/services/universeBuilder/crud.js+++ b/server/services/universeBuilder/crud.js@@ -164,6 +164,35 @@ export async function getUniverse(id, { includeDeleted = false } = {}) {return w;}+/**+ * One universe's render pin (`imageMode` / `imageModelId`) and nothing else.+ *+ * Same motivation as `listUniverseNames` / `listUniverseStyles` above, applied+ * to a by-id read: the two scalars a render-target ladder needs would otherwise+ * cost a `getUniverse`, whose `sanitizeTemplate` pass walks every variation,+ * composite sheet, and bible entry (minting UUIDs for id-less ones) — and that+ * runs on EVERY mode-less universe-tagged render, so an agent filling a+ * 20-entry cast pays it 20 times. Reach for this instead of+ * `recordRenderPin(await getUniverse(id))`.+ *+ * This skips the SANITIZER, not the row fetch — both backends' `readRaw` still+ * return the whole record. That's fine because the sanitize pass is the part+ * that scales with canon size; projecting the two columns in SQL would shave a+ * row read that is already a single indexed lookup, at the cost of a+ * backend-specific query pair.+ *+ * Reading raw is safe because `recordRenderPin` applies the same+ * `normalizeRenderPinValue` the sanitizer's persisted pin fields do. Raw reads+ * DO return tombstones, so deleted records are filtered here; a missing or+ * deleted universe resolves to `null` (the caller falls through the ladder)+ * rather than throwing, since a render must not fail over a stale tag.+ */+export async function getUniverseRenderPin(id) {+ const raw = await store().loadOneRaw(id);+ if (!raw || raw.deleted) return null;+ return { imageMode: raw.imageMode ?? null, imageModelId: raw.imageModelId ?? null };+}+// Returns true when the raw on-disk universe carries variations or composite// sheets that are missing a stable `id` field — i.e. sanitizeTemplate would// mint fresh UUIDs (and those UUIDs would differ on every read until the