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

feat([issue-3231]): per-record render backend/model pins on universe, series, and sprite records

[._.]/ Adam Eivya61c526d5dd9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6085ca6500..3d6ee2b813 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
## Image generation
- **[issue-3231] Each creative surface can now have its own default image backend and model.** A new Defaults tab in Settings → Image Gen lets you pin, per surface — Universe Bible batch renders, character sheets, Series first-pass portraits, sprite references, pipeline visuals, LoRA datasets, and creative-agent renders — which backend (Local, Codex, Grok, or Agy) and, where the backend accepts one, which model that surface renders with. Anything left on Auto keeps following the install-wide default exactly as before, a pinned backend that's disabled safely falls back instead of breaking the surface, and an explicit choice made on a page still wins over the pin. Pinned models now actually reach the renderer on every one of these surfaces — previously they all silently used the provider's own default.
+- **[issue-3231] Universes, series, and sprites can now each carry their own render backend and model.** A Universe can say "my bible and character-sheet renders go to Codex on this model," a Series can pin the backend its storyboards, comic pages, and covers render on, and a sprite's backend picker now saves onto the sprite itself (with a model field for Codex/Agy) so re-rolls and future sessions keep rendering where you chose. The pin is edited right on each record's page — the Universe Builder's Render tab, the series bible sidebar, and the sprite reference workflow — and layers naturally: an explicit per-batch choice still wins, an unpinned record follows the per-surface default from Settings, and a pinned backend that's since been disabled falls back safely instead of breaking renders. Creative Director first-pass portraits and scene frames now honor the project's existing render-backend pin too. Because a pinned backend is a per-machine capability choice, pins stay on the machine that set them rather than syncing to federated peers that may not have that backend configured.
- **[issue-3231] Agy image renders now default to a cheap, fast agent model.** An Agy render with no model chosen used to run on whatever Antigravity's own configuration selected — potentially its slowest, most expensive reasoning tier — just to relay a single image request. Renders now default to the cheapest flash tier (matching how Codex renders already pin their light model), and a model you set in Settings or per render still wins. Settings → Image Gen → Agy CLI also now makes clear which model the field controls: the *agent* driving the session, not the image model — the image itself always renders on Antigravity's fixed server-side Imagen 3 backend, which is now named on the page and recorded with each generated image.
## 3D avatars
diff --git a/client/src/components/imageGen/RecordRenderPinRow.jsx b/client/src/components/imageGen/RecordRenderPinRow.jsx
new file mode 100644
index 0000000000..3f522a4a98
--- /dev/null
+++ b/client/src/components/imageGen/RecordRenderPinRow.jsx
@@ -0,0 +1,54 @@
+import { IMAGE_GEN_MODE, RENDER_TARGET_BACKEND_AUTO, modeLabel, supportsCloudModelOverride } from '../../lib/imageGenBackends';
+
+const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY];
+
+// Per-record render pin editor (#3231 Phase 3) — one row pinning a record's
+// default image backend + (for model-override-capable cloud CLIs) a model.
+// Mirrors the Settings → Image Gen "Render defaults" row: the model input only
+// appears when the pinned backend accepts one, and ANY backend change clears
+// the pinned model — model ids are namespaced per provider, and the server's
+// leak guard can't catch a mode+model pinned together (see ImageGenTab).
+//
+// `onChange` always receives BOTH keys (`{ imageMode, imageModelId }`), with
+// null for "no pin" — key-present-with-null is the intentional clear per the
+// absent-vs-empty convention, so callers can PATCH the payload verbatim.
+export default function RecordRenderPinRow({
+ idPrefix,
+ label = 'Render backend',
+ imageMode = null,
+ imageModelId = null,
+ onChange,
+ modes = DEFAULT_MODES,
+ autoLabel = 'Auto (default)',
+}) {
+ const pinnedMode = imageMode && imageMode !== RENDER_TARGET_BACKEND_AUTO ? imageMode : '';
+ return (
+ <div className="grid grid-cols-1 sm:grid-cols-[auto_auto_1fr] gap-2 sm:items-center">
+ <label htmlFor={`${idPrefix}-mode`} className="text-xs font-medium text-gray-400">{label}</label>
+ <select
+ id={`${idPrefix}-mode`}
+ value={pinnedMode}
+ onChange={(e) => onChange({ imageMode: e.target.value || null, imageModelId: null })}
+ className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-44"
+ >
+ <option value="">{autoLabel}</option>
+ {modes.map((m) => <option key={m} value={m}>{modeLabel(m)}</option>)}
+ </select>
+ {supportsCloudModelOverride(pinnedMode) ? (
+ <input
+ id={`${idPrefix}-model`}
+ type="text"
+ defaultValue={imageModelId || ''}
+ key={`${pinnedMode}:${imageModelId || ''}`}
+ onBlur={(e) => {
+ const v = e.target.value.trim() || null;
+ if (v !== (imageModelId || null)) onChange({ imageMode: pinnedMode, imageModelId: v });
+ }}
+ placeholder="Model (optional)"
+ aria-label={`${label} model`}
+ className="bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent sm:w-52"
+ />
+ ) : <span className="hidden sm:block" />}
+ </div>
+ );
+}
diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsx
index a53ce271bb..69f1f78b95 100644
--- a/client/src/components/sprites/ReferenceWorkflow.jsx
+++ b/client/src/components/sprites/ReferenceWorkflow.jsx
@@ -18,6 +18,7 @@ import CorrectionNote, {
} from './CorrectionNote.jsx';
import FilePickerButton from '../ui/FilePickerButton';
import { IMAGE_ACCEPT } from '../../utils/fileUpload';
+import { supportsCloudModelOverride } from '../../lib/imageGenBackends';
// Reference workflow (issues #2896, #2979): three ordered steps — generate a
// turnaround sheet from text + an optional design image and freeze it, derive
@@ -440,16 +441,48 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti
const noBackend = Array.isArray(backends) && backends.length === 0;
const modePicker = Array.isArray(backends) && backends.length > 0 && (
- <label className="flex items-center gap-2 text-xs text-gray-400">
- Backend
- <select
- value={mode}
- onChange={(e) => onModeChange(e.target.value)}
- className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
- >
- {backends.map((b) => <option key={b.id} value={b.id}>{b.label || b.id}</option>)}
- </select>
- </label>
+ <span className="flex items-center gap-2 flex-wrap">
+ <label className="flex items-center gap-2 text-xs text-gray-400">
+ Backend
+ <select
+ value={mode}
+ onChange={(e) => {
+ const v = e.target.value;
+ onModeChange(v);
+ // Persist the choice as THIS record's render pin (#3231 Phase 3)
+ // so re-rolls and future sessions render on the same backend. A
+ // backend change clears the pinned model — ids are namespaced per
+ // provider (the ImageGenTab render-defaults precedent).
+ updateSpriteRecord(recordId, { imageMode: v || null, imageModelId: null }, { silent: true })
+ .then(() => onChanged())
+ .catch((err) => toast.error(`Backend pin save failed: ${err.message}`));
+ }}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"
+ >
+ {backends.map((b) => <option key={b.id} value={b.id}>{b.label || b.id}</option>)}
+ </select>
+ </label>
+ {supportsCloudModelOverride(mode) && (
+ <label className="flex items-center gap-2 text-xs text-gray-400">
+ Model
+ <input
+ type="text"
+ key={`${recordId}:${mode}:${record.imageModelId || ''}`}
+ defaultValue={record.imageModelId || ''}
+ onBlur={(e) => {
+ const v = e.target.value.trim() || null;
+ if (v === (record.imageModelId || null)) return;
+ updateSpriteRecord(recordId, { imageModelId: v }, { silent: true })
+ .then(() => onChanged())
+ .catch((err) => toast.error(`Model pin save failed: ${err.message}`));
+ }}
+ placeholder="Provider default"
+ aria-label="Pinned cloud model for this sprite"
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white w-44"
+ />
+ </label>
+ )}
+ </span>
);
const turnaroundCandidates = candidatesByTarget.turnaround || [];
const mainCandidates = candidatesByTarget.main || [];
diff --git a/client/src/components/universeBuilder/RenderTab.jsx b/client/src/components/universeBuilder/RenderTab.jsx
index ec30c43442..f7d7cab928 100644
--- a/client/src/components/universeBuilder/RenderTab.jsx
+++ b/client/src/components/universeBuilder/RenderTab.jsx
@@ -5,6 +5,7 @@ import { formatDateTime } from '../../utils/formatters';
import { RUNNER_FAMILIES, loraCompatKey } from '../../lib/runnerFamilies';
import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';
import ImageGenSettingsForm from '../imageGen/ImageGenSettingsForm';
+import RecordRenderPinRow from '../imageGen/RecordRenderPinRow';
import { TRUNK_TABS, humanizeCategory } from '../../lib/universeBuilderShared';
import { totalVariationCount, countCanonWithContent } from '../../lib/universeBuilderCounts';
@@ -13,7 +14,7 @@ import { totalVariationCount, countCanonWithContent } from '../../lib/universeBu
// recent-runs list. Extracted from UniverseBuilder.jsx (#2374). handleRender
// (owned by the page) queues the actual render jobs.
export default function RenderTab({
- draft, selectedId, bucketsByKind, renderOpts, setRenderOpts,
+ draft, setRenderPin, selectedId, bucketsByKind, renderOpts, setRenderOpts,
availableBackends, defaultMode, imageModels, availableLoras = [],
handleRender, rendering, runs,
}) {
@@ -64,6 +65,17 @@ export default function RenderTab({
to enable batch render.
</p>
)}
+ {/* Per-universe render pin (#3231 Phase 3) — the persisted default for
+ THIS universe's bible + character-sheet renders. The batch form
+ below still overrides for one batch (transient renderOpts). */}
+ <RecordRenderPinRow
+ idPrefix={`universe-render-pin-${selectedId || 'new'}`}
+ label="This universe's default"
+ imageMode={draft.imageMode || null}
+ imageModelId={draft.imageModelId || null}
+ onChange={setRenderPin}
+ autoLabel="Auto (install / surface default)"
+ />
<ImageGenSettingsForm
value={{ ...renderOpts, mode: renderOpts.mode || defaultMode || IMAGE_GEN_MODE.LOCAL }}
onChange={(next) => setRenderOpts(next)}
diff --git a/client/src/components/universeBuilder/UniverseBuilderPage.jsx b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
index 5dc418fb0a..76b6f9adcc 100644
--- a/client/src/components/universeBuilder/UniverseBuilderPage.jsx
+++ b/client/src/components/universeBuilder/UniverseBuilderPage.jsx
@@ -144,6 +144,7 @@ export default function UniverseBuilder() {
removeStyleReference,
runs,
saving,
+ setRenderPin,
setCanonDirty,
setDraft,
setNewCategoryName,
@@ -716,6 +717,7 @@ export default function UniverseBuilder() {
{activeTab === TAB_RENDER && (
<RenderTab
draft={draft}
+ setRenderPin={setRenderPin}
selectedId={selectedId}
bucketsByKind={bucketsByKind}
renderOpts={renderOpts}
diff --git a/client/src/hooks/useUniverseDraft.js b/client/src/hooks/useUniverseDraft.js
index a1d230fc92..0e30f95148 100644
--- a/client/src/hooks/useUniverseDraft.js
+++ b/client/src/hooks/useUniverseDraft.js
@@ -462,6 +462,18 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
});
}, [selectedId]);
+ // Per-record render pin (#3231 Phase 3) — this universe's default image
+ // backend + cloud model. Mirrors toggleLock: reactive local update plus an
+ // immediate targeted PATCH (the pin is not part of the autosaved draft
+ // payload, so a stale draft flush can't resurrect a cleared pin).
+ const setRenderPin = useCallback(({ imageMode, imageModelId }) => {
+ setDraft((current) => ({ ...current, imageMode, imageModelId }));
+ if (selectedId) {
+ updateUniverse(selectedId, { imageMode, imageModelId }, { silent: true })
+ .catch((error) => toast.error(`Render pin save failed: ${error.message}`));
+ }
+ }, [selectedId]);
+
const updateCategory = useCallback((category, variations) => setDraft((current) => ({
...current,
categories: {
@@ -573,6 +585,7 @@ export default function useUniverseDraft({ selectedId, goToWorld }) {
removeStyleReference,
runs,
saving,
+ setRenderPin,
setCanonDirty,
setDraft,
setNewCategoryName,
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 182d21f07c..2e497e2823 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -37,6 +37,7 @@ import { buildImporterLink } from '../lib/importerDeepLink';
import { recommendStructure, describeStructure } from '../lib/seasonStructure';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { useArcCanvasSync } from '../hooks/useArcCanvasSync';
+import RecordRenderPinRow from '../components/imageGen/RecordRenderPinRow';
const PIPELINE_SIDEBAR_KEY = 'portos-pipeline-series-sidebar-collapsed';
@@ -56,6 +57,7 @@ const ARC_FLUSH_FIELDS = [
'name', 'logline', 'premise', 'styleNotes', 'factCritical', 'factReference', 'styleGuide',
'titleLogo', 'author', 'authorId',
'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId', 'characterArcs',
+ 'imageMode', 'imageModelId',
];
const ARC_PAYLOAD_DEFAULTS = {
titleLogo: '',
@@ -73,6 +75,10 @@ const ARC_PAYLOAD_DEFAULTS = {
// Per-character story arcs (#1293) — [] means "no authored arcs"; the server
// sanitizer drops empty arcs/beats and dedupes by character identity.
characterArcs: [],
+ // Per-record render pin (#3231 Phase 3) — null means "no pin", which the
+ // server sanitizer also produces from an absent field.
+ imageMode: null,
+ imageModelId: null,
};
// Style-guide option lists — mirror the enums in server/lib/styleGuide.js. Each
@@ -505,6 +511,23 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
</p>
</Field>
+ <Field label="Render backend (this series only)">
+ {/* Per-record render pin (#3231 Phase 3) — this series' default image
+ backend + model for storyboards, comic pages, and covers. */}
+ <RecordRenderPinRow
+ idPrefix={`series-render-pin-${series.id}`}
+ label="Backend"
+ imageMode={series.imageMode || null}
+ imageModelId={series.imageModelId || null}
+ onChange={({ imageMode, imageModelId }) => patchSeries({ imageMode, imageModelId })}
+ autoLabel="Auto (install / surface default)"
+ />
+ <p className="text-[11px] text-gray-500 mt-1">
+ Pins this series' visual renders to one backend (and, for Codex/Agy, a model).
+ Leave on Auto to follow Settings → Image Gen.
+ </p>
+ </Field>
+
<CatalogCastPanel refKind="series" refId={series.id} refLabel={series.name || 'this series'} />
<div>
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index 1a298e631d..e904d5a8dc 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -413,7 +413,15 @@ export default function Sprites() {
setDetail((prev) => (prev?.record?.id === id ? prev : null));
setDetailState('loading');
getSpriteRecord(id, { silent: true })
- .then((d) => { if (!stale) { setDetail(d); setDetailState('loaded'); } })
+ .then((d) => {
+ if (stale) return;
+ setDetail(d);
+ setDetailState('loaded');
+ // Seed the page-owned backend picker from the record's persisted
+ // render pin (#3231 Phase 3) so an opened sprite renders where it was
+ // pinned; unpinned records keep the current page mode.
+ if (d?.record?.imageMode) setImageMode(d.record.imageMode);
+ })
.catch((err) => { if (!stale) setDetailState(err?.status === 404 || err?.status === 400 ? 'missing' : 'error'); });
return () => { stale = true; };
}, [id, retryTick]);
diff --git a/server/lib/renderTargets.js b/server/lib/renderTargets.js
index fd0ac81044..29e3c78a8d 100644
--- a/server/lib/renderTargets.js
+++ b/server/lib/renderTargets.js
@@ -34,3 +34,26 @@ export const RENDER_TARGETS = Object.freeze(Object.values(RENDER_TARGET));
// means the same thing; the explicit value exists so a UI select can round-trip
// the choice).
export const RENDER_TARGET_BACKEND_AUTO = 'auto';
+
+// Max length for a persisted per-record model-id pin — matches the
+// creative-commission `COMMISSION_RENDER_MODEL_MAX` convention.
+export const RECORD_RENDER_MODEL_MAX = 64;
+
+/**
+ * Normalize a record's persisted render pin (#3231 Phase 3 — the flat
+ * `imageMode` / `imageModelId` field pair on universe / series / sprite
+ * records, following the creative-commission shape). The `'auto'` sentinel,
+ * blank strings, and absent fields all collapse to null ("no pin"), so
+ * callers can hand the result straight to `resolveRenderTargetConfig`'s
+ * `recordMode` / `recordModel` options without re-checking sentinels.
+ */
+export function recordRenderPin(record) {
+ const norm = (v) => {
+ const s = typeof v === 'string' ? v.trim() : '';
+ return s && s !== RENDER_TARGET_BACKEND_AUTO ? s : null;
+ };
+ return {
+ mode: norm(record?.imageMode),
+ modelId: norm(record?.imageModelId),
+ };
+}
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index f8a7724b38..99fad307b8 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -144,9 +144,28 @@ export function sanitizeRecordForWire(kind, record) {
// field. The strip is byte-stable against pre-field peers — they never sent
// it, so the wire/hash form is unchanged for them.
if (kind === 'universe') {
- const { styleImageRefs: _styleImageRefs, ...universeRest } = rest;
+ // `imageMode`/`imageModelId` (#3231 Phase 3 per-record render pin) are
+ // WIRE-LOCAL for the same reasons as styleImageRefs: a pinned backend
+ // is an install-capability choice (the peer may not have codex/agy
+ // configured), the pair is one click to re-set, and stripping keeps
+ // universe sync flowing to pre-field peers without a whole-category
+ // schema gate. The sync merge restores the local values (see
+ // universeBuilder/sync.js).
+ const {
+ styleImageRefs: _styleImageRefs,
+ imageMode: _imageMode,
+ imageModelId: _imageModelId,
+ ...universeRest
+ } = rest;
return { ...universeRest, ...sanitizeSoftDeleteFields(record) };
}
+ if (kind === 'series') {
+ // Series carry the same wire-local per-record render pin (#3231
+ // Phase 3) — strip it for the same reasons as the universe pair
+ // above. ADDITIVE_SERIES_FIELDS preserves the local values on merge.
+ const { imageMode: _imageMode, imageModelId: _imageModelId, ...seriesRest } = rest;
+ return { ...seriesRest, ...sanitizeSoftDeleteFields(record) };
+ }
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
case 'mediaCollection': {
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index 7f18469407..c6f0ee69d7 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -179,6 +179,19 @@ describe('syncWire', () => {
expect(JSON.stringify(withRefs)).toBe(JSON.stringify(without));
});
+ it('strips the per-record render pin from universe wire form (#3231 Phase 3)', () => {
+ // imageMode/imageModelId are install-capability choices (the peer may
+ // not have the pinned backend configured) — wire-local like
+ // styleImageRefs, and byte-stable against a record without the pair.
+ const withPin = sanitizeRecordForWire('universe', {
+ id: 'u1', name: 'U', imageMode: 'agy', imageModelId: 'gemini-3.6-flash-low',
+ });
+ expect(withPin.imageMode).toBeUndefined();
+ expect(withPin.imageModelId).toBeUndefined();
+ const without = sanitizeRecordForWire('universe', { id: 'u1', name: 'U' });
+ expect(JSON.stringify(withPin)).toBe(JSON.stringify(without));
+ });
+
it('does NOT strip styleImageRefs from series/issue wire form (universe-only field)', () => {
// The strip is scoped to `kind === 'universe'` — series/issue records
// never carry styleImageRefs, but a stray value (hand-edit, corrupted
diff --git a/server/lib/validation.js b/server/lib/validation.js
index be98fc3a52..d4f297ecad 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -18,7 +18,7 @@ import {
} from '../services/sprites/animationTrackStore.js';
import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { VIDEO_GEN_MODES } from '../services/videoGen/modes.js';
-import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO } from './renderTargets.js';
+import { RENDER_TARGETS, RENDER_TARGET_BACKEND_AUTO, RECORD_RENDER_MODEL_MAX } from './renderTargets.js';
import { GROK_VIDEO_DURATIONS } from './grokVideoClip.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
@@ -1016,6 +1016,23 @@ export const renderDefaultsSettingsSchema = z.object(
Object.fromEntries(RENDER_TARGETS.map((t) => [t, renderTargetEntrySchema.optional()])),
);
+// Per-RECORD render pin (#3231 Phase 3) — the flat `imageMode`/`imageModelId`
+// field pair persisted on universe / series / sprite records, following the
+// creative-commission shape. Spread into a record's create + patch schemas.
+// Absent preserves; `'auto'`/`''`/null clears (the sanitizers collapse all
+// three to "no pin"). The model id keeps the shared cloud-model charset so a
+// pinned id can safely reach a CLI argv.
+export const recordRenderPinFields = {
+ imageMode: z.preprocess(
+ (v) => (v === '' ? null : v),
+ z.enum([RENDER_TARGET_BACKEND_AUTO, ...QUEUEABLE_IMAGE_MODES]).nullable().optional(),
+ ),
+ imageModelId: z.preprocess(
+ (v) => (v === '' ? null : v),
+ cloudModelIdString('model must be a valid model id').max(RECORD_RENDER_MODEL_MAX).nullable().optional(),
+ ),
+};
+
export const imageGenAgySettingsSchema = z.object({
enabled: z.boolean().optional(),
agyPath: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(500).optional()),
@@ -1135,6 +1152,9 @@ export const spriteRecordUpdateSchema = z.object({
// whatever hex they carried (the importer writes via upsert, not this
// schema); null clears back to auto-select-on-lock.
chromaKey: z.enum(CHROMA_KEY_HEXES).nullable().optional(),
+ // Per-record render pin (#3231 Phase 3) — this sprite's default image
+ // backend + cloud model for reference renders.
+ ...recordRenderPinFields,
});
// Phase 4 (issue #2898): publish binding — the shape check only; app
@@ -1251,6 +1271,8 @@ export const spriteCreateSchema = z.object({
// in practice. Absent → the service defaults to 'character'.
kind: z.enum(SPRITE_RECORD_KINDS).optional(),
spec: z.record(z.string(), z.unknown()).nullable().optional(),
+ // Per-record render pin (#3231 Phase 3) — seedable at create time (fork).
+ ...recordRenderPinFields,
});
// 'turnaround' is the identity root of the turnaround-first workflow (#2979) —
diff --git a/server/routes/creativeDirector.js b/server/routes/creativeDirector.js
index 12fe374b6d..9b3489b298 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -183,7 +183,7 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
// report how many were queued; the renders themselves run in the background.
let firstPass = null;
if (generateFirstPass && Array.isArray(result.added) && result.added.length > 0) {
- firstPass = await enqueueFirstPassPortraits(result.added)
+ firstPass = await enqueueFirstPassPortraits(result.added, project)
.catch((e) => {
console.log(`⚠️ CD first-pass portraits failed: ${e.message}`);
return null;
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 506666af2b..863c7435e0 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -442,7 +442,12 @@ describe('creativeDirector routes', () => {
});
const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: true });
expect(r.status).toBe(200);
- expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith([{ ingredientId: 'p1' }]);
+ // The project rides along so the CD renderBackend pin (#3231 Phase 3)
+ // reaches the first-pass mode resolver.
+ expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith(
+ [{ ingredientId: 'p1' }],
+ expect.objectContaining({ id: 'cd-1' }),
+ );
expect(r.body.firstPass).toEqual({ mode: 'local', enqueued: [{ ingredientId: 'p1', jobId: 'job-1' }], skipped: [] });
});
@@ -473,7 +478,10 @@ describe('creativeDirector routes', () => {
expect(r.status).toBe(200);
expect(r.body.composing).toBe(true);
expect(hook.startCreativeDirectorProject).toHaveBeenCalledWith('cd-1');
- expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith([{ ingredientId: 'p1' }]);
+ expect(firstPass.enqueueFirstPassPortraits).toHaveBeenCalledWith(
+ [{ ingredientId: 'p1' }],
+ expect.objectContaining({ id: 'cd-1' }),
+ );
});
it('400s on a non-boolean generateFirstPass', async () => {
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index c3c0d75d7a..e761508509 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -7,7 +7,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
-import { validateRequest, optionalBooleanMap, llmSchema } from '../../lib/validation.js';
+import { validateRequest, optionalBooleanMap, llmSchema, recordRenderPinFields } from '../../lib/validation.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import { TRIM_SIZES, INTERIOR_FONTS } from '../../lib/proseExportSettings.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
@@ -260,6 +260,9 @@ const seriesCreateSchema = z.object({
primaryManuscriptType: z.enum(seriesSvc.MANUSCRIPT_TYPES).nullable().optional(),
issueCountTarget: z.number().int().min(0).max(seriesSvc.ISSUE_COUNT_TARGET_MAX).optional(),
llm: llmSchema,
+ // Per-record render pin (#3231 Phase 3) — this series' default image
+ // backend + cloud model for pipeline visual renders.
+ ...recordRenderPinFields,
// Local-only "don't sync to peers" marker.
ephemeral: z.boolean().optional(),
});
@@ -302,6 +305,9 @@ const seriesPatchSchema = z.object({
// explicit empty array on a gate = "nothing blocks this gate".
severityWeights: severityWeightsSchema.nullable().optional(),
blockingSeverities: blockingSeveritiesSchema.nullable().optional(),
+ // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/''/null
+ // clears; key-absent preserves.
+ ...recordRenderPinFields,
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
const arcFieldLockSchema = z.object({ locked: z.boolean() });
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 0a58cd97b1..9dd24f8994 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -21,7 +21,7 @@
import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';
-import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray } from '../lib/validation.js';
+import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';
@@ -183,6 +183,9 @@ const createSchema = z.object({
characters: canonArrayField,
places: canonArrayField,
objects: canonArrayField,
+ // Per-record render pin (#3231 Phase 3) — this universe's default image
+ // backend + cloud model.
+ ...recordRenderPinFields,
// Local-only "don't sync to peers" marker — see sanitizeRecordForWire.
ephemeral: z.boolean().optional(),
});
@@ -220,6 +223,9 @@ const patchSchema = z.object({
places: canonArrayField,
objects: canonArrayField,
origin: originField,
+ // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/''/null
+ // clears; key-absent preserves.
+ ...recordRenderPinFields,
ephemeral: z.boolean().optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
@@ -351,6 +357,9 @@ const renderSchema = z.object({
// pick mode/size/steps without bouncing to the Image page first.
mode: z.enum(IMAGE_GEN_MODES).optional(),
modelId: z.string().trim().max(64).optional(),
+ // Per-batch cloud model override (#3231 Phase 3) — wins over the universe's
+ // persisted imageModelId pin and the renderDefaults imageModel pin.
+ cloudModel: z.string().trim().max(64).optional(),
width: z.number().int().min(64).max(2048).optional(),
height: z.number().int().min(64).max(2048).optional(),
steps: z.number().int().min(1).max(150).optional(),
diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.js
index f28664eafb..8656476301 100644
--- a/server/services/creativeDirector/firstPassGen.js
+++ b/server/services/creativeDirector/firstPassGen.js
@@ -71,11 +71,17 @@ export function buildPortraitPrompt(ingredient) {
* (#1867) uses the exact same queue-backed-mode gate as the portrait path
* rather than re-deriving it.
*/
-async function resolveQueueModeParams() {
+async function resolveQueueModeParams(project = null) {
const settings = await getSettings();
- // Render-target ladder (#3231): the series-first-pass pin in
- // settings.renderDefaults → the install default → external (not ready).
+ // Render-target ladder (#3231): the CD project's persisted renderBackend
+ // image pin (#3135 — the per-record override for this surface, Phase 3) →
+ // the series-first-pass pin in settings.renderDefaults → the install
+ // default → external (not ready). The record pin is usability-gated by the
+ // resolver, matching enforceRenderBackendPin's live-settings contract.
+ const projectPin = project?.renderBackend?.image || null;
const { mode, cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.SERIES_FIRST_PASS, {
+ recordMode: projectPin?.mode || null,
+ recordModel: projectPin?.modelId || null,
fallbackMode: IMAGE_GEN_MODE.EXTERNAL,
});
if (cloud) {
@@ -126,11 +132,11 @@ async function ingredientHasPortrait(ingredientId) {
* recorded in `skipped`, never thrown — this runs as a side-effect of auto-cast,
* so it must not fail the seeding it follows.
*/
-export async function enqueueFirstPassPortraits(members = []) {
+export async function enqueueFirstPassPortraits(members = [], project = null) {
const list = Array.isArray(members) ? members.filter((m) => m && m.ingredientId) : [];
if (list.length === 0) return { mode: null, enqueued: [], skipped: [] };
- const resolved = await resolveQueueModeParams();
+ const resolved = await resolveQueueModeParams(project);
if (!resolved.ready) {
return { mode: resolved.mode, enqueued: [], skipped: [], reason: resolved.reason };
}
@@ -217,7 +223,7 @@ export async function enqueueFirstPassSceneFrames(project) {
const scenes = Array.isArray(project?.treatment?.scenes) ? project.treatment.scenes : [];
if (scenes.length === 0) return { mode: null, enqueued: [], skipped: [] };
- const resolved = await resolveQueueModeParams();
+ const resolved = await resolveQueueModeParams(project);
if (!resolved.ready) {
return { mode: resolved.mode, enqueued: [], skipped: [], reason: resolved.reason };
}
diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.js
index 0c5736c0b9..6880cee472 100644
--- a/server/services/imageGen/cloudProviderConfig.js
+++ b/server/services/imageGen/cloudProviderConfig.js
@@ -184,17 +184,28 @@ export function renderTargetDefaults(settings, target) {
* is exactly what all seven pre-#3231 call sites did.
*
* Options:
- * - `mode` — the surface's per-request/per-record mode override
- * (e.g. `body.mode`). Wins over the target pin.
- * - `model` — per-request cloud model override. Wins over the target's
- * `imageModel` pin.
+ * - `mode` — the surface's per-request mode override (e.g.
+ * `body.mode`). Wins over every pin.
+ * - `model` — per-request cloud model override. Wins over every pin.
+ * - `recordMode` — the owning record's persisted backend pin (#3231 Phase 3
+ * — universe/series/sprite `imageMode`, normalized via
+ * `recordRenderPin`). Sits between the per-request override
+ * and the target's `renderDefaults` pin, and is
+ * usability-gated like the target pin (a since-disabled
+ * backend degrades instead of bricking the record's
+ * renders — the enforceRenderBackendPin contract).
+ * - `recordModel` — the owning record's persisted model pin. Rides only when
+ * the resolved mode is the record's pinned backend (same
+ * leak guard as the target's model pin).
* - `fallbackMode`— the surface's historical final fallback when nothing
* else resolves (EXTERNAL for batch-reject surfaces, LOCAL
* for local-first ones). Surfaces with their own usability
* ladder (resolveQueueImageMode / pickUsableMode) resolve
- * mode first — seeding the ladder with
+ * mode first — seeding the ladder with the record pin then
* `renderTargetDefaults(...).imageMode` — and pass the
- * result as `mode` here for model threading.
+ * result as `mode` here for model threading (keeping
+ * `recordMode`/`recordModel` so the leak guard still knows
+ * which backend the record pinned).
*
* Returns `{ mode, cloud }` — `cloud` is the resolveCloudProviderConfig
* bundle (null for non-cloud modes), with the layered model threaded through.
@@ -202,25 +213,29 @@ export function renderTargetDefaults(settings, target) {
export function resolveRenderTargetConfig(settings, target, {
mode = null,
model = null,
+ recordMode = null,
+ recordModel = null,
fallbackMode = null,
} = {}) {
const defaults = renderTargetDefaults(settings, target);
- // The target pin is usability-gated: a pinned backend whose enable toggle is
- // off (or that isn't queueable) falls through to the next rung instead of
- // bricking every render on this surface with a disabled-error. An explicit
+ // Pins are usability-gated: a pinned backend whose enable toggle is off (or
+ // that isn't queueable) falls through to the next rung instead of bricking
+ // every render on this surface with a disabled-error. An explicit
// per-request `mode` deliberately is NOT gated — it keeps each surface's
// existing explicit-request error semantics.
+ const recordPinnedMode = recordMode && isModeUsable(settings, recordMode) ? recordMode : null;
const pinnedMode = defaults.imageMode && isModeUsable(settings, defaults.imageMode)
? defaults.imageMode
: null;
- const finalMode = mode || pinnedMode || settings?.imageGen?.mode || fallbackMode;
- // The model pin rides WITH its backend pin: apply defaults.imageModel only
- // when the resolved mode is still the pinned backend. When the mode fell
+ const finalMode = mode || recordPinnedMode || pinnedMode || settings?.imageGen?.mode || fallbackMode;
+ // A model pin rides WITH its backend pin: apply recordModel/defaults.imageModel
+ // only when the resolved mode is still that pin's backend. When the mode fell
// back (pin disabled) or an explicit request chose another backend, the
// pinned model must not leak — codex would happily accept `--model` with a
// gemini id (supportsModelOverride gates by PROVIDER, not by id namespace).
const requestedModel = (typeof model === 'string' && model.trim()) ? model.trim() : null;
const finalModel = requestedModel
+ || (recordMode && finalMode === recordMode ? recordModel : null)
|| (defaults.imageMode && finalMode === defaults.imageMode ? defaults.imageModel : null);
return {
mode: finalMode,
diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.js
index 82042dba8f..e905620eb5 100644
--- a/server/services/imageGen/cloudProviderConfig.test.js
+++ b/server/services/imageGen/cloudProviderConfig.test.js
@@ -13,6 +13,7 @@ import {
resolveQueueImageEditMode,
resolveQueueImageMode,
} from './modes.js';
+import { recordRenderPin } from '../../lib/renderTargets.js';
const settingsWith = (imageGen) => ({ imageGen });
@@ -288,6 +289,60 @@ describe('resolveRenderTargetConfig (#3231)', () => {
expect(cloud.modelId).toBe(CODEX_IMAGEGEN_DEFAULT_MODEL);
});
+ it('a record pin beats the target pin and loses to a per-request mode (#3231 Phase 3)', () => {
+ const settings = withDefaults(
+ { mode: IMAGE_GEN_MODE.LOCAL, codex: { enabled: true }, agy: { enabled: true }, grok: { enabled: true } },
+ { 'universe-bible': { imageMode: IMAGE_GEN_MODE.AGY } },
+ );
+ expect(resolveRenderTargetConfig(settings, 'universe-bible', { recordMode: IMAGE_GEN_MODE.CODEX }).mode)
+ .toBe(IMAGE_GEN_MODE.CODEX);
+ expect(resolveRenderTargetConfig(settings, 'universe-bible', {
+ mode: IMAGE_GEN_MODE.GROK, recordMode: IMAGE_GEN_MODE.CODEX,
+ }).mode).toBe(IMAGE_GEN_MODE.GROK);
+ });
+
+ it('a record model pin rides its backend and wins over the target model pin', () => {
+ const settings = withDefaults(
+ { agy: { enabled: true } },
+ { 'universe-bible': { imageMode: IMAGE_GEN_MODE.AGY, imageModel: 'target-model' } },
+ );
+ const { cloud } = resolveRenderTargetConfig(settings, 'universe-bible', {
+ recordMode: IMAGE_GEN_MODE.AGY, recordModel: 'record-model',
+ });
+ expect(cloud.modelId).toBe('record-model');
+ expect(cloud.jobParams.model).toBe('record-model');
+ });
+
+ it('a disabled record pin falls through and takes its model with it', () => {
+ const settings = withDefaults(
+ { mode: IMAGE_GEN_MODE.CODEX, codex: { enabled: true }, agy: { enabled: false } },
+ {},
+ );
+ const { mode, cloud } = resolveRenderTargetConfig(settings, 'universe-bible', {
+ recordMode: IMAGE_GEN_MODE.AGY, recordModel: 'gemini-3.6-flash-low',
+ });
+ expect(mode).toBe(IMAGE_GEN_MODE.CODEX);
+ expect(cloud.modelId).toBe(CODEX_IMAGEGEN_DEFAULT_MODEL);
+ });
+
+ it('a pre-resolved mode matching the record pin still applies the record model', () => {
+ // Surfaces with their own usability ladder (sprites, pipeline) resolve
+ // mode first and pass it as `mode` — the record model must still ride
+ // when that mode IS the record's pinned backend.
+ const settings = withDefaults({ codex: { enabled: true } }, {});
+ const { cloud } = resolveRenderTargetConfig(settings, 'sprite-reference', {
+ mode: IMAGE_GEN_MODE.CODEX, recordMode: IMAGE_GEN_MODE.CODEX, recordModel: 'record-model',
+ });
+ expect(cloud.modelId).toBe('record-model');
+ });
+
+ it('recordRenderPin normalizes auto/blank/missing to null', () => {
+ expect(recordRenderPin(null)).toEqual({ mode: null, modelId: null });
+ expect(recordRenderPin({ imageMode: 'auto', imageModelId: ' ' })).toEqual({ mode: null, modelId: null });
+ expect(recordRenderPin({ imageMode: ` ${IMAGE_GEN_MODE.AGY} `, imageModelId: 'gemini-3.6-flash-low' }))
+ .toEqual({ mode: IMAGE_GEN_MODE.AGY, modelId: 'gemini-3.6-flash-low' });
+ });
+
it('renderTargetDefaults normalizes auto/blank/missing to null', () => {
expect(renderTargetDefaults({}, 'universe-bible')).toEqual({
imageMode: null, imageModel: null, videoMode: null, videoModel: null,
diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.js
index 8f16559791..3304d7e876 100644
--- a/server/services/pipeline/comicPages.js
+++ b/server/services/pipeline/comicPages.js
@@ -230,7 +230,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
});
}
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
const variant = resolveVariant(options.target);
// Consistency reference: pass an already-rendered page as the init image so a
@@ -301,7 +301,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
});
const jobId = enqueueImageJob({
- prompt, world, settings, mode,
+ prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },
owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),
logLine: `📄 Pipeline comic page — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} panels=${page.panels.length} variant=${variant}${fromProof ? ' (from proof)' : ''}${fromReference ? ` (${autoReference ? 'auto-ref' : 'ref'} page ${referencePageIndex + 1})` : ''}`,
@@ -469,13 +469,13 @@ export async function refineComicPageRender(issueId, options = {}) {
logTag: `Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant}`,
});
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
const initImageStrength = Number.isFinite(options.initImageStrength)
? Math.min(Math.max(options.initImageStrength, 0), 1)
: REFINE_RENDER_DEFAULT_STRENGTH;
const jobId = enqueueImageJob({
- prompt: refined, world, settings, mode,
+ prompt: refined, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildComicPagesOwner({ issueId, target: 'page', pageIndex, variant }),
logLine: `🪄 Pipeline comic page refine — issue=${issueId.slice(0, 8)} page=${pageIndex + 1} variant=${variant} strength=${initImageStrength}`,
@@ -505,7 +505,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
// characterId/wardrobeId is a client/state bug worth a 400, not the silent
// drop buildScenePrompt would otherwise apply.
assertCharacterAppearancesResolve(options.characterAppearances, canon.characters);
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
// Match on description + slugline so the featured-character set (and thus
// which wardrobe picks apply) stays consistent with the scene-video / shot
// paths and the storyboards picker UI — all of which match both fields.
@@ -543,7 +543,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
const prompt = triggerClause ? `${composedPrompt}\n\nFeaturing ${triggerClause}.` : composedPrompt;
const jobId = enqueueImageJob({
- prompt, world, settings, mode,
+ prompt, world, settings, mode, series,
options: { ...options, ...loraRenderOptions(characterLoras) },
owner: `pipeline:${issueId}:${stageId}`,
logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,
diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.js
index b1cb39bdee..ef90e2f6b2 100644
--- a/server/services/pipeline/covers.js
+++ b/server/services/pipeline/covers.js
@@ -147,7 +147,7 @@ async function enqueueComicCoverLike(issueId, target, options = {}) {
const script = typeof options[scriptOptionKey] === 'string'
? options[scriptOptionKey]
: (record?.script || '');
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
const variant = resolveVariant(options.target);
const fromProof = variant === 'final' && options.useProofAsBase === true;
const initImagePath = fromProof
@@ -162,7 +162,7 @@ async function enqueueComicCoverLike(issueId, target, options = {}) {
: composeComicBackCoverPrompt({ series, world, issue, backCoverScript: script, extraStyle });
const logTarget = target === 'cover' ? 'cover' : 'back cover';
const jobId = enqueueImageJob({
- prompt, world, settings, mode,
+ prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildComicPagesOwner({ issueId, target, variant }),
logLine: `🎨 Pipeline comic ${logTarget} — issue=${issueId.slice(0, 8)} number=${issue.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,
@@ -337,7 +337,7 @@ async function enqueueVolumeCoverLike(seriesId, seasonId, target, options = {})
const script = typeof options[scriptOptionKey] === 'string'
? options[scriptOptionKey]
: (record?.script || '');
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
const variant = resolveVariant(options.target);
const fromProof = variant === 'final' && options.useProofAsBase === true;
const initImagePath = fromProof
@@ -352,7 +352,7 @@ async function enqueueVolumeCoverLike(seriesId, seasonId, target, options = {})
: composeVolumeBackCoverPrompt({ series, world, season, backCoverScript: script, extraStyle });
const logTarget = target === 'cover' ? 'cover' : 'back cover';
const jobId = enqueueImageJob({
- prompt, world, settings, mode,
+ prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength },
owner: buildSeasonCoverOwner({ seriesId, seasonId, target, variant }),
logLine: `🎨 Pipeline volume ${logTarget} — series=${seriesId.slice(0, 8)} season=${seasonId.slice(0, 8)} vol=${season.number || 1} variant=${variant}${fromProof ? ' (from proof)' : ''}`,
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index b1c204a98a..3d0fedb700 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -21,6 +21,7 @@ import { sanitizeProseExportSettings } from '../../lib/proseExportSettings.js';
import { sanitizeSeverityWeights, sanitizeBlockingSeverities } from '../../lib/editorial/severityConfig.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+import { recordRenderPin, RECORD_RENDER_MODEL_MAX } from '../../lib/renderTargets.js';
import {
maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,
deleteSyncBaseHash,
@@ -288,6 +289,7 @@ const sanitizeSeries = (raw) => {
// behind-sender's omission is preserved (see ADDITIVE_SERIES_FIELDS).
const severityWeights = sanitizeSeverityWeights(raw.severityWeights);
const blockingSeverities = sanitizeBlockingSeverities(raw.blockingSeverities);
+ const renderPin = recordRenderPin(raw);
return {
id: raw.id,
name,
@@ -360,6 +362,15 @@ const sanitizeSeries = (raw) => {
: null,
issueCountTarget,
llm,
+ // Per-record render pin (#3231 Phase 3) — this series' default image
+ // backend + cloud model for pipeline visual renders (storyboards, comic
+ // pages, covers). Persisted only when set so existing series keep their
+ // on-disk shape. WIRE-LOCAL (an install-capability choice — the peer may
+ // not have the pinned backend configured): sanitizeRecordForWire strips
+ // the pair and ADDITIVE_SERIES_FIELDS preserves the local values on
+ // merge — no pipelineSeries schema-version bump needed.
+ ...(renderPin.mode ? { imageMode: renderPin.mode } : {}),
+ ...(renderPin.modelId ? { imageModelId: renderPin.modelId.slice(0, RECORD_RENDER_MODEL_MAX) } : {}),
// Share-bucket provenance — present on imported records, absent on locally-authored ones.
origin: sanitizeOrigin(raw.origin),
createdAt,
@@ -437,6 +448,10 @@ export async function createSeries(input = {}) {
targetFormat: input.targetFormat || 'comic+tv',
issueCountTarget: input.issueCountTarget || 0,
llm: input.llm || null,
+ // Per-record render pin (#3231 Phase 3) — sanitizeSeries persists the
+ // pair only when actually set.
+ imageMode: input.imageMode || null,
+ imageModelId: input.imageModelId || null,
createdAt: now,
updatedAt: now,
ephemeral: input.ephemeral === true,
@@ -625,6 +640,10 @@ export async function updateSeries(id, patch = {}) {
...('authorId' in patch ? { authorId: patch.authorId } : {}),
...('stylePromptOverride' in patch ? { stylePromptOverride: patch.stylePromptOverride } : {}),
...('stylePromptOverrideMode' in patch ? { stylePromptOverrideMode: patch.stylePromptOverrideMode } : {}),
+ // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/null
+ // clears (sanitizeSeries drops the field); key-absent preserves.
+ ...('imageMode' in patch ? { imageMode: patch.imageMode } : {}),
+ ...('imageModelId' in patch ? { imageModelId: patch.imageModelId } : {}),
...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),
...('primaryManuscriptType' in patch ? { primaryManuscriptType: patch.primaryManuscriptType } : {}),
...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),
@@ -856,7 +875,7 @@ async function cascadeDeleteSideEffects(id) {
// consult the RAW remote payload to tell the two apart: key absent → preserve
// local; key present (even null/empty) → honor the intentional clear. Mirrors
// the `universeId` hierarchy guard. See issue #1361.
-const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig', 'severityWeights', 'blockingSeverities', 'exportSettings'];
+const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig', 'severityWeights', 'blockingSeverities', 'exportSettings', 'imageMode', 'imageModelId'];
// Additive sub-fields nested inside `arc`. A peer that predates these (readerMap
// shipped at schema v2, tickingClock at #1289/v3, foreshadowing at #2172/v10)
// still sends an `arc` object — just without these keys — so the erasure for
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index cb7730a23a..dee3aba0da 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -257,6 +257,27 @@ describe('pipeline series service', () => {
expect(after.universeId).toBe('uni-A'); // …but the link was preserved
});
+ it('round-trips the per-record render pin and preserves it across a wire-stripped merge (#3231 Phase 3)', async () => {
+ const s = await svc.createSeries({ name: 'Pinned', imageMode: 'agy', imageModelId: 'gemini-3.6-flash-low' });
+ expect(s.imageMode).toBe('agy');
+ expect(s.imageModelId).toBe('gemini-3.6-flash-low');
+ // 'auto' clears the mode pin; absent preserves the model pin.
+ const cleared = await svc.updateSeries(s.id, { imageMode: 'auto' });
+ expect(cleared.imageMode).toBeUndefined();
+ expect(cleared.imageModelId).toBe('gemini-3.6-flash-low');
+ await svc.updateSeries(s.id, { imageMode: 'codex' });
+ // Inbound remote edit (wire-stripped — no pin fields) must not erase the
+ // local pin (ADDITIVE_SERIES_FIELDS).
+ const local = await svc.getSeries(s.id);
+ const { imageMode: _im, imageModelId: _imid, ...wireForm } = local;
+ const res = await svc.mergeSeriesFromSync([{ ...wireForm, name: 'Pinned (peer edit)', updatedAt: '2999-01-01T00:00:00.000Z' }]);
+ expect(res.applied).toBe(true);
+ const after = await svc.getSeries(s.id);
+ expect(after.name).toBe('Pinned (peer edit)');
+ expect(after.imageMode).toBe('codex');
+ expect(after.imageModelId).toBe('gemini-3.6-flash-low');
+ });
+
it('mergeSeriesFromSync still applies a MOVE to a different non-empty universe', async () => {
const s = await svc.createSeries({ name: 'Mover', universeId: 'uni-A' });
const movePayload = { ...s, universeId: 'uni-B', updatedAt: '2999-01-01T00:00:00.000Z' };
diff --git a/server/services/pipeline/storyboards.js b/server/services/pipeline/storyboards.js
index ba03a7b415..1d69d4836a 100644
--- a/server/services/pipeline/storyboards.js
+++ b/server/services/pipeline/storyboards.js
@@ -158,7 +158,7 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI
});
}
- const mode = resolveMode(options, settings);
+ const mode = resolveMode(options, settings, series);
const matchedCharacters = matchCharactersInText(
`${description} ${scene.slugline || ''}`,
canon.characters,
@@ -176,7 +176,7 @@ export async function enqueueStoryboardShotStartFrame(issueId, sceneIndex, shotI
});
const jobId = enqueueImageJob({
- prompt, world, settings, options, mode,
+ prompt, world, settings, options, mode, series,
owner: buildStoryboardsShotOwner({ issueId, sceneIndex: sIdx, shotIndex: tIdx }),
logLine: `🎞️ Pipeline shot start-frame — issue=${issueId.slice(0, 8)} scene=${sIdx + 1} shot=${tIdx + 1}`,
});
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index dcc80e8bce..f0b923f19b 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -23,7 +23,7 @@ import { resolveCharacterLoras } from '../characterLoraResolver.js';
import { pickCanon } from './seriesCanon.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
import { pickUsableMode, renderTargetDefaults, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
-import { RENDER_TARGET } from '../../lib/renderTargets.js';
+import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { resolveImageCleaners } from '../imageGen/index.js';
const joinStyleParts = (...parts) =>
@@ -73,8 +73,12 @@ const applyWorldStyle = (prompt, world, series = null) => {
// one first; this is the wider param-assembly consolidation from #2881.)
// The pipeline-visual renderDefaults pin (#3231) slots between the explicit
// per-request override and the install default — usability-gated like both.
-const resolveMode = (options, settings) => pickUsableMode(settings, [
+// The series' persisted per-record pin (#3231 Phase 3) sits between the
+// per-request override and the install-wide target pin: "this series renders
+// on codex" beats the surface default, loses to an explicit UI selection.
+const resolveMode = (options, settings, series = null) => pickUsableMode(settings, [
options.mode,
+ recordRenderPin(series).mode,
renderTargetDefaults(settings, RENDER_TARGET.PIPELINE_VISUAL).imageMode,
settings?.imageGen?.mode,
]);
@@ -218,7 +222,7 @@ const loadBibleContext = async (issueId) => {
return { ...chain, settings };
};
-const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine }) => {
+const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine, series = null }) => {
// Merge user + world negatives — mirrors composeStyledPrompt's preset
// negative handling so the world's global negative-prompt terms stay in
// effect even when the caller supplies their own additions. Deduplicated
@@ -259,8 +263,15 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
// effect on storyboard, comic-panel, or cover renders.
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
// Mode is already resolved through the ladder above; this call threads the
- // pipeline-visual renderDefaults imageModel into the cloud job params.
- const { cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.PIPELINE_VISUAL, { mode });
+ // series' persisted imageModelId pin (#3231 Phase 3), then the
+ // pipeline-visual renderDefaults imageModel, into the cloud job params —
+ // each riding only when the resolved mode is still its pinned backend.
+ const seriesPin = recordRenderPin(series);
+ const { cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.PIPELINE_VISUAL, {
+ mode,
+ recordMode: seriesPin.mode,
+ recordModel: seriesPin.modelId,
+ });
const params = cloud
? { ...cloud.jobParams, cleanC2PA, denoise, ...baseParams }
: { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };
diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.js
index df930c86f3..0f46a0f6a8 100644
--- a/server/services/sprites/recordsLogic.js
+++ b/server/services/sprites/recordsLogic.js
@@ -43,6 +43,13 @@ export function mirrorTimestamp(value, fallback) {
const trimOrNull = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
+// Per-record render-pin mode (#3231 Phase 3): the 'auto' UI sentinel means
+// "no pin" and is stored as null, matching recordRenderPin's normalization.
+const pinModeOrNull = (v) => {
+ const t = trimOrNull(v);
+ return t && t !== 'auto' ? t : null;
+};
+
export function buildSpriteRecord(input, { id, now }) {
const kind = SPRITE_RECORD_KINDS.includes(input.kind) ? input.kind : 'character';
return {
@@ -65,6 +72,11 @@ export function buildSpriteRecord(input, { id, now }) {
? input.importedFrom
: null,
notes: trimOrNull(input.notes),
+ // Per-record render pin (#3231 Phase 3) — this sprite's default image
+ // backend + cloud model for reference renders. null = no pin (fall
+ // through to renderDefaults / the install default).
+ imageMode: pinModeOrNull(input.imageMode),
+ imageModelId: trimOrNull(input.imageModelId),
createdAt: now,
updatedAt: now,
deleted: false,
@@ -74,7 +86,7 @@ export function buildSpriteRecord(input, { id, now }) {
// Whitelist patch — key-absent preserves, key-present applies (including an
// intentional clear via null/''), per the LLM/merge convention in CLAUDE.md.
-const PATCHABLE = ['name', 'status', 'kind', 'spec', 'chromaKey', 'publishBinding', 'notes'];
+const PATCHABLE = ['name', 'status', 'kind', 'spec', 'chromaKey', 'publishBinding', 'notes', 'imageMode', 'imageModelId'];
export function applySpriteRecordPatch(record, patch) {
const next = { ...record };
@@ -88,7 +100,10 @@ export function applySpriteRecordPatch(record, patch) {
else if (key === 'kind') next.kind = SPRITE_RECORD_KINDS.includes(patch.kind) ? patch.kind : record.kind;
else if (key === 'spec' || key === 'publishBinding') {
next[key] = patch[key] && typeof patch[key] === 'object' ? patch[key] : null;
- } else next[key] = trimOrNull(patch[key]);
+ // 'auto' (the UI's "no pin" sentinel) clears like null/'' — key-present
+ // always applies per the whitelist-patch convention above.
+ } else if (key === 'imageMode') next.imageMode = pinModeOrNull(patch.imageMode);
+ else next[key] = trimOrNull(patch[key]);
}
next.updatedAt = new Date().toISOString();
return next;
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 9910cf56e9..6bfe165489 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -37,7 +37,7 @@ import {
} from '../imageGen/modes.js';
import { resolveImageCleaners } from '../imageGen/index.js';
import { renderTargetDefaults, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
-import { RENDER_TARGET } from '../../lib/renderTargets.js';
+import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { getSettings } from '../settings.js';
import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';
import { spriteDir, resolveSpriteAssetPath, listSpriteAssets } from './paths.js';
@@ -387,11 +387,13 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
// fork subsequent renders onto a different background than the frozen set.
const genKey = manifest.chromaKey || record.chromaKey || DEFAULT_CHROMA_KEY;
const settings = await getSettings();
- // Render-target ladder (#3231): the page's explicit body.mode wins, then the
- // sprite-reference pin in settings.renderDefaults, both gated through the
- // usability ladder (a pinned-but-disabled backend falls through).
+ // Render-target ladder (#3231): the page's explicit body.mode wins, then
+ // the sprite record's persisted pin (Phase 3), then the sprite-reference
+ // pin in settings.renderDefaults — all gated through the usability ladder
+ // (a pinned-but-disabled backend falls through).
+ const spritePin = recordRenderPin(record);
let mode = resolveQueueImageMode(
- body.mode || renderTargetDefaults(settings, RENDER_TARGET.SPRITE_REFERENCE).imageMode,
+ body.mode || spritePin.mode || renderTargetDefaults(settings, RENDER_TARGET.SPRITE_REFERENCE).imageMode,
settings,
);
@@ -546,19 +548,29 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
// The model the provider will ACTUALLY run, for candidate provenance —
// grok picks its model internally, so its sidecars record null. body.model
- // (a per-render override) wins over the sprite-reference renderDefaults pin,
- // which wins over the provider's saved default (#3231).
+ // (a per-render override) wins over the record's imageModelId pin (Phase 3),
+ // which wins over the sprite-reference renderDefaults pin, which wins over
+ // the provider's saved default (#3231). Each pin rides only while the
+ // resolved mode is still its pinned backend (the resolver's leak guard).
const { cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.SPRITE_REFERENCE, {
mode,
model: body.model,
+ recordMode: spritePin.mode,
+ recordModel: spritePin.modelId,
});
const cloudJobParams = mode === IMAGE_GEN_MODE.CODEX
? { ...cloud?.jobParams, effort: body.effort || settings.imageGen?.codex?.effort }
: cloud?.jobParams;
+ // Local mode mirrors the cloud leak guard by hand: the record's model pin
+ // applies only when the record pinned local (or nothing) — a gemini id
+ // pinned for a cloud backend must not become an mflux modelId.
+ const localPinModel = (!spritePin.mode || spritePin.mode === IMAGE_GEN_MODE.LOCAL)
+ ? spritePin.modelId
+ : null;
const effectiveModel = mode === IMAGE_GEN_MODE.CODEX || mode === IMAGE_GEN_MODE.AGY
? cloud.modelId
: mode === IMAGE_GEN_MODE.LOCAL
- ? (body.model || settings.imageGen?.local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL)
+ ? (body.model || localPinModel || settings.imageGen?.local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL)
: null;
const baseParams = {
prompt,
@@ -747,6 +759,14 @@ export async function listSpriteThumbnails() {
export async function forkSprite(sourceId, body) {
await resolveSourceReference(sourceId); // fail fast before creating a record
const record = await createCharacter({ name: body.name, id: body.id, kind: 'character' });
+ // Persist the fork's chosen backend/model as the NEW record's render pin
+ // (#3231 Phase 3) so re-rolls keep rendering where the fork was made.
+ if (body.mode || body.model) {
+ await updateRecord(record.id, {
+ ...(body.mode ? { imageMode: body.mode } : {}),
+ ...(body.model ? { imageModelId: body.model } : {}),
+ });
+ }
const gen = await startReferenceGeneration(record.id, {
target: TURNAROUND_ID,
designPrompt: body.designPrompt,
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index a684184cd0..6813b43424 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -1209,6 +1209,24 @@ describe("universeBuilder service", () => {
// …but local probe renders survived.
expect(after.styleImageRefs).toEqual(["probe-1.png", "probe-2.png"]);
});
+
+ it("preserves the local render pin across a remote-wins LWW edit (#3231 Phase 3)", async () => {
+ // imageMode/imageModelId are wire-local like styleImageRefs — a peer's
+ // edit to other fields must not clear this machine's pinned backend.
+ const w = await seedWorld();
+ await svc.updateUniverse(w.id, { imageMode: "agy", imageModelId: "gemini-3.6-flash-low" });
+ const editTs = new Date(Date.now() + 60_000).toISOString();
+ const r = await svc.mergeUniversesFromSync([{
+ ...w,
+ name: "Remote Edited Name",
+ updatedAt: editTs,
+ }]);
+ expect(r.applied).toBe(true);
+ const after = await svc.getUniverse(w.id);
+ expect(after.name).toBe("Remote Edited Name");
+ expect(after.imageMode).toBe("agy");
+ expect(after.imageModelId).toBe("gemini-3.6-flash-low");
+ });
});
describe("pruneTombstonedUniverses", () => {
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 6fbe4ab883..5eeb077651 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -187,6 +187,10 @@ export async function createUniverse(input = {}) {
influences: input.influences || {},
styleReferences: input.styleReferences || [],
styleImageRefs: input.styleImageRefs || [],
+ // Per-record render pin (#3231 Phase 3) — sanitizeTemplate persists the
+ // pair only when actually set.
+ imageMode: input.imageMode || null,
+ imageModelId: input.imageModelId || null,
locked: input.locked || {},
// Canon registries — let callers seed a universe at creation time
// (writers-room promote, share-bucket import). sanitizeTemplate runs
@@ -418,6 +422,9 @@ export async function updateUniverse(id, patchOrMutator = {}, options = {}) {
'styleReferences',
// Base style-probe render refs — patched wholesale (sanitizer re-caps).
'styleImageRefs',
+ // Per-record render pin (#3231 Phase 3). Key-present with 'auto'/null
+ // clears (sanitizeTemplate drops the field); key-absent preserves.
+ 'imageMode', 'imageModelId',
// Canon entity arrays — patched wholesale (the sanitizer reruns
// sanitizeBibleList so per-entry shape is enforced on every save).
'characters', 'places', 'objects',
diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.js
index 0b01ce1689..dbbdc9a232 100644
--- a/server/services/universeBuilder/sanitize.js
+++ b/server/services/universeBuilder/sanitize.js
@@ -18,6 +18,7 @@ import {
} from '../../lib/storyBible.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
+import { recordRenderPin, RECORD_RENDER_MODEL_MAX } from '../../lib/renderTargets.js';
// RECORD-shape schema version, stamped INSIDE each universe record. Distinct
// from the type-level (storage layout) schemaVersion carried by
@@ -705,6 +706,7 @@ export const sanitizeTemplate = (raw) => {
const compositeSheets = sanitizeCompositeSheets(raw.compositeSheets || []);
const influences = resolveInfluences(raw);
const locked = sanitizeLocked(raw.locked);
+ const renderPin = recordRenderPin(raw);
// Canon registries. Two passes:
// 1. foldRetiredCharactersBucket — Phase A retirement contract. ALWAYS
// runs (regardless of schemaVersion) so a `categories.characters`
@@ -767,6 +769,15 @@ export const sanitizeTemplate = (raw) => {
// conflict-journal content hash (which reuses that projection). Per-peer +
// one-click to regenerate, so no schema-version gate is needed.
styleImageRefs: sanitizeEntryImageRefs(raw.styleImageRefs),
+ // Per-record render pin (#3231 Phase 3) — this universe's default image
+ // backend + cloud model for bible/character-sheet renders. Persisted only
+ // when set ('auto'/blank/absent collapse to absent) so every existing
+ // universe keeps its on-disk shape. WIRE-LOCAL like styleImageRefs: a
+ // pinned backend is an install-capability choice (a peer may not have
+ // codex/agy configured), so sanitizeRecordForWire strips the pair and the
+ // sync merge restores the local values — no schema-version gate needed.
+ ...(renderPin.mode ? { imageMode: renderPin.mode } : {}),
+ ...(renderPin.modelId ? { imageModelId: renderPin.modelId.slice(0, RECORD_RENDER_MODEL_MAX) } : {}),
locked,
characters,
places,
diff --git a/server/services/universeBuilder/sync.js b/server/services/universeBuilder/sync.js
index e8d8859f7c..36caa9d961 100644
--- a/server/services/universeBuilder/sync.js
+++ b/server/services/universeBuilder/sync.js
@@ -130,6 +130,12 @@ export async function mergeUniversesFromSync(remoteUniverses, { source = { via:
// shift the journal's divergence verdict). Mirror of the ephemeral
// local-only contract above.
sanitized.styleImageRefs = local.styleImageRefs ?? [];
+ // The per-record render pin (#3231 Phase 3) is wire-local too —
+ // restore the local pair so a remote-wins LWW write can't clear this
+ // machine's pinned backend/model (the fields are persisted only when
+ // set, so absent-locally stays absent).
+ if (local.imageMode) sanitized.imageMode = local.imageMode;
+ if (local.imageModelId) sanitized.imageModelId = local.imageModelId;
// Non-blocking conflict journal: archive the about-to-be-lost local
// version when BOTH sides diverged from the last synced base. Always
// advances the base hash (clean or conflict) so the next snapshot
diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.js
index be61822f47..752bd07e66 100644
--- a/server/services/universeBuilderRender.js
+++ b/server/services/universeBuilderRender.js
@@ -20,7 +20,7 @@ import { getImageModels, isFlux2 } from '../lib/mediaModels.js';
import { usesDiffusersRunner } from '../lib/runners.js';
import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from './imageGen/modes.js';
import { resolveRenderTargetConfig } from './imageGen/cloudProviderConfig.js';
-import { RENDER_TARGET } from '../lib/renderTargets.js';
+import { RENDER_TARGET, recordRenderPin } from '../lib/renderTargets.js';
import { resolveImageCleaners } from './imageGen/index.js';
import { getStylePresetById } from '../lib/writersRoomStylePresets.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -60,10 +60,16 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
}
const settings = await getSettings();
- // Render-target ladder (#3231): body.mode → the universe-bible pin in
- // settings.renderDefaults → the install default → external (rejected below).
+ // Render-target ladder (#3231): body.mode → the universe's persisted pin
+ // (Phase 3) → the universe-bible pin in settings.renderDefaults → the
+ // install default → external (rejected below). body.cloudModel wins over
+ // the record's imageModelId pin the same way.
+ const renderPin = recordRenderPin(universe);
const { mode, cloud } = resolveRenderTargetConfig(settings, RENDER_TARGET.UNIVERSE_BIBLE, {
mode: body.mode,
+ model: body.cloudModel,
+ recordMode: renderPin.mode,
+ recordModel: renderPin.modelId,
fallbackMode: IMAGE_GEN_MODE.EXTERNAL,
});
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index 2023325182..615c471d9d 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -25,7 +25,7 @@ import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';
import { buildUniverseRunTag } from './universeRunTag.js';
import { IMAGE_GEN_MODE } from './imageGen/modes.js';
import { resolveRenderTargetConfig } from './imageGen/cloudProviderConfig.js';
-import { RENDER_TARGET } from '../lib/renderTargets.js';
+import { RENDER_TARGET, recordRenderPin } from '../lib/renderTargets.js';
import {
flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,
} from '../lib/canonPrompt.js';
@@ -418,9 +418,13 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
// the media-job queue with the active mode set; codex and local are both
// first-class. External SD-API has no multi-zone layout support, so it
// gets a clear remediation rather than a silently-degraded render.
- // Render-target ladder (#3231): the universe-character-sheet pin in
- // settings.renderDefaults → the install default → local.
+ // Render-target ladder (#3231): the universe's persisted pin (Phase 3) →
+ // the universe-character-sheet pin in settings.renderDefaults → the install
+ // default → local.
+ const renderPin = recordRenderPin(universe);
const sheetTarget = resolveRenderTargetConfig(settings, RENDER_TARGET.UNIVERSE_CHARACTER_SHEET, {
+ recordMode: renderPin.mode,
+ recordModel: renderPin.modelId,
fallbackMode: IMAGE_GEN_MODE.LOCAL,
});
const activeMode = sheetTarget.mode;