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

refactor: drop dead imports and move local-image-model validation out of the route

[._.]/ Adam Eivy2bb6b8aa4e4f
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 986925597f..6477c52f2b 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -22,12 +22,11 @@ import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/ind
import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';
import setupRouter from './imageGenSetup.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
-import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';
-import { usesDiffusersRunner } from '../lib/runners.js';
+import { getImageModels, requiredReposForModel } from '../lib/mediaModels.js';
import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';
import { startHfDownloadStream } from '../lib/sseDownload.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
-import { prepareGenerateParams } from '../services/imageGen/prepareParams.js';
+import { prepareGenerateParams, resolveLocalImageModel } from '../services/imageGen/prepareParams.js';
import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';
import { join, basename } from 'node:path';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
@@ -39,7 +38,6 @@ import {
import { getSketchPngPath, isValidKey as isValidSketchKey } from '../services/mediaSketches.js';
import { itemKey } from '../lib/mediaItemKey.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
-import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';
import * as characterService from '../services/character.js';
import { randomUUID } from 'crypto';
import { buildUniverseRunTag } from '../services/universeRunTag.js';
@@ -426,47 +424,14 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
return res.json(queuedImageResponse({ ...queued, mode, model: cloud.modelId }));
}
if (mode === IMAGE_GEN_MODE.LOCAL) {
- const py = settings.imageGen?.local?.pythonPath || null;
- // Pre-validate config: mflux models need pythonPath, FLUX.2 doesn't
- // (it uses its own bundled venv). Without this guard, the queue would
- // accept the job and only surface the failure async over SSE.
- const allModels = getImageModels();
- // Reject a typo'd modelId synchronously rather than enqueueing a doomed
- // job. When omitted, fall through to the default ('dev'-ish) — the
- // worker does the same lookup so behavior stays consistent.
- if (params.modelId && !allModels.some((m) => m.id === params.modelId)) {
- throw new ServerError(
- `Unknown modelId: ${params.modelId}`,
- { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },
- );
- }
- const selectedModel = allModels.find((m) => m.id === params.modelId)
- ?? allModels.find((m) => m.id === 'dev')
- ?? allModels[0];
- // Edit-only models (Qwen-Image-Edit) load a pipeline that REQUIRES a
- // source image. Reject a text-only submission up-front rather than
- // enqueueing a job that crashes deep inside diffusers. `params.initImagePath`
- // is already populated above from either an uploaded `initImage` or a
- // gallery `initImageFile`.
- if (isEditOnly(selectedModel) && !params.initImagePath) {
- throw new ServerError(
- `${selectedModel.name || selectedModel.id} is an image-edit model — it requires a source image. Upload an init image to use it.`,
- { status: 400, code: 'IMAGE_GEN_EDIT_IMAGE_REQUIRED' },
- );
- }
- 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 { pythonPath: py, selectedModel } = resolveLocalImageModel(settings, params);
const queued = enqueueJob({
kind: 'image',
params: { pythonPath: py, ...params },
});
- // Resolve the effective model the same way the validation block above
- // does so the response reflects the actual fallback chain (caller
- // modelId → 'dev' → allModels[0]) rather than just the requested id.
+ // selectedModel reflects the actual fallback chain resolveLocalImageModel
+ // applied (caller modelId → 'dev' → allModels[0]) rather than just the
+ // requested id.
return res.json(queuedImageResponse({
...queued,
mode: IMAGE_GEN_MODE.LOCAL,
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 1e0264ed00..a61225353c 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -19,7 +19,7 @@ import { existsSync, watch as fsWatch } from 'fs';
import { join, dirname, resolve as resolvePath, sep as PATH_SEP, basename } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveGalleryImage, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
+import { atomicWrite, assertSafeFilename, detectImageFormat, ensureDir, listDirectoryByExtension, PATHS, safeJSONParse, resolveImageInputPath, tryReadFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -35,7 +35,7 @@ import { parseByteProgress, formatDownloadMessage } from '../videoGen/generateVi
const IS_WIN = process.platform === 'win32';
-import { getImageModels, isFlux2, isZImage, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';
+import { getImageModels, isFlux2, isErnie, isHiDream, isQwen } from '../../lib/mediaModels.js';
import { usesDiffusersRunner, flux2Bf16BaseRepo } from '../../lib/runners.js';
// Read the registry lazily — callers below hit getImageModels() at request
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index b7272c3894..5659baa179 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -36,7 +36,8 @@ import {
import { RENDER_TARGET, recordRenderPin } from '../../lib/renderTargets.js';
import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';
import { getUniverseRenderPin } from '../universeBuilder/crud.js';
-import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
+import { getImageModels, isFlux2, isEditOnly } from '../../lib/mediaModels.js';
+import { usesDiffusersRunner } from '../../lib/runners.js';
// The job tags that name the record owning a render, each mapped to the record
// loader and the render target whose `renderDefaults` pin backs it. A generate
@@ -296,3 +297,57 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
return { data, mode, settings, uploadedTempPaths };
}
+
+/**
+ * resolveLocalImageModel — pre-dispatch validation for the LOCAL backend,
+ * called from the route right before it enqueues a local job.
+ *
+ * Resolves the effective model via the same fallback chain the local worker
+ * uses (`params.modelId` → `'dev'` → the first registered model) and
+ * validates it can actually run: an edit-only model (e.g. Qwen-Image-Edit)
+ * requires a source image, and any model that isn't FLUX.2 or diffusers-run
+ * needs a configured pythonPath. Throws the identical `ServerError`s (same
+ * status/code/message, same order) the route used to throw inline — these
+ * surface directly in the UI.
+ *
+ * @param {object} settings - raw settings object (as returned by getSettings())
+ * @param {object} params - in-flight generate params (post prepareGenerateParams)
+ * @returns {{ pythonPath: string|null, selectedModel: object|undefined }}
+ */
+export function resolveLocalImageModel(settings, params) {
+ const pythonPath = settings.imageGen?.local?.pythonPath || null;
+ // Pre-validate config: mflux models need pythonPath, FLUX.2 doesn't
+ // (it uses its own bundled venv). Without this guard, the queue would
+ // accept the job and only surface the failure async over SSE.
+ const allModels = getImageModels();
+ // Reject a typo'd modelId synchronously rather than enqueueing a doomed
+ // job. When omitted, fall through to the default ('dev'-ish) — the
+ // worker does the same lookup so behavior stays consistent.
+ if (params.modelId && !allModels.some((m) => m.id === params.modelId)) {
+ throw new ServerError(
+ `Unknown modelId: ${params.modelId}`,
+ { status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },
+ );
+ }
+ const selectedModel = allModels.find((m) => m.id === params.modelId)
+ ?? allModels.find((m) => m.id === 'dev')
+ ?? allModels[0];
+ // Edit-only models (Qwen-Image-Edit) load a pipeline that REQUIRES a
+ // source image. Reject a text-only submission up-front rather than
+ // enqueueing a job that crashes deep inside diffusers. `params.initImagePath`
+ // is already populated above from either an uploaded `initImage` or a
+ // gallery `initImageFile`.
+ if (isEditOnly(selectedModel) && !params.initImagePath) {
+ throw new ServerError(
+ `${selectedModel.name || selectedModel.id} is an image-edit model — it requires a source image. Upload an init image to use it.`,
+ { status: 400, code: 'IMAGE_GEN_EDIT_IMAGE_REQUIRED' },
+ );
+ }
+ if (selectedModel && !isFlux2(selectedModel) && !usesDiffusersRunner(selectedModel) && !pythonPath) {
+ throw new ServerError(
+ 'Local image generation is not configured (settings.imageGen.local.pythonPath is missing).',
+ { status: 400, code: 'IMAGE_GEN_NOT_CONFIGURED' },
+ );
+ }
+ return { pythonPath, selectedModel };
+}
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index 4e9d15c80b..28b7dae11d 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -10,7 +10,6 @@
* Split out of the former 4,004-line peerSync.js (#1830).
*/
import { join } from 'path';
-import { PATHS, readJSONFile } from '../../lib/fileUtils.js';
import { isStr } from '../../lib/storyBible.js';
import { isPlainObject } from '../../lib/objects.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
@@ -18,12 +17,11 @@ import { peerFetch } from '../../lib/peerHttpClient.js';
import { withAbortTimeout } from '../../lib/abortTimeout.js';
import { sanitizeRecordForWire } from '../../lib/syncWire.js';
import { setSyncBaseHash, contentHashForRecord, flushBaseHashes } from '../../lib/conflictJournal.js';
-import { sanitizeAssetFilename } from './buckets.js';
import {
buildPortosMeta,
formatVersionGap,
} from '../../lib/schemaVersions.js';
-import { getInstanceId, getPeers, UNKNOWN_INSTANCE_ID } from '../instances.js';
+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { getUniverse } from '../universeBuilder.js';
import { getSeries } from '../pipeline/series.js';
import { listIssues } from '../pipeline/issues.js';