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([imagegen-local-defer-module-load-side-effects]): drop dead IMAGE_MODELS export and revert lazy-import workaround

[._.]/ Adam Eivy5034faa66f75
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index 1bbbab5bb0..023dcd65c2 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -30,8 +30,10 @@ const IS_WIN = process.platform === 'win32';
import { getImageModels, isFlux2, isZImage, isErnie } from '../../lib/mediaModels.js';
-export const IMAGE_MODELS = Object.fromEntries(getImageModels().map((m) => [m.id, m]));
-
+// Read the registry lazily — callers below hit getImageModels() at request
+// time. A prior `IMAGE_MODELS = Object.fromEntries(getImageModels()...)`
+// snapshot lived here but fired loadMediaModels() at import time, breaking
+// any test that mocks PATHS.data to a non-writable path.
export const listImageModels = () => getImageModels();
// Per-job clients: jobId -> { clients, status, meta, broadcast }
@@ -219,13 +221,11 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', m
// callers that bypass the queue must not run two concurrent renders — the
// activeProcess handle below would be clobbered and cancel() would orphan
// the first child.
- // Use the registry cache view (which applies the per-platform `broken`
- // filter via getImageModels) rather than the module-load IMAGE_MODELS
- // snapshot. Note: loadMediaModels memoizes on first read — on-disk edits
- // to data/media-models.json still need a server restart to apply.
- // Don't re-check model.broken here: getImageModels() already filtered
- // current-platform entries; an extra truthiness check would also reject
- // entries broken on the OTHER platform (e.g. 'windows' on a macOS box).
+ // loadMediaModels memoizes — on-disk edits to data/media-models.json still
+ // need a server restart to apply. Don't re-check model.broken here:
+ // getImageModels() already filtered current-platform entries; an extra
+ // check would also reject entries broken on the OTHER platform (e.g.
+ // 'windows' on a macOS box).
const model = getImageModels().find((m) => m.id === modelId);
if (!model) throw new ServerError(`Unknown or unsupported model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
// Both flux2 and z-image runners resolve their own Python via the FLUX.2
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 2ee9607691..88687a820e 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -11,12 +11,13 @@ vi.mock('../../lib/pythonSetup.js', () => ({
FLUX2_VENV_DEFAULT: '/fake/home/.portos/venv-flux2/bin/python3',
}));
-// Point the registry at a temp dir so importing local.js (which calls
-// getImageModels() at module load and triggers seedIfMissing in
-// mediaModels.js) doesn't write to the repo's data/media-models.json.
-// Save + restore the prior env value and call vi.resetModules() so a
-// previously-cached mediaModels.js inside the same vitest worker doesn't
-// stick to the wrong file. Pattern matches server/lib/mediaModels.test.js.
+// Point the registry at a temp dir. local.js itself no longer calls
+// getImageModels() at module load — but any test that exercises a code path
+// invoking the registry (e.g. generateImage → loadMediaModels → seedIfMissing)
+// would still write to the repo's data/media-models.json without this. Save +
+// restore the prior env value and call vi.resetModules() so a previously
+// cached mediaModels.js inside the same vitest worker doesn't stick to the
+// wrong file. Pattern matches server/lib/mediaModels.test.js.
let tmpRegistryDir;
let priorRegistryEnv;
let buildArgs;
diff --git a/server/services/universeBuilderCollectionHook.js b/server/services/universeBuilderCollectionHook.js
index 07b835cfc1..d4a3ce939f 100644
--- a/server/services/universeBuilderCollectionHook.js
+++ b/server/services/universeBuilderCollectionHook.js
@@ -21,27 +21,12 @@
* the run finishes naturally.
*/
-import { writeFile } from 'fs/promises';
import { mediaJobEvents } from './mediaJobQueue/index.js';
import { addItem, ERR_DUPLICATE } from './mediaCollections.js';
import { withReexportSuppressed, emitRecordUpdated } from './sharing/recordEvents.js';
import { appendEntryImageRef, getUniverse, ENTRY_REF_KIND } from './universeBuilder.js';
-
-// `imageGen/local.js` runs `getImageModels()` at module-load time, which
-// requires the on-disk media-models registry directory to be writable. That
-// fires through `routes/universeBuilder.js` → this hook on every importer
-// (e.g. `routes/pipeline.js`), tripping any test that mocks PATHS to a
-// non-writable path. Lazy-loading here keeps the production path identical
-// (one resolve per hook init, then a cached module ref) while letting
-// pipeline/routes tests load without invoking the registry side-effect.
-let _readImageSidecar = null;
-async function getReadImageSidecar() {
- if (!_readImageSidecar) {
- const mod = await import('./imageGen/local.js');
- _readImageSidecar = mod.readImageSidecar;
- }
- return _readImageSidecar;
-}
+import { readImageSidecar } from './imageGen/local.js';
+import { atomicWrite } from '../lib/fileUtils.js';
// runId → { universeId, pending, universePromise? }. Pure in-memory; lost on restart.
// `universePromise` memoizes the universe doc for the lifetime of the batch so
@@ -116,7 +101,6 @@ function buildSidecarPatch({ tag, universe }) {
// PNG itself is missing too — creating a universe-only sidecar in that case
// would leave a stub record with no prompt/seed/model on disk.
async function enrichSidecar(filename, patch) {
- const readImageSidecar = await getReadImageSidecar();
const { path, metadata } = await readImageSidecar(filename);
if (!metadata || Object.keys(metadata).length === 0) return;
let changed = false;
@@ -129,7 +113,10 @@ async function enrichSidecar(filename, patch) {
}
}
if (!changed) return;
- await writeFile(path, JSON.stringify(next, null, 2));
+ // Atomic (temp + rename) so concurrent readers — listGallery, the
+ // lightbox metadata fetch, or another batch entry — can't observe a
+ // mid-truncate empty file.
+ await atomicWrite(path, next);
}
let completedHandler = null;