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
fix: preserve inherited models for single-image renders (#8547)
[._.]/ Adam Eivy7c1f3b9535ad
diff --git a/client/src/components/universe/UniverseCanonSection.jsx b/client/src/components/universe/UniverseCanonSection.jsxindex 6f5130a151..18b7c53d59 100644--- a/client/src/components/universe/UniverseCanonSection.jsx+++ b/client/src/components/universe/UniverseCanonSection.jsx@@ -405,7 +405,7 @@ export default function UniverseCanonSection({toast.error(`Add a description before generating a reference for ${entry.name}`);return;}- const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const baseOpts = pipelineImageCfgToRenderOpts(imageCfg, { universeRun: { universeId: universe?.id } });const styled = composeCanonStyledPrompt({name: entry.name,description,@@ -472,7 +472,7 @@ export default function UniverseCanonSection({toast.error(`Add a description, palette, or recurring details before generating a clean plate for ${entry.name}`);return;}- const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const baseOpts = pipelineImageCfgToRenderOpts(imageCfg, { universeRun: { universeId: universe?.id } });const plate = composeCleanPlatePrompt(entry, baseOpts.negativePrompt || '');// Layer the universe style on top of the clean-plate composition so the// empty-location render shares the visual language of the populated refs.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8c61c64fd3..35fc247f32 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -79,7 +79,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useImageGenQueue` | Work-scoped live queue of in-flight image renders. | Pages that show per-work image-gen queue state. || `useLocalImageRuntime` | The local image runtime's verdict for one model — `{ runtime, loading, refresh }` — from `GET /api/image-gen/status?mode=local&modelId=…`, the same `diagnoseLocalRuntime` the renderer refuses against. `runtime` carries `readiness`, `reason` and a one-button `remedy`. Pass `null` while the host is still resolving which model it renders on. | Any surface whose renders can be blocked by an unhealthy local runtime: pair it with `LocalRuntimeStatus` to show the verdict and its fix, and read `readiness` to stand the surface's own Render button down. || `useDeckRenderTarget` | What a deck's next card render runs on — `{ backends, size, summary, localRuntime, blocked }` — resolving the `RENDER_TARGET.DECK` pin ladder, the card trim, and the local runtime's verdict in one call. | Any deck surface that queues a render or names the options it will use (the render bar, the card grid's per-card re-render) — resolve it once on the page and pass it down rather than probing per consumer. |-| `useImageRenderSettings` | Load the pipeline image-gen config once (`getSettings → readPipelineImageSettings`), failing open to `PIPELINE_IMAGE_DEFAULTS`; takes `{ record, target }` to fold that record's `imageMode`/`imageModelId` pin, then the target's `renderDefaults` pin, over the install default; returns `{ imageCfg }`. | A single-image render slot that needs the render config and doesn't already load the full settings blob. Pass `record` + `target` whenever the render belongs to a pinnable record (universe, series, sprite). |+| `useImageRenderSettings` | Load settings and project shared record → target → install render preferences; returns `{ imageCfg, backends }`. `imageCfg.inheritedBackend` distinguishes inherited display/runtime preferences from explicit form overrides; local model admission stays server-side. | Single-image render slots; pass record and target, and retain the owning record tag on submission. || `useUserTimezone` | Resolve the user's configured IANA timezone (`settings.timezone`) once, falling back to the browser zone then UTC; returns the tz string. | A date-scoped surface that must derive "today" the same way the server does (POST launcher/history day keys, #2681). || `useSingleImageRender` | Queue-one-render / wait-for-completion jobId lifecycle: builds opts from `imageCfg`, calls `buildPrompt`, POSTs `generateImage`, tracks the `jobId` head, and runs a once-per-`(key, filename)` completion guard before `onComplete`. | Single-image render slots driven by `EntryThumbSlot`/`MediaJobThumb` (style probe, characters step). Completion SSE stays in the thumb. |diff --git a/client/src/hooks/useDeckRenderTarget.js b/client/src/hooks/useDeckRenderTarget.jsindex 2c0e7daaab..696044123e 100644--- a/client/src/hooks/useDeckRenderTarget.js+++ b/client/src/hooks/useDeckRenderTarget.js@@ -38,7 +38,8 @@ export default function useDeckRenderTarget(deck) {// otherwise have to be added to each. Empty until the fetch lands, which is// also how a caller knows not to claim anything about the render yet.const summary = resolved- ? [modeLabel(imageCfg.mode), imageCfg.cloudModel || imageCfg.modelId, `${size.width}×${size.height}`].filter(Boolean).join(' · ')+ ? [modeLabel(imageCfg.mode), imageCfg.mode === IMAGE_GEN_MODE.LOCAL && imageCfg.inheritedBackend+ ? 'Inherited local model' : imageCfg.cloudModel || imageCfg.modelId, `${size.width}×${size.height}`].filter(Boolean).join(' · '): '';return { backends, size, summary, localRuntime, blocked };diff --git a/client/src/hooks/useImageRenderSettings.js b/client/src/hooks/useImageRenderSettings.jsindex f0ec6890e8..b5e24cd4da 100644--- a/client/src/hooks/useImageRenderSettings.js+++ b/client/src/hooks/useImageRenderSettings.js@@ -41,7 +41,8 @@ export default function useImageRenderSettings({ record = null, target = null }const backends = settings ? deriveAvailableBackends(settings, { excludeExternal: true }) : [];return {backends,- imageCfg: resolveRenderCfg(settings, { record, target, backends: settings ? backends : null }),+ // Display projection only; tagged submissions retain server inheritance.+ imageCfg: resolveRenderCfg(settings, { record, target }),};}, [settings, target, record?.imageMode, record?.imageModelId]);}diff --git a/client/src/hooks/useImageRenderSettings.test.jsx b/client/src/hooks/useImageRenderSettings.test.jsxindex 27bef85faa..5609d3dcc3 100644--- a/client/src/hooks/useImageRenderSettings.test.jsx+++ b/client/src/hooks/useImageRenderSettings.test.jsx@@ -15,6 +15,7 @@ const UNRESOLVED = {...IMAGE_RENDER_KNOB_DEFAULTS,mode: 'local',modelId: LOCAL_IMAGEGEN_DEFAULT_MODEL,+ inheritedBackend: true,cloudModel: null,};@@ -51,16 +52,17 @@ describe('useImageRenderSettings', () => {},};- it('takes the local model from the install pin, not the pipeline form', async () => {+ it('retains the install preference for legacy runtime probes', async () => {getSettings.mockResolvedValue({ ...PIPELINE_FORM, imageGen: { local: { modelId: 'flux2-klein-9b' } } });const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));await waitFor(() => expect(result.current.imageCfg.modelId).toBe('flux2-klein-9b'));});- it('falls back to the shipped local default when the install pins no model', async () => {+ it('marks the shipped fallback as inherited', async () => {getSettings.mockResolvedValue(PIPELINE_FORM);const { result } = renderHook(() => useImageRenderSettings({ target: 'deck' }));await waitFor(() => expect(result.current.imageCfg.modelId).toBe(LOCAL_IMAGEGEN_DEFAULT_MODEL));+ expect(result.current.imageCfg.inheritedBackend).toBe(true);});it('takes the backend from the install-wide mode, not the pipeline form', async () => {diff --git a/client/src/hooks/useSingleImageRender.js b/client/src/hooks/useSingleImageRender.jsindex 3cbc4771ff..5f3ad0dcbf 100644--- a/client/src/hooks/useSingleImageRender.js+++ b/client/src/hooks/useSingleImageRender.js@@ -78,7 +78,7 @@ export default function useSingleImageRender({ buildPrompt, onComplete, onError,const render = useCallback(async (imageCfg, key = singleKeyRef.current, extraParams = undefined) => {const built = buildPromptRef.current?.(key);if (!built) return null; // caller aborted (already toasted why)- const baseOpts = pipelineImageCfgToRenderOpts(imageCfg);+ const baseOpts = pipelineImageCfgToRenderOpts(imageCfg, extraParams);// `extraParams` lets a caller attach extra fields to the generate payload// (e.g. the base-style probe's `universeRun` collection target) so the// server can route the finished render — the front-end does nodiff --git a/client/src/hooks/useSingleImageRender.test.jsx b/client/src/hooks/useSingleImageRender.test.jsxindex 27b47cb801..80aec1f204 100644--- a/client/src/hooks/useSingleImageRender.test.jsx+++ b/client/src/hooks/useSingleImageRender.test.jsx@@ -8,6 +8,7 @@ vi.mock('../services/api', () => ({// pipelineImageCfgToRenderOpts is exercised for real (pure); pass a minimal cfg.import useSingleImageRender from './useSingleImageRender.js';+import { resolveRenderCfg } from '../lib/pipelineImageDefaults.js';const IMG_CFG = { mode: 'local', modelId: 'm', width: 512, height: 512, steps: '', guidance: '', seed: '', negativePrompt: 'lowres', extraStyle: '' };@@ -33,6 +34,25 @@ describe('useSingleImageRender', () => {expect(generateImage.mock.calls[0][1]).toEqual({ silent: true });});+ it('submits inherited tags without projected pins while preserving explicit render overrides', async () => {+ generateImage.mockResolvedValue({ jobId: 'example-job' });+ const cfg = resolveRenderCfg({+ imageGen: { mode: 'codex', codex: { enabled: true } },+ renderDefaults: { 'universe-bible': { imageMode: 'codex', imageModel: 'example-target' } },+ }, { record: { imageMode: 'codex' }, target: 'universe-bible' });+ expect(cfg.cloudModel).toBe('example-target');+ const { result } = renderHook(() => useSingleImageRender({ buildPrompt: () => ({ prompt: 'Example image' }) }));+ const universeRun = { universeId: 'example-universe' };+ await act(async () => { await result.current.render(cfg, undefined, { universeRun }); });+ expect(generateImage.mock.calls[0][0]).toEqual({+ prompt: 'Example image', negativePrompt: undefined, width: 1024, height: 1536, universeRun,+ });+ await act(async () => {+ await result.current.render(cfg, undefined, { universeRun, mode: 'local', modelId: 'example-explicit' });+ });+ expect(generateImage.mock.calls[1][0]).toMatchObject({ mode: 'local', modelId: 'example-explicit', universeRun });+ });+it('aborts without POSTing when buildPrompt returns null', async () => {const buildPrompt = vi.fn(() => null);const { result } = renderHook(() => useSingleImageRender({ buildPrompt, onComplete: vi.fn() }));diff --git a/client/src/lib/imageGenModes.js b/client/src/lib/imageGenModes.jsindex 5d4c949178..2055578dcd 100644--- a/client/src/lib/imageGenModes.js+++ b/client/src/lib/imageGenModes.js@@ -38,6 +38,8 @@ import {normalizeRenderPinValue,} from '../../../server/lib/renderTargets.js';import {+ resolveRenderPins,+ resolveRenderTargetPins,imageModeCandidates,isModeUsable,pickUsableMode,@@ -115,6 +117,7 @@ export {// `server/lib/renderModeLadder.js` for the fall-through semantics (a pin is// a preference, not a guarantee) and the candidate-order contract.imageModeCandidates,+ resolveRenderTargetPins,isModeUsable,pickUsableMode,renderTargetDefaults,@@ -227,30 +230,20 @@ export function localModelSelectOptions(models, pinned, fallbackId = LOCAL_IMAGE* first, which for every surface is: the record's own pin (`recordRenderPin`'s* `imageMode`/`imageModelId`), then the target's `renderTargetPin(settings, target)`.*- * Why the client resolves this at all: single-image render call sites (a- * universe cast reference, the base-style probe) send `mode` EXPLICITLY, and an- * explicit mode outranks every pin on the server ladder — so a universe pinned- * to agy rendered its cast on whatever the install-wide default resolved to- * (codex, on a codex-enabled install) until the client folded the pin in itself.- *- * `availableBackends` (the `deriveAvailableBackends` shape) is a client-side- * usability gate with no server counterpart: a pin naming a backend this install- * no longer has enabled falls through to the next rung rather than queueing a- * job that can only 400. Pass `null` when the backend list isn't loaded yet —- * an empty array means "loaded, nothing enabled" and suppresses every pin.+ * This is a compatibility wrapper over the shared pure pin resolver. Model+ * inheritance follows lower pins on the same usable backend. The optional+ * backend list gates previews; null means the list has not loaded yet.** @param {Array<object|null>} sources - Pin sources, highest priority first.* @param {Array<{id:string}>|null} [availableBackends] - Enabled backends, or null.* @returns {{mode: string|null, modelId: string|null}} The first usable pin.*/export function renderPinLadder(sources, availableBackends = null) {- for (const source of sources) {- const mode = normalizeRenderPinValue(source?.imageMode);- if (!mode) continue;- if (Array.isArray(availableBackends) && !availableBackends.some((b) => b.id === mode)) continue;- return { mode, modelId: normalizeRenderPinValue(source?.imageModelId) };- }- return { mode: null, modelId: null };+ const { mode, modelId } = resolveRenderPins(sources, {+ usable: (candidate) => !Array.isArray(availableBackends)+ || availableBackends.some((backend) => backend.id === candidate),+ });+ return { mode, modelId };}/**diff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.jsindex 127407cdf1..f0b42514f7 100644--- a/client/src/lib/pipelineImageDefaults.js+++ b/client/src/lib/pipelineImageDefaults.js@@ -7,8 +7,8 @@import {installLocalModelId, isCloudCliMode, IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL,- pickUsableMode, renderPinLadder, renderTargetPin, supportsCloudModelOverride,-} from './imageGenBackends';+ resolveRenderTargetPins, supportsCloudModelOverride,+} from './imageGenModes.js';// The geometry + prompt knobs of a render config, with no backend or model —// the half that is NOT install-wide state. `settings.pipeline.imageGen` is the@@ -43,42 +43,31 @@ export const UNRESOLVED_RENDER_CFG = Object.freeze({mode: IMAGE_GEN_MODE.LOCAL,modelId: LOCAL_IMAGEGEN_DEFAULT_MODEL,cloudModel: null,+ inheritedBackend: true,});/**- * Resolve "what will a render on this surface actually run on" — the client- * mirror of the server's own ladder, and the ONE place a non-Pipeline surface- * derives a render config.- *- * The backend walks `renderPinLadder` (the record's own `imageMode`, then the- * target's `renderDefaults` pin, both gated on backends this install actually- * has) and falls through to the install-wide `imageGen.mode` via the shared- * `pickUsableMode`. The model then follows the backend it belongs to: local- * takes the pin, else `imageGen.local.modelId`, else the shipped default; an- * override-capable cloud CLI takes the pin as `cloudModel` and nothing else, so- * a cloud mode can never be advertised beside a local model.- *- * Nothing here reads `settings.pipeline.imageGen`. That slice is the Pipeline- * visual FORM's sticky buffer, and using it as a general base is what made a- * deck claim it would render on the model a comic page was last rendered with- * while the server used the install pin the whole time.- *- * @param {object|null} settings - The settings blob, or null when unresolved.- * @param {object} [opts]- * @param {object|null} [opts.record] - Record whose `imageMode`/`imageModelId` pin wins.- * @param {string|null} [opts.target] - RENDER_TARGET id whose `renderDefaults` pin is next.- * @param {Array<{id:string}>|null} [opts.backends] - Enabled backends a pin is gated on;- * `null` while the list isn't loaded (`[]` means "loaded, nothing enabled").+ * Display-only projection of record → target → install preferences. The shared+ * pure ladder can preview backend/cloud pins; local catalog and hardware+ * validation stay on the server: modelId is a preference, not an admitted model.+ * The provenance marker lets tagged submissions omit these inherited choices.+ * Pipeline forms use readPipelineImageSettings and remain explicit overrides.*/-export function resolveRenderCfg(settings, { record = null, target = null, backends = null } = {}) {+export function resolveRenderCfg(settings, { record = null, target = null } = {}) {if (!settings) return UNRESOLVED_RENDER_CFG;- const pin = renderPinLadder([record, renderTargetPin(settings, target)], backends);- const mode = pin.mode || pickUsableMode(settings, [settings.imageGen?.mode]);+ const pin = resolveRenderTargetPins(settings, target, {+ recordMode: record?.imageMode,+ recordModel: record?.imageModelId,+ fallbackMode: IMAGE_GEN_MODE.LOCAL,+ });+ const mode = pin.mode;const isLocal = mode === IMAGE_GEN_MODE.LOCAL;return {...IMAGE_RENDER_KNOB_DEFAULTS,mode,+ // Retained for legacy form/runtime consumers, never an admitted model.modelId: isLocal ? (pin.modelId || installLocalModelId(settings)) : null,+ inheritedBackend: true,cloudModel: !isLocal && supportsCloudModelOverride(mode) ? pin.modelId : null,};}@@ -121,13 +110,16 @@ const numericOrNaN = (v) => (String(v ?? '').trim() === '' ? NaN : Number(v));// Strip empty strings + coerce numerics so the request body only carries// fields the server should act on. Empty strings would otherwise serialize// to "" and trip the zod number coercion.-export function pipelineImageCfgToRenderOpts(cfg) {- const opts = { mode: cfg.mode };- if (cfg.mode === IMAGE_GEN_MODE.LOCAL && cfg.modelId) opts.modelId = cfg.modelId;+export function pipelineImageCfgToRenderOpts(cfg, tags = {}) {+ // Only a tagged inherited projection can be re-resolved against its owner.+ // Editable Pipeline configs have no marker and retain explicit API semantics.+ const inherited = cfg.inheritedBackend && (tags.universeRun?.universeId || tags.musicVideo?.projectId);+ const opts = inherited ? {} : { mode: cfg.mode };+ if (!inherited && cfg.mode === IMAGE_GEN_MODE.LOCAL && cfg.modelId) opts.modelId = cfg.modelId;// A record render pin can name the cloud CLI's model too (`applyRecordRenderPin`// routes it here); the dispatcher folds `cloudModel` into the provider's own// model for that one job. Local reads `modelId` above instead.- if (isCloudCliMode(cfg.mode) && cfg.cloudModel) opts.cloudModel = cfg.cloudModel;+ if (!inherited && isCloudCliMode(cfg.mode) && cfg.cloudModel) opts.cloudModel = cfg.cloudModel;if (Number.isFinite(cfg.width)) opts.width = cfg.width;if (Number.isFinite(cfg.height)) opts.height = cfg.height;if (!isCloudCliMode(cfg.mode)) {diff --git a/server/lib/README.md b/server/lib/README.mdindex 48e60789b6..e29c435657 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -36,7 +36,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `generationModes.js` | Shared immutable image/video render-backend alphabets (`IMAGE_GEN_MODE[S]`, `QUEUEABLE_IMAGE_MODES`, `VIDEO_GEN_MODE[S]`, and cloud subsets) plus `mediaJobExecutionLane({ kind, mode, remote })` / `MEDIA_JOB_EXECUTION_LANES` — THE media-queue lane rule the scheduler and the public job projection share, kept below both validation and generation services so schemas never import orchestration modules. || `imageGenCapabilities.js` | Per-backend image-gen capability literals, a dependency-free leaf beside `generationModes.js`: `EDIT_INCAPABLE_IMAGE_MODES`/`isEditCapableMode` and the derived `I2I_CAPABLE_MODES`, the shipped defaults (`CODEX_IMAGEGEN_DEFAULT_MODEL`/`_EFFORT`, `AGY_IMAGEGEN_DEFAULT_MODEL`, `AGY_IMAGEGEN_IMAGE_MODEL`), the `AGY_`/`GROK_ASPECT_RATIOS` alphabets, and `IMAGE_GEN_PROVIDER_CAPABILITIES` (`supportsModelOverride`, `maxInputImages`, `promptRequiredWithInputImage`) with its `supportsCloudModelOverride`/`maxInputImages`/`cloudPromptRequired` readers. The `services/imageGen/*` modules re-export these, and `client/src/lib/imageGenModes.js` imports them instead of copying them (#6590). || `imageRuntimeRemedies.js` | Local image-runtime vocabulary, a dependency-free leaf beside `imageGenCapabilities.js`: `IMAGE_RUNTIME_READINESS` (ready/unavailable/unknown), `IMAGE_RUNTIME` + `IMAGE_RUNTIME_LABELS` (the shared torch venv vs. the configurable mflux interpreter), `IMAGE_RUNTIME_REMEDY` (the one action that fixes each unavailable state), and `IMAGE_RUNTIME_UNAVAILABLE_CODE`. `services/imageGen/localRuntime.js` builds the diagnosis from these, `services/imageGen/local.js` tags its pre-flight render refusal with the same remedy, and `client/src/lib/imageGenModes.js` re-exports them so no component hand-copies a remedy kind. |-| `renderModeLadder.js` | Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. |+| `renderModeLadder.js` | `resolveRenderPins` and `resolveRenderTargetPins` share backend-scoped model candidate inheritance across browser and server. Image-gen mode resolution ladder (#6815), a dependency-free leaf beside `generationModes.js`/`renderTargets.js` so the client imports it directly instead of hand-copying it: `isModeUsable(settings, mode)` (queueable + enabled gate, no per-provider spec lookup), `pickUsableMode(settings, candidates)` (first usable candidate, falling through disabled pins to the cloud-then-local tail), `renderTargetDefaults(settings, target)` (the normalized `settings.renderDefaults[target]` pin), and `imageModeCandidates(settings, target, record)` (the shared `[recordPin, targetPin, installDefault]` candidate order, declared once so a UI's own "what will Auto resolve to" display can't drift from the resolver). `services/imageGen/cloudProviderConfig.js` re-exports the first three for its existing callers. || `fableLoomLimits.js` | FableLoom record caps (`LOOM_LIMITS`) — the single source of truth shared by the route schemas and the record sanitizer. A leaf module, below both. || `fableLoomCameraMovements.js` | Shared FableLoom camera-movement registry for generated cut direction and the manual scene editor selector. || `fableLoomPlayback.js` | FableLoom node playback modes (`cut` auto-advances; `decision` loops while awaiting input), with the backward-compatible default. |diff --git a/server/lib/renderModeLadder.js b/server/lib/renderModeLadder.jsindex f7e68275ff..a053365ff9 100644--- a/server/lib/renderModeLadder.js+++ b/server/lib/renderModeLadder.js@@ -107,3 +107,33 @@ export function imageModeCandidates(settings, target, record = null) {settings?.imageGen?.mode,];}++/**+ * Pure pin projection shared by browser previews and server dispatch. A+ * mode-only pin inherits models from lower pins on the SAME usable backend.+ * Keep all candidates so local catalog/hardware validation can skip stale pins.+ */+export function resolveRenderPins(sources, { mode = null, usable = () => true } = {}) {+ const pins = sources.map(recordRenderPin).filter((pin) => pin.mode && usable(pin.mode));+ const finalMode = mode || pins[0]?.mode || null;+ const modelCandidates = pins.filter((pin) => pin.mode === finalMode)+ .map((pin) => pin.modelId).filter(Boolean);+ return { mode: finalMode, modelId: modelCandidates[0] || null, modelCandidates };+}++/** Resolve preferences without filesystem, catalog, or provider dependencies. */+export function resolveRenderTargetPins(settings, target, {+ mode = null, model = null, recordMode = null, recordModel = null, fallbackMode = null,+} = {}) {+ const defaults = renderTargetDefaults(settings, target);+ const sources = [+ { imageMode: recordMode, imageModelId: recordModel },+ { imageMode: defaults.imageMode, imageModelId: defaults.imageModel },+ ];+ const usable = (candidate) => isModeUsable(settings, candidate);+ const pin = resolveRenderPins(sources, { usable });+ const finalMode = mode || pin.mode || settings?.imageGen?.mode || fallbackMode;+ const resolved = resolveRenderPins(sources, { mode: finalMode, usable });+ const requestedModel = typeof model === 'string' && model.trim() ? model.trim() : null;+ return { ...resolved, modelId: requestedModel || resolved.modelId };+}diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 8d2e2d47fa..5f0b4476e9 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -207,6 +207,12 @@ import { AGY_IMAGEGEN_DEFAULT_MODEL } from '../lib/imageGenCapabilities.js';import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';import { prepareRemoteMediaJob } from '../services/federatedMedia/remoteSubmission.js';+import { resolveRenderCfg, pipelineImageCfgToRenderOpts } from '../../client/src/lib/pipelineImageDefaults.js';+import * as mediaModels from '../lib/mediaModels.js';++const getUniverseRenderPin = vi.hoisted(() => vi.fn(async () => null));+vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverseRenderPin }));+describe('Image Gen Routes', () => {let app;@@ -218,6 +224,93 @@ describe('Image Gen Routes', () => {vi.clearAllMocks();});+ describe('inherited browser render preferences', () => {+ const tag = { universeRun: { universeId: 'example-universe', universeName: 'Example Universe' } };+ const model = (id, state = 'available') => ({+ id, name: id, hardwareCompatibility: { state }, pipelineClass: 'QwenImage21Pipeline',+ });+ afterEach(() => {+ vi.restoreAllMocks();+ getUniverseRenderPin.mockResolvedValue(null);+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });+ });+ const submit = async (settings, record, overrides = {}) => {+ getSettings.mockResolvedValue(settings);+ getUniverseRenderPin.mockResolvedValue(record);+ const cfg = resolveRenderCfg(settings, { record, target: 'universe-bible' });+ const opts = pipelineImageCfgToRenderOpts(cfg, tag);+ expect(opts).not.toHaveProperty('mode');+ expect(opts).not.toHaveProperty('modelId');+ expect(opts).not.toHaveProperty('cloudModel');+ return request(app).post('/api/image-gen/generate').send({+ ...opts, ...tag, prompt: 'A synthetic landscape', ...overrides,+ });+ };++ it.each(['example-retired', 'example-incompatible'])('falls back from inherited %s but rejects an explicit request', async (pin) => {+ vi.spyOn(mediaModels, 'getImageModels').mockReturnValue([+ model('example-incompatible', 'unavailable'), model('example-compatible'),+ ]);+ const settings = { imageGen: { mode: 'local', local: { modelId: pin, pythonPath: '/example/python' } } };+ const response = await submit(settings, { imageMode: 'local', imageModelId: pin });+ expect(response.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenLastCalledWith(expect.objectContaining({+ params: expect.objectContaining({ modelId: 'example-compatible' }),+ }));+ expect(getUniverseRenderPin).toHaveBeenCalledTimes(1);+ mediaJobQueue.enqueueJob.mockClear();+ const explicit = await submit(settings, {}, { mode: 'local', modelId: pin });+ expect(explicit.status).toBe(400);+ expect(explicit.body.code).toBe(pin === 'example-retired' ? 'IMAGE_GEN_UNKNOWN_MODEL' : 'MODEL_HARDWARE_UNAVAILABLE');+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();+ });++ it('keeps local record and target preferences ahead of the install and uses the selected capability', async () => {+ vi.spyOn(mediaModels, 'getImageModels').mockReturnValue([+ { ...model('example-install'), pipelineClass: 'FluxPipeline' }, model('example-target'), model('example-record'),+ ]);+ const settings = {+ imageGen: { mode: 'local', local: { modelId: 'example-install', pythonPath: '/example/python' } },+ renderDefaults: { 'universe-bible': { imageMode: 'local', imageModel: 'example-target' } },+ };+ for (const [pin, expected] of [['example-record', 'example-record'], ['example-retired', 'example-target']]) {+ const response = await submit(settings, { imageMode: 'local', imageModelId: pin });+ expect(response.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenLastCalledWith(expect.objectContaining({+ params: expect.objectContaining({ modelId: expected }),+ }));+ }+ // Six references require the selected Qwen model; the install's Flux+ // fallback would reject them before enqueue if preparation resolved twice.+ vi.spyOn(fileUtils, 'resolveGalleryImage').mockReturnValue('/example/reference.png');+ const response = await submit(settings, { imageMode: 'local', imageModelId: 'example-record' }, {+ referenceImageFiles: Array.from({ length: 6 }, (_, index) => `example-ref-${index}.png`),+ });+ expect(response.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenLastCalledWith(expect.objectContaining({+ params: expect.objectContaining({ modelId: 'example-record', referenceImagePaths: Array(6).fill('/example/reference.png') }),+ }));+ });++ it('inherits same-backend cloud target models and keeps explicit overrides and backend isolation', async () => {+ const settings = {+ imageGen: { mode: 'codex', codex: { enabled: true, model: 'example-install-cloud' }, agy: { enabled: true } },+ renderDefaults: { 'universe-bible': { imageMode: 'codex', imageModel: 'example-target-cloud' } },+ };+ for (const [record, overrides, expectedMode, expectedModel] of [+ [{ imageMode: 'codex' }, {}, 'codex', 'example-target-cloud'],+ [{ imageMode: 'codex', imageModelId: 'example-record-cloud' }, {}, 'codex', 'example-record-cloud'],+ [{ imageMode: 'codex' }, { cloudModel: 'example-explicit' }, 'codex', 'example-explicit'],+ [{ imageMode: 'codex' }, { mode: 'agy', cloudModel: 'example-agy' }, 'agy', 'example-agy'],+ [{ imageMode: 'grok', imageModelId: 'example-disabled' }, {}, 'codex', 'example-target-cloud'],+ ]) {+ const response = await submit(settings, record, overrides);+ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({ mode: expectedMode, model: expectedModel });+ }+ });+ });+describe('GET /api/image-gen/gallery', () => {it('preserves legacy arrays and pages/searches the test disk fallback', async () => {const items = [diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex edc1224412..2bb71107d1 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -26,6 +26,7 @@ import {isModeUsable,pickUsableMode,renderTargetDefaults,+ resolveRenderTargetPins,} from '../../lib/renderModeLadder.js';import {AGY_IMAGEGEN_DEFAULT_MODEL,@@ -223,28 +224,12 @@ export function resolveRenderTargetConfig(settings, target, {recordModel = null,fallbackMode = null,} = {}) {- const defaults = renderTargetDefaults(settings, target);- // 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 || 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);+ const resolved = resolveRenderTargetPins(settings, target, {+ mode, model, recordMode, recordModel, fallbackMode,+ });return {- mode: finalMode,- cloud: resolveCloudProviderConfig(settings, finalMode, { model: finalModel }),+ mode: resolved.mode,+ modelCandidates: resolved.modelCandidates,+ cloud: resolveCloudProviderConfig(settings, resolved.mode, { model: resolved.modelId }),};}diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex 7b15cfbc09..3ae3b52afa 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -115,7 +115,7 @@ export function selectLocalImageModel(modelId, allModels = getImageModels(), pin* heavy before init images exist.*/export function selectLocalImageModelFromSettings(settings, modelId, allModels = getImageModels(), recordModelId = null) {- return selectLocalImageModel(modelId, allModels, [recordModelId, settings?.imageGen?.local?.modelId].filter(Boolean));+ return selectLocalImageModel(modelId, allModels, [recordModelId, settings?.imageGen?.local?.modelId].flat().filter(Boolean));}/**@@ -191,6 +191,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFields// whichever branch ran last silently overwrite the other's mode while// inheriting its model. Adding a surface is one row here, matching the// "one entry + one resolve call" contract in lib/renderTargets.js.+ let localModelCandidates = [];const source = data.mode ? null : RECORD_PIN_SOURCES.find((s) => data[s.tag]?.[s.idKey]);if (source) {const record = await source.load(data[source.tag][source.idKey]).catch(() => null);@@ -202,6 +203,7 @@ export async function prepareGenerateParams({ data, files, referenceImageFieldsfallbackMode: IMAGE_GEN_MODE.EXTERNAL,});mode = resolved.mode;+ localModelCandidates = resolved.modelCandidates;// Stamping the id ERASES where it came from, and the dispatch below// re-resolves from `data.cloudModel` alone — so a shipped default// materialized here would arrive there looking like a deliberate choice and@@ -219,7 +221,10 @@ export async function prepareGenerateParams({ data, files, referenceImageFieldsconst referenceImageCount = namedReferenceFiles.length + referenceUploads.length;const inputImageCount = (initUpload || data.initImageFile ? 1 : 0) + referenceImageCount;- const localModel = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModelFromSettings(settings, data.modelId) : null;+ const localModel = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModelFromSettings(settings, data.modelId, getImageModels(), localModelCandidates) : null;+ // Freeze the selected preference before capability checks. Explicit ids stay+ // untouched so the existing unknown/hardware rejection still applies.+ if (!data.modelId && localModel?.id) data.modelId = localModel.id;const referenceCap = localModel?.pipelineClass === 'QwenImage21Pipeline' ? 10 : 4;if (referenceImageCount > referenceCap) {cleanupReqFilesTemp();