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

fix: resolve local image models consistently (#8076)

[._.]/ Adam Eivya9b3d41d967b
diff --git a/server/routes/universeBuilder/index.test.js b/server/routes/universeBuilder/index.test.js
index 16eae97831..68492d010f 100644
--- a/server/routes/universeBuilder/index.test.js
+++ b/server/routes/universeBuilder/index.test.js
@@ -254,6 +254,7 @@ vi.mock('../../lib/mediaModels.js', () => ({
isFlux2: () => false,
isZImage: () => false,
isErnie: () => false,
+ isEditOnly: () => false,
}));
// Controllable listSeries for DELETE /:id → 409 UNIVERSE_HAS_LIVE_SERIES test.
diff --git a/server/services/README.md b/server/services/README.md
new file mode 100644
index 0000000000..6cc29cfb81
--- /dev/null
+++ b/server/services/README.md
@@ -0,0 +1,18 @@
+# Server Services
+
+Domain services own multi-step workflows over models, settings, and shared
+infrastructure. Import the narrow service module needed by a caller; the
+image-generation paths below are useful entry points when tracing render jobs.
+
+| Module | Responsibility |
+| --- | --- |
+| `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |
+| `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. |
+| `universeBuilderRender.js` | Universe Builder batch render jobs. |
+| `pipeline/visualStageHelpers.js` | Shared pipeline visual prompt, LoRA compatibility, and image-job enqueue helpers. |
+| `creativeDirector/firstPassGen.js` | Gracefully gated first-pass portraits and scene frames. |
+| `universeCharacterSheet.js` | Character reference-sheet render and completion workflow. |
+| `loraDatasetGenerate.js` | Training-image render and dataset lifecycle. |
+| `sprites/reference.js` | Sprite reference candidate rendering and provenance. |
+| `deckRender.js` | Deck card image render jobs. |
+| `fableLoom/production.js` | FableLoom production render planning and enqueueing. |
diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.js
index 1467e8e605..0b3b851e48 100644
--- a/server/services/creativeDirector/firstPassGen.js
+++ b/server/services/creativeDirector/firstPassGen.js
@@ -33,7 +33,9 @@ import { getSettings } from '../settings.js';
import { resolveImageCleaners } from '../imageGen/index.js';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
import { resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
+import { resolveLocalImageModel } from '../imageGen/prepareParams.js';
import { RENDER_TARGET } from '../../lib/renderTargets.js';
+import { ServerError } from '../../lib/errorHandler.js';
import { getIngredient, listMediaForIngredient } from '../catalogDB.js';
import { resolveAspectDimensions } from '../../lib/creativeDirectorPresets.js';
import { payloadSnippet, getActiveCatalogType } from '../../lib/catalogTypes.js';
@@ -107,20 +109,24 @@ async function resolveQueueModeParams(project = null) {
return { mode, ready: true, jobParams: { ...cloud.jobParams, cleanC2PA, denoise } };
}
if (mode === IMAGE_GEN_MODE.LOCAL) {
- // We pass no modelId, so the worker renders with its default ('dev') model —
- // an mflux model that REQUIRES a configured pythonPath (the imageGen route
- // and universeBuilderRender both reject this up front with
- // IMAGE_GEN_NOT_CONFIGURED). First-pass gen runs fire-and-forget with no
- // client listening, so a doomed job's SSE failure would vanish while the
- // user is told portraits are rendering. Skip cleanly instead — same
- // graceful-skip contract as a disabled codex.
- const pythonPath = settings.imageGen?.local?.pythonPath || null;
- if (!pythonPath) return { mode, ready: false, reason: 'local-not-configured' };
+ let localModel;
+ try {
+ localModel = resolveLocalImageModel(settings, {});
+ } catch (err) {
+ if (!(err instanceof ServerError)) throw err;
+ return { mode, ready: false, reason: err.code };
+ }
+ if (!localModel.selectedModel) return { mode, ready: false, reason: 'IMAGE_GEN_UNKNOWN_MODEL' };
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
return {
mode,
ready: true,
- jobParams: { pythonPath, cleanC2PA, denoise },
+ jobParams: {
+ pythonPath: localModel.pythonPath,
+ modelId: localModel.selectedModel.id,
+ cleanC2PA,
+ denoise,
+ },
};
}
// external (or an unknown mode) — synchronous SD-API isn't suited for a
diff --git a/server/services/creativeDirector/firstPassGen.test.js b/server/services/creativeDirector/firstPassGen.test.js
index ffcfa7a437..2a7c750e59 100644
--- a/server/services/creativeDirector/firstPassGen.test.js
+++ b/server/services/creativeDirector/firstPassGen.test.js
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+const { resolveLocalImageModel } = vi.hoisted(() => ({ resolveLocalImageModel: vi.fn() }));
+
// Mock the I/O boundaries; keep catalogTypes real (pure snippet transform) so
// buildPortraitPrompt exercises the actual physicalDescription fallback chain.
vi.mock('../mediaJobQueue/index.js', () => ({
@@ -18,6 +20,9 @@ vi.mock('../settings.js', () => ({
vi.mock('../imageGen/index.js', () => ({
resolveImageCleaners: vi.fn(() => ({ cleanC2PA: true, denoise: false })),
}));
+vi.mock('../imageGen/prepareParams.js', () => ({
+ resolveLocalImageModel: (...args) => resolveLocalImageModel(...args),
+}));
vi.mock('../catalogDB.js', () => ({
getIngredient: vi.fn(),
listMediaForIngredient: vi.fn(),
@@ -27,6 +32,7 @@ import { buildPortraitPrompt, enqueueFirstPassPortraits, enqueueFirstPassSceneFr
import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getIngredient, listMediaForIngredient } from '../catalogDB.js';
+import { ServerError } from '../../lib/errorHandler.js';
let jobSeq = 0;
@@ -36,6 +42,15 @@ beforeEach(() => {
enqueueJob.mockImplementation(() => ({ jobId: `job-${++jobSeq}`, position: 1, status: 'queued' }));
// Default: local mode configured, ingredients have no portrait.
getSettings.mockResolvedValue({ imageGen: { mode: 'local', local: { pythonPath: '/py' } } });
+ resolveLocalImageModel.mockImplementation((settings) => {
+ const pythonPath = settings.imageGen?.local?.pythonPath || null;
+ if (!pythonPath) {
+ throw new ServerError('Local image generation is not configured.', {
+ status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED',
+ });
+ }
+ return { pythonPath, selectedModel: { id: settings.imageGen?.local?.modelId || 'dev' } };
+ });
listMediaForIngredient.mockResolvedValue([]);
});
@@ -84,6 +99,7 @@ describe('enqueueFirstPassPortraits', () => {
expect(firstJob.params.catalogAttach).toEqual({ ingredientId: 'a', kind: 'portrait' });
expect(firstJob.params.prompt).toBe('Name-a — desc a');
expect(firstJob.params.pythonPath).toBe('/py');
+ expect(firstJob.params.modelId).toBe('dev');
expect(firstJob.params.cleanC2PA).toBe(true);
});
@@ -129,14 +145,25 @@ describe('enqueueFirstPassPortraits', () => {
expect(getIngredient).not.toHaveBeenCalled();
});
- it('skips gracefully when local mode has no pythonPath (default model would fail unseen)', async () => {
+ it('skips gracefully with the resolver error code when the selected model needs no pythonPath', async () => {
getSettings.mockResolvedValue({ imageGen: { mode: 'local', local: {} } });
const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);
- expect(out).toEqual({ mode: 'local', enqueued: [], skipped: [], reason: 'local-not-configured' });
+ expect(out).toEqual({ mode: 'local', enqueued: [], skipped: [], reason: 'IMAGE_GEN_NOT_CONFIGURED' });
expect(enqueueJob).not.toHaveBeenCalled();
expect(getIngredient).not.toHaveBeenCalled();
});
+ it('queues the install-pinned local model explicitly', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/py', modelId: 'pinned-flux' } },
+ });
+ getIngredient.mockResolvedValue({ id: 'a', type: 'character', name: 'A', payload: { physicalDescription: 'd' } });
+
+ await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);
+
+ expect(enqueueJob.mock.calls[0][0].params.modelId).toBe('pinned-flux');
+ });
+
it('skips gracefully for external mode (not queue-backed)', async () => {
getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });
const out = await enqueueFirstPassPortraits([{ ingredientId: 'a' }]);
diff --git a/server/services/deckRender.js b/server/services/deckRender.js
index 7b2cd5cd19..d79f99a54e 100644
--- a/server/services/deckRender.js
+++ b/server/services/deckRender.js
@@ -71,7 +71,7 @@ export async function renderDeckCards(deckId, { cardIds, onlyMissing = false, mo
? pin.modelId
: null;
const localModel = mode === IMAGE_GEN_MODE.LOCAL
- ? resolveLocalImageModel(settings, { modelId: model || localPinModel || settings.imageGen?.local?.modelId || undefined })
+ ? resolveLocalImageModel(settings, { modelId: model || localPinModel || undefined })
: null;
const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);
diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.js
index 85d19c9ca2..2b2a4dc12f 100644
--- a/server/services/fableLoom/production.js
+++ b/server/services/fableLoom/production.js
@@ -410,10 +410,9 @@ function imageInputForNode(run, asset) {
return resolveImageInputPath(imageAsset?.result?.filename || null);
}
-function requestedImageModel(settings, render, recordedConditioning = null) {
+function requestedImageModel(render, recordedConditioning = null) {
return recordedConditioning?.capability?.modelId
|| render.imageModel
- || settings.imageGen?.local?.modelId
|| undefined;
}
@@ -498,7 +497,7 @@ async function prepareImageJob(run, asset) {
const recordedConditioning = await loadRecordedConditioning(run, asset);
const mode = resolveImageBackend(settings, run.render, recordedConditioning);
const allModels = getImageModels();
- const requestedModel = requestedImageModel(settings, run.render, recordedConditioning);
+ const requestedModel = requestedImageModel(run.render, recordedConditioning);
const provisionalModel = selectLocalImageModelFromSettings(settings, requestedModel, allModels);
const cloud = mode === IMAGE_GEN_MODE.LOCAL
? null
@@ -983,7 +982,7 @@ export async function planEpisodeProduction(loomId, episodeId, options = {}) {
}
}
if (render.imageMode === IMAGE_GEN_MODE.LOCAL || render.imageModel) {
- const imageModelId = render.imageModel || settings.imageGen?.local?.modelId;
+ const imageModelId = render.imageModel || selectLocalImageModelFromSettings(settings)?.id;
if (imageModelId && !getImageModels().some((model) => model.id === imageModelId)) {
plan.planningIssues.push(`Image model "${imageModelId}" is not available on this machine.`);
}
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 92e7b3ff83..745ae937e6 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -1,5 +1,10 @@
/**
- * prepareGenerateParams — pre-dispatch preparation for POST /image-gen/generate.
+ * Shared image-generation preparation and local model selection.
+ *
+ * `selectLocalImageModel`, `selectLocalImageModelFromSettings`, and
+ * `resolveLocalImageModel` are the canonical owner of local image model
+ * identity for every queueing surface. `prepareGenerateParams` also owns
+ * pre-dispatch preparation for POST /image-gen/generate:
*
* Handles everything between Zod validation and the final dispatch branch:
* - resolve effective backend mode + per-render cleaners
@@ -27,8 +32,8 @@ import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, ensureDir, resolveGalleryImage, copyFileGuarded, unlinkGuarded } from '../../lib/fileUtils.js';
import { getSettings } from '../settings.js';
-import { IMAGE_GEN_MODE, resolveImageCleaners } from './index.js';
-import { LOCAL_IMAGEGEN_DEFAULT_MODEL, editIncapableModeError, isEditCapableMode, modeLabel } from './modes.js';
+import { resolveImageCleaners } from './index.js';
+import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL, editIncapableModeError, isEditCapableMode, modeLabel } from './modes.js';
import {
cloudPromptRequired, maxInputImages, resolveCloudProviderConfig, resolveRenderTargetConfig,
} from './cloudProviderConfig.js';
@@ -88,8 +93,9 @@ const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '
*/
export function selectLocalImageModel(modelId, allModels = getImageModels(), pinnedId = null) {
const requestedModel = allModels.find((model) => model.id === modelId);
+ const pinnedIds = (Array.isArray(pinnedId) ? pinnedId : [pinnedId]).filter(Boolean);
return requestedModel || [
- allModels.find((model) => model.id === pinnedId),
+ ...pinnedIds.map((id) => allModels.find((model) => model.id === id)),
allModels.find((model) => model.id === LOCAL_IMAGEGEN_DEFAULT_MODEL),
...allModels,
].filter(Boolean).find((model) => isHardwareCompatible(model.hardwareCompatibility)) || allModels[0];
@@ -99,12 +105,16 @@ export function selectLocalImageModel(modelId, allModels = getImageModels(), pin
* Select the local image model honoring the install-wide pin
* (`settings.imageGen.local.modelId`). Call this from any site that has
* settings and only needs identity (FLUX.2 gate, FableLoom capability)
- * rather than the full `resolveLocalImageModel` pre-dispatch validator —
+ * An optional `recordModelId` is another persisted preference, checked before
+ * the install pin and filtered by the same hardware gate. Use this for local
+ * record pins; do not pass those pins as explicit request model IDs.
+ *
+ * Call this rather than the full `resolveLocalImageModel` pre-dispatch validator —
* that path also checks pythonPath / edit-only / unknown id, which is too
* heavy before init images exist.
*/
-export function selectLocalImageModelFromSettings(settings, modelId, allModels = getImageModels()) {
- return selectLocalImageModel(modelId, allModels, settings?.imageGen?.local?.modelId || null);
+export function selectLocalImageModelFromSettings(settings, modelId, allModels = getImageModels(), recordModelId = null) {
+ return selectLocalImageModel(modelId, allModels, [recordModelId, settings?.imageGen?.local?.modelId].filter(Boolean));
}
/**
diff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.js
index bf3591ad5d..c569b668ab 100644
--- a/server/services/imageGen/prepareParams.test.js
+++ b/server/services/imageGen/prepareParams.test.js
@@ -10,6 +10,9 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync, readdirSync } from 'node:fs';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
const getSettings = vi.fn(async () => ({}));
vi.mock('../settings.js', () => ({ getSettings: (...a) => getSettings(...a) }));
@@ -20,9 +23,41 @@ vi.mock('../musicVideo/projects.js', () => ({ getProject: (...a) => getProject(.
const getUniverseRenderPin = vi.fn(async () => null);
vi.mock('../universeBuilder/crud.js', () => ({ getUniverseRenderPin: (...a) => getUniverseRenderPin(...a) }));
-const { prepareGenerateParams, selectLocalImageModel } = await import('./prepareParams.js');
+const { prepareGenerateParams, selectLocalImageModel, selectLocalImageModelFromSettings } = await import('./prepareParams.js');
const { AGY_IMAGEGEN_DEFAULT_MODEL } = await import('./modes.js');
+const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..');
+const MODEL_PIN_READ = /\bimageGen\s*\??\.\s*local\s*\??\.\s*modelId\b/;
+const ALLOWED_PIN_READERS = new Set([
+ 'services/imageGen/prepareParams.js',
+ 'routes/settings.js',
+ 'lib/validation.js',
+]);
+
+function findDirectLocalModelPinReads(root = SERVER_ROOT) {
+ const violations = [];
+ const walk = (directory) => {
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ if (entry.isDirectory() && ['.git', 'build', 'data', 'dist', 'node_modules'].includes(entry.name)) continue;
+ if (entry.isSymbolicLink()) continue;
+ const absolutePath = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ walk(absolutePath);
+ continue;
+ }
+ if (!entry.isFile() || !/\.(?:js|mjs)$/.test(entry.name) || /\.test\.(?:js|mjs)$/.test(entry.name)) continue;
+ const file = relative(SERVER_ROOT, absolutePath).replaceAll('\\', '/');
+ if (ALLOWED_PIN_READERS.has(file)) continue;
+ const source = readFileSync(absolutePath, 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/^\s*\/\/.*$/gm, '');
+ if (MODEL_PIN_READ.test(source)) violations.push(file);
+ }
+ };
+ walk(root);
+ return violations.sort();
+}
+
const CODEX_ON = { codex: { enabled: true, codexPath: '/bin/codex' } };
const run = (data) => prepareGenerateParams({ data, files: undefined, referenceImageFields: [] });
@@ -72,6 +107,23 @@ describe('selectLocalImageModel', () => {
expect(selectLocalImageModel(undefined, models, 'klein').id).toBe('dev');
expect(selectLocalImageModel(undefined, models, 'retired-model').id).toBe('dev');
});
+
+ it('treats a record pin as a hardware-filtered preference before the install pin', () => {
+ const models = [
+ { id: 'dev', hardwareCompatibility: { state: 'available' } },
+ { id: 'record-pin', hardwareCompatibility: { state: 'unavailable' } },
+ { id: 'install-pin', hardwareCompatibility: { state: 'available' } },
+ ];
+ const settings = { imageGen: { local: { modelId: 'install-pin' } } };
+ expect(selectLocalImageModelFromSettings(settings, undefined, models, 'record-pin').id).toBe('install-pin');
+ expect(selectLocalImageModelFromSettings(settings, undefined, models, 'dev').id).toBe('dev');
+ });
+});
+
+describe('local model pin ownership', () => {
+ it('allows direct install-pin reads only in its resolver and settings writers', () => {
+ expect(findDirectLocalModelPinReads()).toEqual([]);
+ });
});
beforeEach(() => {
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index 7ab67a4171..7cd9d94d41 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -36,13 +36,12 @@ import {
import { universeAestheticLine } from '../lib/universeVisualStyle.js';
import {
extractCharacterPromptCommon,
- resolveSheetModelId,
REFERENCE_SHEET_CONSTANTS,
} from './universeCharacterSheet.js';
-import { getImageModels } from '../lib/mediaModels.js';
import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';
import { IMAGE_GEN_MODE } from './imageGen/modes.js';
import { resolveRenderTargetConfig } from './imageGen/cloudProviderConfig.js';
+import { selectLocalImageModelFromSettings } from './imageGen/prepareParams.js';
import { RENDER_TARGET } from '../lib/renderTargets.js';
import {
datasetImagePath,
@@ -273,8 +272,7 @@ async function resolveRenderParams({ modelId: modelOverride = null } = {}) {
return { base: { ...base, ...cloud.providerParams }, activeMode, modelId: cloud.modelId };
}
if (activeMode === IMAGE_GEN_MODE.LOCAL) {
- const allModels = getImageModels();
- const modelId = resolveSheetModelId({ override: modelOverride, settings, allModels });
+ const modelId = selectLocalImageModelFromSettings(settings, modelOverride)?.id || null;
if (!modelId) {
throw new ServerError(
'No local image-gen models are registered. Install a model via `bash scripts/setup-image-video.sh` before generating dataset images.',
diff --git a/server/services/loraDatasetGenerate.test.js b/server/services/loraDatasetGenerate.test.js
index 189fbef92a..164036df77 100644
--- a/server/services/loraDatasetGenerate.test.js
+++ b/server/services/loraDatasetGenerate.test.js
@@ -1,5 +1,11 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+const renderMocks = vi.hoisted(() => ({
+ getSettings: vi.fn(),
+ enqueueJob: vi.fn(),
+ getImageModels: vi.fn(),
+}));
+
// Mock the data deps so getDatasetVariationAxes can be exercised without a
// real universe/dataset store — it's a thin getDataset → live-subject →
// deriveVariationAxes wrapper, and the live-subject lookup is the part the
@@ -30,15 +36,33 @@ vi.mock('sharp', () => ({
toFile: vi.fn(async () => ({})),
})),
}));
+vi.mock('./settings.js', () => ({ getSettings: (...args) => renderMocks.getSettings(...args) }));
+vi.mock('./mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => renderMocks.enqueueJob(...args),
+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },
+}));
+vi.mock('./imageGen/index.js', () => ({
+ IMAGE_GEN_MODE: { LOCAL: 'local', CODEX: 'codex', EXTERNAL: 'external' },
+ resolveImageCleaners: vi.fn(() => ({ cleanC2PA: false, denoise: false })),
+}));
+vi.mock('../lib/mediaModels.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getImageModels: (...args) => renderMocks.getImageModels(...args),
+}));
import {
- buildDatasetImagePrompt, deriveVariationAxes, getDatasetVariationAxes,
+ buildDatasetImagePrompt, deriveVariationAxes, generateDatasetImages, getDatasetVariationAxes,
normalizeCropProposals, proposeCropRegions, sliceReferenceSheet,
} from './loraDatasetGenerate.js';
import { extractSubjectSignaturePhrases } from './loraDatasetSubject.js';
import { getDataset, updateDataset } from './loraDatasets.js';
import { getUniverse } from './universeBuilder.js';
+const renderModels = [
+ { id: 'dev', hardwareCompatibility: { state: 'available' } },
+ { id: 'pinned-model', hardwareCompatibility: { state: 'available' } },
+];
+
// Pure-function coverage for the kind-aware prompt builder + variation axes.
// These are the highest-risk new logic in the object/place feature: a
// regression in the subject block or negative-prompt selection would ship
@@ -224,6 +248,32 @@ describe('getDatasetVariationAxes', () => {
});
});
+describe('generateDatasetImages local model selection', () => {
+ beforeEach(() => {
+ getDataset.mockResolvedValue({
+ id: 'ds1',
+ character: { entryKind: 'characters', universeId: 'u1', entryId: 'c1' },
+ images: [],
+ });
+ getUniverse.mockResolvedValue({
+ artStyle: 'ink-and-wash',
+ characters: [{ id: 'c1', name: 'Example Character', physicalDescription: 'A traveler.' }],
+ });
+ updateDataset.mockResolvedValue({});
+ renderMocks.getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'pinned-model' } },
+ });
+ renderMocks.enqueueJob.mockReturnValue({ jobId: 'job-1' });
+ renderMocks.getImageModels.mockReturnValue(renderModels);
+ });
+
+ it('queues the install-pinned model explicitly', async () => {
+ await generateDatasetImages('ds1', { count: 1 });
+
+ expect(renderMocks.enqueueJob.mock.calls[0][0].params.modelId).toBe('pinned-model');
+ });
+});
+
describe('normalizeCropProposals', () => {
const dims = { width: 1000, height: 800 };
diff --git a/server/services/pipeline/comicPages.js b/server/services/pipeline/comicPages.js
index 0d9e4039a0..023261505a 100644
--- a/server/services/pipeline/comicPages.js
+++ b/server/services/pipeline/comicPages.js
@@ -293,7 +293,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
// composeComicPagePrompt only returns '' when panels.length === 0, which is
// already rejected above. The "(continuation of previous beat)" placeholder
// covers panels with no description, so the prompt is non-empty by here.
- const { loras: characterLoras, triggerByKey } = await applyCharacterLorasToRender({
+ const { loras: characterLoras, triggerByKey, selectedModel } = await applyCharacterLorasToRender({
matchedCharacters, mode, options, settings,
});
@@ -307,6 +307,7 @@ export async function enqueueVisualComicPage(issueId, options = {}) {
const jobId = enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, initImagePath, initImageStrength, ...loraRenderOptions(characterLoras) },
+ selectedModel,
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})` : ''}`,
});
@@ -542,7 +543,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
});
}
- const { loras: characterLoras } = await applyCharacterLorasToRender({
+ const { loras: characterLoras, selectedModel } = await applyCharacterLorasToRender({
matchedCharacters, mode, options, settings,
});
// composeVisualPrompt is shared with the episode-video batch path, so the
@@ -556,6 +557,7 @@ export async function enqueueVisualImage(issueId, stageId, options = {}) {
const jobId = enqueueImageJob({
prompt, world, settings, mode, series,
options: { ...options, ...loraRenderOptions(characterLoras) },
+ selectedModel,
owner: `pipeline:${issueId}:${stageId}`,
logLine: `🎬 Pipeline visual — issue=${issueId.slice(0, 8)} stage=${stageId}`,
});
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index 279deafcb0..da2d76b2d0 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -18,7 +18,6 @@ import { ServerError } from '../../lib/errorHandler.js';
import { buildScenePrompt, buildPlaceByKey, matchScenePlace } from '../../lib/scenePrompt.js';
import { composeStyledPrompt } from '../../lib/composeStyledPrompt.js';
import { buildVisualStyleClause, mergeNegativePromptTokens } from '../../lib/universeVisualStyle.js';
-import { getImageModels } from '../../lib/mediaModels.js';
import { loraCompatKey } from '../../lib/runners.js';
import { resolveCharacterLoras } from '../characterLoraResolver.js';
import { pickCanon } from './seriesCanon.js';
@@ -27,6 +26,7 @@ import { resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
import { imageModeCandidates, pickUsableMode } from '../../lib/renderModeLadder.js';
import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { resolveImageCleaners } from '../imageGen/index.js';
+import { selectLocalImageModelFromSettings } from '../imageGen/prepareParams.js';
const joinStyleParts = (...parts) =>
parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');
@@ -85,32 +85,26 @@ const resolveMode = (options, settings, series = null) => pickUsableMode(setting
* Resolve trained character LoRAs for a pipeline render. Local mode only —
* codex has no LoRA support, so resolution is skipped there with one log
* line. `options.applyCharacterLoras === false` is the per-render opt-out
- * (default on). The compat key comes from the model the local render will
- * actually use (request override → saved local model → first registered),
- * mirroring resolveSheetModelId's order; an unresolvable model just means
- * no compat filtering.
+ * (default on). The compat key comes from the model selected for the local
+ * render, and that same model is carried into the queued job.
*
- * Returns `{ loras, triggerByKey }` — `triggerByKey` maps canon
+ * Returns `{ loras, triggerByKey, selectedModel }` — `triggerByKey` maps canon
* entryId/ingredientId → trigger word for prompt weaving.
*/
async function applyCharacterLorasToRender({ matchedCharacters, mode, options, settings }) {
- const none = { loras: [], triggerByKey: new Map() };
- if (options.applyCharacterLoras === false || !matchedCharacters?.length) return none;
+ const none = (selectedModel = null) => ({ loras: [], triggerByKey: new Map(), selectedModel });
+ if (options.applyCharacterLoras === false || !matchedCharacters?.length) return none();
if (mode !== IMAGE_GEN_MODE.LOCAL) {
console.log(`⚠️ character LoRA skipped — ${mode} mode has no LoRA support`);
- return none;
+ return none();
}
- const allModels = getImageModels();
- const model = allModels.find((m) => m.id === options.modelId)
- || allModels.find((m) => m.id === settings?.imageGen?.local?.modelId)
- || allModels[0]
- || null;
- const compatKey = model ? loraCompatKey(model) : null;
+ const selectedModel = selectLocalImageModelFromSettings(settings, options.modelId);
+ const compatKey = selectedModel ? loraCompatKey(selectedModel) : null;
const loras = await resolveCharacterLoras(matchedCharacters, { compatKey }).catch((err) => {
console.error(`❌ character LoRA resolution failed: ${err?.message}`);
return [];
});
- if (!loras.length) return none;
+ if (!loras.length) return none(selectedModel);
const triggerByKey = new Map();
for (const lora of loras) {
if (!lora.triggerWord || !lora.character) continue;
@@ -118,7 +112,7 @@ async function applyCharacterLorasToRender({ matchedCharacters, mode, options, s
if (lora.character.ingredientId) triggerByKey.set(lora.character.ingredientId, lora.triggerWord);
}
console.log(`🧬 character LoRA auto-apply — ${loras.map((l) => `${l.character?.name || '?'}→${l.filename}`).join(', ')}`);
- return { loras, triggerByKey };
+ return { loras, triggerByKey, selectedModel };
}
// These renders do NOT opt out of the server-side trigger weave (#4665). Both
@@ -230,7 +224,7 @@ const loadBibleContext = async (issueId) => {
return { ...chain, settings };
};
-const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine, series = null }) => {
+const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLine, series = null, selectedModel = 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
@@ -279,9 +273,23 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
recordMode: seriesPin.mode,
recordModel: seriesPin.modelId,
});
+ const localModel = mode === IMAGE_GEN_MODE.LOCAL
+ ? selectedModel || selectLocalImageModelFromSettings(settings, options.modelId)
+ : null;
+ if (mode === IMAGE_GEN_MODE.LOCAL && !localModel) {
+ throw new ServerError('No local image-gen models are registered.', {
+ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL',
+ });
+ }
const params = cloud
? { ...cloud.jobParams, cleanC2PA, denoise, ...baseParams }
- : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };
+ : {
+ pythonPath: settings.imageGen?.local?.pythonPath || null,
+ modelId: localModel.id,
+ cleanC2PA,
+ denoise,
+ ...baseParams,
+ };
const { jobId } = enqueueJob({ kind: 'image', params, owner });
console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);
return jobId;
diff --git a/server/services/pipeline/visualStageHelpers.test.js b/server/services/pipeline/visualStageHelpers.test.js
new file mode 100644
index 0000000000..94f3e354b1
--- /dev/null
+++ b/server/services/pipeline/visualStageHelpers.test.js
@@ -0,0 +1,80 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ selectLocalImageModelFromSettings: vi.fn(),
+ enqueueJob: vi.fn(),
+ loraCompatKey: vi.fn(),
+ resolveCharacterLoras: vi.fn(),
+}));
+
+vi.mock('../imageGen/prepareParams.js', () => ({
+ selectLocalImageModelFromSettings: (...args) => mocks.selectLocalImageModelFromSettings(...args),
+}));
+vi.mock('../mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => mocks.enqueueJob(...args),
+ cancelJob: vi.fn(),
+}));
+vi.mock('../../lib/runners.js', () => ({ loraCompatKey: (...args) => mocks.loraCompatKey(...args) }));
+vi.mock('../characterLoraResolver.js', () => ({
+ resolveCharacterLoras: (...args) => mocks.resolveCharacterLoras(...args),
+}));
+vi.mock('../imageGen/index.js', () => ({
+ resolveImageCleaners: vi.fn(() => ({ cleanC2PA: false, denoise: false })),
+}));
+
+import { applyCharacterLorasToRender, enqueueImageJob, loraRenderOptions } from './visualStageHelpers.js';
+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
+
+const settings = { imageGen: { local: { pythonPath: '/python', modelId: 'install-pin' } } };
+const selectedModel = { id: 'resolved-model' };
+const characterLora = {
+ filename: 'character.safetensors',
+ scale: 0.8,
+ triggerWord: 'sampleword',
+ character: { entryId: 'entry-1' },
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.selectLocalImageModelFromSettings.mockReturnValue(selectedModel);
+ mocks.enqueueJob.mockReturnValue({ jobId: 'job-1' });
+ mocks.loraCompatKey.mockReturnValue('compat:resolved-model');
+ mocks.resolveCharacterLoras.mockResolvedValue([characterLora]);
+});
+
+describe('pipeline local model selection', () => {
+ it('uses one resolved model for LoRA compatibility and the queued job', async () => {
+ const settingsInUse = { ...settings };
+ const options = {};
+ const loraResult = await applyCharacterLorasToRender({
+ matchedCharacters: [{ entryId: 'entry-1' }],
+ mode: IMAGE_GEN_MODE.LOCAL,
+ options,
+ settings: settingsInUse,
+ });
+
+ enqueueImageJob({
+ prompt: 'pipeline render',
+ world: null,
+ settings: settingsInUse,
+ options: { ...options, ...loraRenderOptions(loraResult.loras) },
+ mode: IMAGE_GEN_MODE.LOCAL,
+ owner: 'pipeline-test',
+ logLine: 'pipeline test',
+ selectedModel: loraResult.selectedModel,
+ });
+
+ expect(mocks.selectLocalImageModelFromSettings).toHaveBeenCalledOnce();
+ expect(mocks.selectLocalImageModelFromSettings).toHaveBeenCalledWith(settingsInUse, undefined);
+ expect(mocks.loraCompatKey).toHaveBeenCalledWith(selectedModel);
+ expect(mocks.resolveCharacterLoras).toHaveBeenCalledWith(
+ [{ entryId: 'entry-1' }],
+ { compatKey: 'compat:resolved-model' },
+ );
+ expect(mocks.enqueueJob.mock.calls[0][0].params).toMatchObject({
+ modelId: 'resolved-model',
+ loraFilenames: ['character.safetensors'],
+ loraScales: [0.8],
+ });
+ });
+});
diff --git a/server/services/pipeline/visualStages.test.js b/server/services/pipeline/visualStages.test.js
index c11e359c07..812cf54e9f 100644
--- a/server/services/pipeline/visualStages.test.js
+++ b/server/services/pipeline/visualStages.test.js
@@ -118,9 +118,9 @@ vi.mock('../stageRunner.js', () => ({ runStagedLLM: (...a) => runStagedLLMMock(.
vi.mock('../../lib/mediaModels.js', () => ({
getDefaultVideoModelId: () => 'ltx-default',
getVideoModels: () => [{ id: 'ltx-default' }, { id: 'ltx-extra' }],
- // Character-LoRA auto-apply resolves the render model's compat key from
- // the image registry; empty registry → no compat filtering in tests.
- getImageModels: () => [],
+ // Local queueing now requires an explicit selected model ID, and character
+ // LoRA compatibility must resolve against that same model.
+ getImageModels: () => [{ id: 'dev', hardwareCompatibility: { state: 'available' } }],
}));
// Keep the character-LoRA resolver off the real data/loras directory; tests
diff --git a/server/services/sprites/reference.js b/server/services/sprites/reference.js
index 68975c8923..8c2a011472 100644
--- a/server/services/sprites/reference.js
+++ b/server/services/sprites/reference.js
@@ -32,10 +32,11 @@ import { ServerError } from '../../lib/errorHandler.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import {
- IMAGE_GEN_MODE, resolveQueueImageMode, LOCAL_IMAGEGEN_DEFAULT_MODEL,
+ IMAGE_GEN_MODE, resolveQueueImageMode,
} from '../imageGen/modes.js';
import { resolveImageCleaners } from '../imageGen/index.js';
import { resolveRenderTargetConfig } from '../imageGen/cloudProviderConfig.js';
+import { selectLocalImageModelFromSettings } from '../imageGen/prepareParams.js';
import { imageModeCandidates, pickUsableMode } from '../../lib/renderModeLadder.js';
import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { getSettings } from '../settings.js';
@@ -574,10 +575,18 @@ async function startReferenceGenerationImpl(recordId, body, upload = null) {
const localPinModel = (!spritePin.mode || spritePin.mode === IMAGE_GEN_MODE.LOCAL)
? spritePin.modelId
: null;
+ const selectedLocalModel = mode === IMAGE_GEN_MODE.LOCAL
+ ? selectLocalImageModelFromSettings(settings, body.model || undefined, undefined, localPinModel)
+ : null;
+ if (mode === IMAGE_GEN_MODE.LOCAL && !selectedLocalModel) {
+ throw new ServerError('No local image-gen models are registered.', {
+ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL',
+ });
+ }
const effectiveModel = mode === IMAGE_GEN_MODE.CODEX || mode === IMAGE_GEN_MODE.AGY
? cloud.modelId
: mode === IMAGE_GEN_MODE.LOCAL
- ? (body.model || localPinModel || settings.imageGen?.local?.modelId || LOCAL_IMAGEGEN_DEFAULT_MODEL)
+ ? selectedLocalModel.id
: null;
const baseParams = {
prompt,
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index c6d9ad8ed0..015abf357f 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -15,6 +15,11 @@ import { mkdir, writeFile, readFile } from 'fs/promises';
import { writeCandidatePng, placeCandidate as placeCandidateFixture, expectCarriesCorrection } from './spriteTestFixtures.js';
const TEST_ROOT = mkdtempSync(join(tmpdir(), 'sprite-reference-test-'));
+const localImageModels = [
+ { id: 'dev', hardwareCompatibility: { state: 'available' } },
+ { id: 'flux-dev-4bit', hardwareCompatibility: { state: 'available' } },
+ { id: 'record-incompatible', hardwareCompatibility: { state: 'unavailable' } },
+];
// MUTATE actual.PATHS (don't replace the object): fileUtils' internal
// resolvers (resolveImageInputPath / resolveSpriteImageInput) close over the
@@ -39,6 +44,10 @@ vi.mock('../mediaJobQueue/index.js', () => ({
vi.mock('../imageGen/index.js', () => ({
resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
}));
+vi.mock('../../lib/mediaModels.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getImageModels: () => localImageModels,
+}));
const settings = {
imageGen: {
@@ -797,6 +806,17 @@ describe('lockReference', () => {
expect(call.params.spriteRef.model).toBe('flux-dev-4bit');
});
+ it('falls through an incompatible record pin to the compatible install pin', async () => {
+ const id = newId();
+ await createCharacter(id, { imageMode: 'local', imageModelId: 'record-incompatible' });
+
+ await startReferenceGeneration(id, { target: 'turnaround', designPrompt: 'example design' });
+
+ const { params } = enqueueJob.mock.calls[0][0];
+ expect(params.modelId).toBe('flux-dev-4bit');
+ expect(params.spriteRef.model).toBe('flux-dev-4bit');
+ });
+
it('rebases legacy repo-root manifest paths from a phase-1 import', async () => {
const id = newId();
await createCharacter(id);
diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.js
index aa108179ab..96726e7cef 100644
--- a/server/services/universeBuilderRender.js
+++ b/server/services/universeBuilderRender.js
@@ -16,10 +16,9 @@ import { getSettings } from './settings.js';
import { findOrCreateUniverseCollection } from './mediaCollections.js';
import { buildUniverseRunTag } from './universeRunTag.js';
import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';
-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 { resolveLocalImageModel } from './imageGen/prepareParams.js';
import { RENDER_TARGET, recordRenderPin } from '../lib/renderTargets.js';
import { resolveImageCleaners } from './imageGen/index.js';
import { getStylePresetById } from '../lib/writersRoomStylePresets.js';
@@ -86,21 +85,13 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
// Mirror the upfront validation /api/image-gen/generate does so a doomed
// batch fails before any jobs land in the queue.
if (cloud && !cloud.enabled) throw cloud.disabledError;
- if (mode === IMAGE_GEN_MODE.LOCAL) {
- const py = settings.imageGen?.local?.pythonPath || null;
- const allModels = getImageModels();
- if (body.modelId && !allModels.some((m) => m.id === body.modelId)) {
- throw new ServerError(`Unknown modelId: ${body.modelId}`, { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' });
- }
- const selectedModel = allModels.find((m) => m.id === body.modelId)
- ?? allModels.find((m) => m.id === 'dev')
- ?? allModels[0];
- if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !py) {
- throw new ServerError(
- 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',
- { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },
- );
- }
+ const localModel = mode === IMAGE_GEN_MODE.LOCAL
+ ? resolveLocalImageModel(settings, { modelId: body.modelId })
+ : null;
+ if (mode === IMAGE_GEN_MODE.LOCAL && !localModel.selectedModel) {
+ throw new ServerError('No local image-gen models are registered.', {
+ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL',
+ });
}
// Provision the collection up front so renders can be tagged as they
@@ -195,10 +186,15 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
});
} else {
// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).
- const py = settings.imageGen?.local?.pythonPath || null;
queued = enqueueJob({
kind: 'image',
- params: { pythonPath: py, modelId: body.modelId, cleanC2PA, denoise, ...params },
+ params: {
+ pythonPath: localModel.pythonPath,
+ modelId: localModel.selectedModel.id,
+ cleanC2PA,
+ denoise,
+ ...params,
+ },
});
}
jobIds.push(queued.jobId);
diff --git a/server/services/universeBuilderRender.test.js b/server/services/universeBuilderRender.test.js
index f87c444b43..d3508f2c62 100644
--- a/server/services/universeBuilderRender.test.js
+++ b/server/services/universeBuilderRender.test.js
@@ -1,15 +1,78 @@
-/**
- * Smoke test for universeBuilderRender.js
- *
- * Verifies the module imports correctly and exports the expected function.
- * Full integration tests for the render flow live in universeBuilder.test.js.
- */
-
-import { describe, it, expect } from 'vitest';
-
-describe('universeBuilderRender', () => {
- it('exports renderUniverseJobs as a function', async () => {
- const mod = await import('./universeBuilderRender.js');
- expect(typeof mod.renderUniverseJobs).toBe('function');
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getUniverse: vi.fn(),
+ compilePrompts: vi.fn(),
+ recordRun: vi.fn(),
+ enqueueJob: vi.fn(),
+ getSettings: vi.fn(),
+ getImageModels: vi.fn(),
+ findOrCreateUniverseCollection: vi.fn(),
+ buildUniverseRunTag: vi.fn(),
+ registerUniverseBuilderRun: vi.fn(),
+}));
+
+vi.mock('./universeBuilder.js', () => ({
+ getUniverse: (...args) => mocks.getUniverse(...args),
+ compilePrompts: (...args) => mocks.compilePrompts(...args),
+ recordRun: (...args) => mocks.recordRun(...args),
+}));
+vi.mock('./settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));
+vi.mock('./mediaJobQueue/index.js', () => ({ enqueueJob: (...args) => mocks.enqueueJob(...args) }));
+vi.mock('./mediaCollections.js', () => ({ findOrCreateUniverseCollection: (...args) => mocks.findOrCreateUniverseCollection(...args) }));
+vi.mock('./universeRunTag.js', () => ({ buildUniverseRunTag: (...args) => mocks.buildUniverseRunTag(...args) }));
+vi.mock('./universeBuilderCollectionHook.js', () => ({ registerUniverseBuilderRun: (...args) => mocks.registerUniverseBuilderRun(...args) }));
+vi.mock('./imageGen/index.js', () => ({
+ IMAGE_GEN_MODE: { LOCAL: 'local', EXTERNAL: 'external' },
+ resolveImageCleaners: () => ({ cleanC2PA: false, denoise: false }),
+}));
+vi.mock('../lib/mediaModels.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getImageModels: (...args) => mocks.getImageModels(...args),
+}));
+
+import { renderUniverseJobs } from './universeBuilderRender.js';
+
+const models = [
+ { id: 'dev', hardwareCompatibility: { state: 'available' } },
+ { id: 'pinned-model', hardwareCompatibility: { state: 'available' } },
+ { id: 'incompatible-pin', hardwareCompatibility: { state: 'unavailable' } },
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getUniverse.mockResolvedValue({ id: 'universe-1', name: 'Example Universe' });
+ mocks.compilePrompts.mockReturnValue([{ prompt: 'render prompt', category: 'character', label: 'Example' }]);
+ mocks.recordRun.mockImplementation(async (run) => run);
+ mocks.enqueueJob.mockReturnValue({ jobId: 'job-1' });
+ mocks.getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'pinned-model' } },
+ });
+ mocks.getImageModels.mockReturnValue(models);
+ mocks.findOrCreateUniverseCollection.mockResolvedValue({ id: 'collection-1', name: 'Universe: Example' });
+ mocks.buildUniverseRunTag.mockResolvedValue({ universeId: 'universe-1' });
+});
+
+describe('renderUniverseJobs local model selection', () => {
+ it('queues the install-pinned model when the request leaves modelId unset', async () => {
+ await renderUniverseJobs('universe-1', {}, (err) => err);
+
+ expect(mocks.enqueueJob.mock.calls[0][0].params.modelId).toBe('pinned-model');
+ });
+
+ it('falls back from an incompatible install pin to a hardware-compatible model', async () => {
+ mocks.getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'incompatible-pin' } },
+ });
+
+ await renderUniverseJobs('universe-1', {}, (err) => err);
+
+ expect(mocks.enqueueJob.mock.calls[0][0].params.modelId).toBe('dev');
+ });
+
+ it('keeps the existing unknown-model 400 when the request names an unregistered model', async () => {
+ await expect(renderUniverseJobs('universe-1', { modelId: 'missing-model' }, (err) => err))
+ .rejects.toMatchObject({ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' });
+ expect(mocks.enqueueJob).not.toHaveBeenCalled();
});
});
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index bb905914da..cb4c76142e 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -20,11 +20,11 @@ import { getSettings } from './settings.js';
import { getUniverse, updateUniverse } from './universeBuilder.js';
import { purgeReferenceSheetFromAllUniverses } from './universeCanon.js';
import { universeAestheticLine } from '../lib/universeVisualStyle.js';
-import { getImageModels } from '../lib/mediaModels.js';
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 { selectLocalImageModelFromSettings } from './imageGen/prepareParams.js';
import { RENDER_TARGET, recordRenderPin } from '../lib/renderTargets.js';
import {
flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,
@@ -59,22 +59,6 @@ function resolveSheetDimensions(mode, builtWidth, builtHeight) {
return { width: builtWidth || DEFAULT_WIDTH, height: builtHeight || DEFAULT_HEIGHT };
}
-// Resolve the local-mode model id. With pure text-template rendering we no
-// longer depend on FLUX.2-specific init-image / multi-ref flags, so any
-// registered model is fair game. Order:
-// 1. Explicit override (when it matches a registered model).
-// 2. settings.imageGen.local.modelId.
-// 3. First available local model.
-// Returns null when nothing is registered; caller surfaces the 400.
-export function resolveSheetModelId({ override, settings, allModels }) {
- const findById = (id) => (typeof id === 'string' ? allModels.find((m) => m.id === id) : null);
- const trimmedOverride = typeof override === 'string' ? override.trim() : '';
- return findById(trimmedOverride)?.id
- ?? findById(settings?.imageGen?.local?.modelId)?.id
- ?? allModels[0]?.id
- ?? null;
-}
-
const DEFAULT_EXPRESSIONS = Object.freeze([
'neutral', 'curious', 'worried', 'surprised', 'amused', 'determined', 'relaxed',
]);
@@ -186,7 +170,7 @@ export function buildCharacterReferenceSheetPrompt(universe, character) {
width: DEFAULT_WIDTH,
height: DEFAULT_HEIGHT,
// modelId is resolved at render time from current settings — see
- // resolveSheetModelId. Returned as null here so the prompt builder stays
+ // the shared local model selector. Returned as null here so the prompt builder stays
// pure (no settings I/O) and the renderer is the single decision point.
modelId: null,
};
@@ -456,8 +440,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
modelId = cloud.modelId;
params = { ...baseParams, ...cloud.providerParams };
} else if (activeMode === IMAGE_GEN_MODE.LOCAL) {
- const allModels = getImageModels();
- modelId = resolveSheetModelId({ override: options.modelId, settings, allModels });
+ modelId = selectLocalImageModelFromSettings(settings, options.modelId)?.id || null;
if (!modelId) {
throw new ServerError(
'No local image-gen models are registered. Install a model via `bash scripts/setup-image-video.sh` before generating a reference sheet.',
diff --git a/server/services/universeCharacterSheet.modelResolution.test.js b/server/services/universeCharacterSheet.modelResolution.test.js
new file mode 100644
index 0000000000..4ce517d678
--- /dev/null
+++ b/server/services/universeCharacterSheet.modelResolution.test.js
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getUniverse: vi.fn(),
+ getSettings: vi.fn(),
+ enqueueJob: vi.fn(),
+ getImageModels: vi.fn(),
+ buildUniverseRunTag: vi.fn(),
+ claimPendingSheetSlot: vi.fn(),
+}));
+
+vi.mock('./universeBuilder.js', () => ({ getUniverse: (...args) => mocks.getUniverse(...args) }));
+vi.mock('./settings.js', () => ({ getSettings: (...args) => mocks.getSettings(...args) }));
+vi.mock('./mediaJobQueue/index.js', () => ({
+ enqueueJob: (...args) => mocks.enqueueJob(...args),
+ mediaJobEvents: { on: vi.fn(), off: vi.fn() },
+}));
+vi.mock('./universeRunTag.js', () => ({ buildUniverseRunTag: (...args) => mocks.buildUniverseRunTag(...args) }));
+vi.mock('./universeCharacterSheetSlot.js', () => ({
+ claimPendingSheetSlot: (...args) => mocks.claimPendingSheetSlot(...args),
+ getPendingSheetSlot: vi.fn(),
+ releasePendingSheetSlot: vi.fn(),
+}));
+vi.mock('./imageGen/index.js', () => ({
+ IMAGE_GEN_MODE: { LOCAL: 'local', CODEX: 'codex', EXTERNAL: 'external' },
+ resolveImageCleaners: vi.fn(() => ({ cleanC2PA: false, denoise: false })),
+}));
+vi.mock('../lib/mediaModels.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ getImageModels: (...args) => mocks.getImageModels(...args),
+}));
+
+import { renderCharacterReferenceSheet } from './universeCharacterSheet.js';
+
+const models = [
+ { id: 'dev', hardwareCompatibility: { state: 'available' } },
+ { id: 'pinned-model', hardwareCompatibility: { state: 'available' } },
+ { id: 'incompatible-pin', hardwareCompatibility: { state: 'unavailable' } },
+];
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getUniverse.mockResolvedValue({
+ id: 'universe-1',
+ name: 'Example Universe',
+ influences: { embrace: [] },
+ characters: [{ id: 'character-1', name: 'Example Character' }],
+ });
+ mocks.getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'pinned-model' } },
+ });
+ mocks.enqueueJob.mockReturnValue({ jobId: 'job-1', position: 1 });
+ mocks.getImageModels.mockReturnValue(models);
+ mocks.buildUniverseRunTag.mockResolvedValue(null);
+});
+
+describe('renderCharacterReferenceSheet local model selection', () => {
+ it('queues the install-pinned model when the request has no model override', async () => {
+ await renderCharacterReferenceSheet('universe-1', 'character-1');
+
+ expect(mocks.enqueueJob.mock.calls[0][0].params.modelId).toBe('pinned-model');
+ });
+
+ it('skips an incompatible install pin and queues the compatible default', async () => {
+ mocks.getSettings.mockResolvedValue({
+ imageGen: { mode: 'local', local: { pythonPath: '/python', modelId: 'incompatible-pin' } },
+ });
+
+ await renderCharacterReferenceSheet('universe-1', 'character-1');
+
+ expect(mocks.enqueueJob.mock.calls[0][0].params.modelId).toBe('dev');
+ });
+});
diff --git a/server/services/universeCharacterSheet.test.js b/server/services/universeCharacterSheet.test.js
index 8c431d4b38..cb99b19e57 100644
--- a/server/services/universeCharacterSheet.test.js
+++ b/server/services/universeCharacterSheet.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildCharacterReferenceSheetPrompt, REFERENCE_SHEET_CONSTANTS, resolveSheetModelId, listSheetVariants } from './universeCharacterSheet.js';
+import { buildCharacterReferenceSheetPrompt, REFERENCE_SHEET_CONSTANTS, listSheetVariants } from './universeCharacterSheet.js';
const baseUniverse = {
id: 'u-123',
@@ -126,7 +126,7 @@ describe('universeCharacterSheet — buildCharacterReferenceSheetPrompt', () =>
expect(out.height).toBe(REFERENCE_SHEET_CONSTANTS.DEFAULT_HEIGHT);
// modelId resolution is deferred to render time (uses current settings,
// not a hardcoded default). Pure prompt builder returns null so the
- // caller chooses — see resolveSheetModelId.
+ // caller chooses through the shared local image model selector.
expect(out.modelId).toBeNull();
expect(out.negativePrompt).toContain('watermark');
expect(out.negativePrompt).toContain('text artifacts');
@@ -153,52 +153,6 @@ describe('universeCharacterSheet — buildCharacterReferenceSheetPrompt', () =>
});
});
-describe('universeCharacterSheet — resolveSheetModelId', () => {
- const flux2Model = { id: 'flux2-klein-9b', runner: 'flux2' };
- const devModel = { id: 'dev', runner: 'mflux' };
-
- it('honors an explicit override when the model exists in the registry', () => {
- const out = resolveSheetModelId({
- override: 'dev',
- settings: { imageGen: { local: { modelId: 'flux2-klein-9b' } } },
- allModels: [flux2Model, devModel],
- });
- expect(out).toBe('dev');
- });
-
- it('ignores an override that does not match any registered model, falling through to settings', () => {
- const out = resolveSheetModelId({
- override: 'made-up-model',
- settings: { imageGen: { local: { modelId: 'dev' } } },
- allModels: [flux2Model, devModel],
- });
- expect(out).toBe('dev');
- });
-
- it('honors the user-configured local modelId from settings', () => {
- const out = resolveSheetModelId({
- override: '',
- settings: { imageGen: { local: { modelId: 'dev' } } },
- allModels: [flux2Model, devModel],
- });
- expect(out).toBe('dev');
- });
-
- it('falls back to the first available local model as a last resort', () => {
- const out = resolveSheetModelId({
- override: undefined,
- settings: {},
- allModels: [devModel, flux2Model],
- });
- expect(out).toBe('dev');
- });
-
- it('returns null when no models are registered (caller surfaces the 400)', () => {
- const out = resolveSheetModelId({ override: undefined, settings: {}, allModels: [] });
- expect(out).toBeNull();
- });
-});
-
describe('universeCharacterSheet — variant catalog + prototype-pollution guard', () => {
// Renderer/delete read the registry by string key. Without an own-property
// check, an attacker can send `variant=constructor` (or any Object.prototype