Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-3231]): dedupe render-pin normalization and reuse the shared pin row
[._.]/ Adam Eivy04e9c7fab645
diff --git a/client/src/components/imageGen/RecordRenderPinRow.jsx b/client/src/components/imageGen/RecordRenderPinRow.jsxindex 3f522a4a98..b0d330f74e 100644--- a/client/src/components/imageGen/RecordRenderPinRow.jsx+++ b/client/src/components/imageGen/RecordRenderPinRow.jsx@@ -1,4 +1,5 @@import { IMAGE_GEN_MODE, RENDER_TARGET_BACKEND_AUTO, modeLabel, supportsCloudModelOverride } from '../../lib/imageGenBackends';+import useFieldDraft from '../../hooks/useFieldDraft';const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.AGY];@@ -12,6 +13,9 @@ const DEFAULT_MODES = [IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MOD// `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.+// `options` (`[{ id, label }]`) swaps in a host-derived backend list (e.g. the+// sprites page's availability-filtered set); `showAuto={false}` drops the+// "Auto" entry for hosts whose picker always names a concrete backend.export default function RecordRenderPinRow({idPrefix,label = 'Render backend',@@ -19,9 +23,15 @@ export default function RecordRenderPinRow({imageModelId = null,onChange,modes = DEFAULT_MODES,+ options = null,autoLabel = 'Auto (default)',+ showAuto = true,}) {const pinnedMode = imageMode && imageMode !== RENDER_TARGET_BACKEND_AUTO ? imageMode : '';+ const optionList = options || modes.map((m) => ({ id: m, label: modeLabel(m) }));+ const modelDraft = useFieldDraft(imageModelId, (v) => {+ onChange({ imageMode: pinnedMode || null, imageModelId: v.trim() || null });+ });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>@@ -31,19 +41,16 @@ export default function RecordRenderPinRow({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>)}+ {showAuto ? <option value="">{autoLabel}</option> : (!pinnedMode && <option value="" disabled>Pick a backend</option>)}+ {optionList.map((o) => <option key={o.id} value={o.id}>{o.label || o.id}</option>)}</select>{supportsCloudModelOverride(pinnedMode) ? (<inputid={`${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 });- }}+ value={modelDraft.value}+ onChange={modelDraft.onChange}+ onBlur={modelDraft.onBlur}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"diff --git a/client/src/components/sprites/ReferenceWorkflow.jsx b/client/src/components/sprites/ReferenceWorkflow.jsxindex 69f1f78b95..abc4609de0 100644--- a/client/src/components/sprites/ReferenceWorkflow.jsx+++ b/client/src/components/sprites/ReferenceWorkflow.jsx@@ -18,7 +18,7 @@ import CorrectionNote, {} from './CorrectionNote.jsx';import FilePickerButton from '../ui/FilePickerButton';import { IMAGE_ACCEPT } from '../../utils/fileUpload';-import { supportsCloudModelOverride } from '../../lib/imageGenBackends';+import RecordRenderPinRow from '../imageGen/RecordRenderPinRow.jsx';// Reference workflow (issues #2896, #2979): three ordered steps — generate a// turnaround sheet from text + an optional design image and freeze it, derive@@ -200,6 +200,11 @@ function StageHeading({ id, number, title, status, statusTone = 'text-gray-500'export default function ReferenceWorkflow({ record, reference, renders, corrections, onCorrectionChange, backends, trackDefinitions, mode, onModeChange, onChanged, onForked }) {const recordId = record.id;+ // Local shadow of record.imageModelId (#3231 Phase 3) — pin PATCHes update+ // this directly instead of refetching the whole detail payload; re-seeded+ // when the user switches records.+ const [modelPin, setModelPin] = useState(record.imageModelId || null);+ useEffect(() => { setModelPin(record.imageModelId || null); }, [recordId, record.imageModelId]);const manifest = reference?.manifest || null;const candidates = reference?.candidates || [];const mainLocked = manifest?.mainReference?.locked === true;@@ -440,49 +445,26 @@ export default function ReferenceWorkflow({ record, reference, renders, correcti}, { errorMessage: 'Failed to set chroma key' });const noBackend = Array.isArray(backends) && backends.length === 0;+ // Backend + model picker, persisted onto THIS record as its render pin+ // (#3231 Phase 3) so re-rolls and future sessions render where the user+ // chose. `modelPin` shadows record.imageModelId locally — the PATCH already+ // holds the new value, so no detail refetch is needed (the useUniverseDraft+ // setRenderPin pattern).const modePicker = Array.isArray(backends) && backends.length > 0 && (- <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>+ <RecordRenderPinRow+ idPrefix={`sprite-render-pin-${recordId}`}+ label="Backend"+ imageMode={mode}+ imageModelId={modelPin}+ options={backends}+ showAuto={false}+ onChange={({ imageMode, imageModelId }) => {+ if (imageMode && imageMode !== mode) onModeChange(imageMode);+ setModelPin(imageModelId);+ updateSpriteRecord(recordId, { imageMode, imageModelId }, { silent: true })+ .catch((err) => toast.error(`Render pin save failed: ${err.message}`));+ }}+ />);const turnaroundCandidates = candidatesByTarget.turnaround || [];const mainCandidates = candidatesByTarget.main || [];diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsxindex e904d5a8dc..564e7e9ddd 100644--- a/client/src/pages/Sprites.jsx+++ b/client/src/pages/Sprites.jsx@@ -413,15 +413,7 @@ export default function Sprites() {setDetail((prev) => (prev?.record?.id === id ? prev : null));setDetailState('loading');getSpriteRecord(id, { silent: true })- .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);- })+ .then((d) => { if (!stale) { setDetail(d); setDetailState('loaded'); } }).catch((err) => { if (!stale) setDetailState(err?.status === 404 || err?.status === 400 ? 'missing' : 'error'); });return () => { stale = true; };}, [id, retryTick]);@@ -526,6 +518,19 @@ export default function Sprites() {}, []);const hasImageBackend = Array.isArray(imageBackends) && imageBackends.length > 0;+ // Seed the page-owned backend picker from an opened record's persisted+ // render pin (#3231 Phase 3) — but only when that backend is actually+ // available, so a pinned-but-since-disabled backend degrades to the server+ // ladder's graceful fallback instead of being sent as an explicit (and+ // erroring) body.mode. Unpinned records keep the current page mode.+ const detailPinMode = detail?.record?.imageMode || '';+ const detailRecordId = detail?.record?.id || '';+ useEffect(() => {+ if (detailPinMode && (imageBackends || []).some((b) => b.id === detailPinMode)) {+ setImageMode(detailPinMode);+ }+ }, [detailPinMode, detailRecordId, imageBackends]);+// Run ids the walk selection has approved. An approved run's strip/frames// never move on disk (approval is recorded in the selection, not the path),// so the pure path classifier still reads them as `candidate` — the assetdiff --git a/server/lib/renderTargets.js b/server/lib/renderTargets.jsindex 29e3c78a8d..e75a714126 100644--- a/server/lib/renderTargets.js+++ b/server/lib/renderTargets.js@@ -39,21 +39,42 @@ export const RENDER_TARGET_BACKEND_AUTO = 'auto';// creative-commission `COMMISSION_RENDER_MODEL_MAX` convention.export const RECORD_RENDER_MODEL_MAX = 64;+// The ONE normalization rule for render-pin values, shared by the per-record+// pin below and the settings-registry reader (renderTargetDefaults in+// imageGen/cloudProviderConfig.js): trim; the `'auto'` sentinel and blank+// strings collapse to null ("no pin — fall through").+export const normalizeRenderPinValue = (v) => {+ const s = typeof v === 'string' ? v.trim() : '';+ return s && s !== RENDER_TARGET_BACKEND_AUTO ? s : null;+};+/*** 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.+ * `recordMode` / `recordModel` options without re-checking sentinels. The+ * model id is capped here so every record kind persists the same bounded+ * shape.*/export function recordRenderPin(record) {- const norm = (v) => {- const s = typeof v === 'string' ? v.trim() : '';- return s && s !== RENDER_TARGET_BACKEND_AUTO ? s : null;+ const modelId = normalizeRenderPinValue(record?.imageModelId);+ return {+ mode: normalizeRenderPinValue(record?.imageMode),+ modelId: modelId ? modelId.slice(0, RECORD_RENDER_MODEL_MAX) : null,};+}++/**+ * The persist-only-when-set spread for a record sanitizer (#3231 Phase 3) —+ * returns `{ imageMode?, imageModelId? }` with each key present only when a+ * real pin exists, so existing records keep their on-disk shape byte-stable.+ */+export function persistedRenderPinFields(raw) {+ const pin = recordRenderPin(raw);return {- mode: norm(record?.imageMode),- modelId: norm(record?.imageModelId),+ ...(pin.mode ? { imageMode: pin.mode } : {}),+ ...(pin.modelId ? { imageModelId: pin.modelId } : {}),};}diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 99fad307b8..c13366b797 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -143,28 +143,21 @@ export function sanitizeRecordForWire(kind, record) {// 412-reject ALL universe transfers over a low-stakes, one-click-regenerable// 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') {- // `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) };+ // `imageMode`/`imageModelId` (#3231 Phase 3 per-record render pin, on+ // universes AND series) 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 sync flowing to pre-field peers without a+ // whole-category schema gate. The receive side restores the local+ // values (universeBuilder/sync.js for universes; ADDITIVE_SERIES_FIELDS+ // for series).+ if (kind === 'universe' || kind === 'series') {+ const { imageMode: _imageMode, imageModelId: _imageModelId, ...noPinRest } = rest;+ if (kind === 'universe') {+ const { styleImageRefs: _styleImageRefs, ...universeRest } = noPinRest;+ return { ...universeRest, ...sanitizeSoftDeleteFields(record) };+ }+ return { ...noPinRest, ...sanitizeSoftDeleteFields(record) };}return { ...rest, ...sanitizeSoftDeleteFields(record) };}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex d4f297ecad..16c5bb210f 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -979,8 +979,9 @@ export const imageGenGrokSettingsSchema = z.object({// Shared "valid model id" base — one definition of the shape a cloud-CLI// model id may take (bounds + charset), derived per consumer below so a-// future tweak (e.g. allowing `@`) lands everywhere at once.-const cloudModelIdString = (message) => z.string().trim().max(200)+// future tweak (e.g. allowing `@`) lands everywhere at once. Exported for+// route schemas that carry a one-off model override (universe renderSchema).+export const cloudModelIdString = (message) => z.string().trim().max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/, message);const agyImageModelSchema = z.preprocess(diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 9dd24f8994..25e5b65028 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -21,7 +21,8 @@import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError, createServiceErrorMapper } from '../lib/errorHandler.js';-import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields } from '../lib/validation.js';+import { validateRequest, optionalBooleanMap, llmSchema, isPaginationRequested, paginateArray, recordRenderPinFields, cloudModelIdString } from '../lib/validation.js';+import { RECORD_RENDER_MODEL_MAX } from '../lib/renderTargets.js';import * as svc from '../services/universeBuilder.js';import * as canonSvc from '../services/universeCanon.js';import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';@@ -358,8 +359,9 @@ const renderSchema = z.object({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(),+ // persisted imageModelId pin and the renderDefaults imageModel pin. Shares+ // the model-id charset guard so a bad id can't reach a CLI argv.+ cloudModel: cloudModelIdString('cloudModel must be a valid model id').max(RECORD_RENDER_MODEL_MAX).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/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex 6880cee472..5aec7d13b9 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -17,7 +17,7 @@*/import { ServerError } from '../../lib/errorHandler.js';-import { RENDER_TARGET_BACKEND_AUTO } from '../../lib/renderTargets.js';+import { normalizeRenderPinValue } from '../../lib/renderTargets.js';import {AGY_IMAGEGEN_DEFAULT_MODEL,CLOUD_IMAGE_GEN_MODES,@@ -160,15 +160,11 @@ export function pickUsableMode(settings, candidates = []) {*/export function renderTargetDefaults(settings, target) {const d = settings?.renderDefaults?.[target] || {};- const norm = (v) => {- const s = typeof v === 'string' ? v.trim() : '';- return s && s !== RENDER_TARGET_BACKEND_AUTO ? s : null;- };return {- imageMode: norm(d.imageMode),- imageModel: norm(d.imageModel),- videoMode: norm(d.videoMode),- videoModel: norm(d.videoModel),+ imageMode: normalizeRenderPinValue(d.imageMode),+ imageModel: normalizeRenderPinValue(d.imageModel),+ videoMode: normalizeRenderPinValue(d.videoMode),+ videoModel: normalizeRenderPinValue(d.videoModel),};}diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 3d0fedb700..ee01a41fd9 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -21,7 +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 { persistedRenderPinFields } from '../../lib/renderTargets.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes,deleteSyncBaseHash,@@ -289,7 +289,6 @@ 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,@@ -369,8 +368,7 @@ const sanitizeSeries = (raw) => {// 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) } : {}),+ ...persistedRenderPinFields(raw),// Share-bucket provenance — present on imported records, absent on locally-authored ones.origin: sanitizeOrigin(raw.origin),createdAt,diff --git a/server/services/sprites/records.js b/server/services/sprites/records.jsindex e489cd6362..ea4a4b217d 100644--- a/server/services/sprites/records.js+++ b/server/services/sprites/records.js@@ -58,7 +58,7 @@ export async function createRecord(input, id) {* `props` families stay import-only. Only character records unlock the* reference → walk → publish workflows (gated client-side on kind).*/-export async function createCharacter({ id, name, spec = null, kind = 'character' }) {+export async function createCharacter({ id, name, spec = null, kind = 'character', imageMode = null, imageModelId = null }) {const recordId = id || deriveSpriteId(name);if (!isValidSpriteId(recordId)) {throw new ServerError(`Cannot derive a valid sprite id from "${name}" — pass an explicit id`, { status: 400, code: 'INVALID_SPRITE_ID' });@@ -73,7 +73,10 @@ export async function createCharacter({ id, name, spec = null, kind = 'character// buildSpriteRecord validates kind against SPRITE_RECORD_KINDS and falls// back to 'character' for anything unexpected — the Zod schema enum-gates it// before this point, so an out-of-set value can't reach here from the route.- return createRecord({ kind, name, spec }, recordId);+ // The render pin (#3231 Phase 3) is seedable at create time so a fork+ // persists its chosen backend/model in the same write that creates the+ // record — buildSpriteRecord normalizes the pair.+ return createRecord({ kind, name, spec, imageMode, imageModelId }, recordId);}export async function updateRecord(id, patch) {diff --git a/server/services/sprites/recordsLogic.js b/server/services/sprites/recordsLogic.jsindex 0f46a0f6a8..b3b376bdb3 100644--- a/server/services/sprites/recordsLogic.js+++ b/server/services/sprites/recordsLogic.js@@ -18,6 +18,11 @@export const SPRITE_RECORD_KINDS = ['character', 'place', 'object', 'props'];+// The one import is lib/renderTargets.js, itself a dependency-free leaf, so+// this module stays safe to import from mocked suites (see the note on+// SPRITE_ID_PATTERN in lib/validation.js).+import { recordRenderPin } from '../../lib/renderTargets.js';+// Record ids double as the on-disk directory name under data/sprites/ — keep// them strict kebab-case so a record id can never traverse the filesystem.export const SPRITE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;@@ -43,13 +48,6 @@ 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 {@@ -75,8 +73,8 @@ export function buildSpriteRecord(input, { id, now }) {// 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),+ imageMode: recordRenderPin(input).mode,+ imageModelId: recordRenderPin(input).modelId,createdAt: now,updatedAt: now,deleted: false,@@ -101,8 +99,11 @@ export function applySpriteRecordPatch(record, patch) {else if (key === 'spec' || key === 'publishBinding') {next[key] = patch[key] && typeof patch[key] === 'object' ? patch[key] : null;// '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);+ // always applies per the whitelist-patch convention above. recordRenderPin+ // also caps the model id, so a PATCH persists the same bounded shape as+ // the other pinned record kinds.+ } else if (key === 'imageMode') next.imageMode = recordRenderPin(patch).mode;+ else if (key === 'imageModelId') next.imageModelId = recordRenderPin(patch).modelId;else next[key] = trimOrNull(patch[key]);}next.updatedAt = new Date().toISOString();diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.jsindex 6bfe165489..be792e2879 100644--- a/server/services/sprites/reference.js+++ b/server/services/sprites/reference.js@@ -36,7 +36,7 @@ import {LOCAL_IMAGEGEN_DEFAULT_MODEL,} from '../imageGen/modes.js';import { resolveImageCleaners } from '../imageGen/index.js';-import { renderTargetDefaults, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';+import { pickUsableMode, renderTargetDefaults, resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';import { getSettings } from '../settings.js';import { getRecord, updateRecord, listRecords, createCharacter } from './records.js';@@ -389,11 +389,18 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {const settings = await getSettings();// 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).+ // pin in settings.renderDefaults, then the install default. The pins go+ // through pickUsableMode so each disabled rung falls to the NEXT rung+ // (matching resolveRenderTargetConfig's per-rung gating) instead of a+ // disabled record pin swallowing the target pin; resolveQueueImageMode+ // keeps the historical gate for an explicit body.mode.const spritePin = recordRenderPin(record);let mode = resolveQueueImageMode(- body.mode || spritePin.mode || renderTargetDefaults(settings, RENDER_TARGET.SPRITE_REFERENCE).imageMode,+ body.mode || pickUsableMode(settings, [+ spritePin.mode,+ renderTargetDefaults(settings, RENDER_TARGET.SPRITE_REFERENCE).imageMode,+ settings?.imageGen?.mode,+ ]),settings,);@@ -758,15 +765,13 @@ 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 } : {}),- });- }+ // The fork's chosen backend/model seeds the NEW record's render pin+ // (#3231 Phase 3) in the create itself, so re-rolls keep rendering where+ // the fork was made.+ const record = await createCharacter({+ name: body.name, id: body.id, kind: 'character',+ imageMode: body.mode || null, imageModelId: body.model || null,+ });const gen = await startReferenceGeneration(record.id, {target: TURNAROUND_ID,designPrompt: body.designPrompt,diff --git a/server/services/universeBuilder/sanitize.js b/server/services/universeBuilder/sanitize.jsindex dbbdc9a232..e9536f2acf 100644--- a/server/services/universeBuilder/sanitize.js+++ b/server/services/universeBuilder/sanitize.js@@ -18,7 +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';+import { persistedRenderPinFields } from '../../lib/renderTargets.js';// RECORD-shape schema version, stamped INSIDE each universe record. Distinct// from the type-level (storage layout) schemaVersion carried by@@ -706,7 +706,6 @@ 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`@@ -776,8 +775,7 @@ export const sanitizeTemplate = (raw) => {// 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) } : {}),+ ...persistedRenderPinFields(raw),locked,characters,places,