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: move business logic out of imageGen/pipeline routes into services

[._.]/ Adam Eivy7713ec753fbb
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 438eacc339..889d81fe70 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -9,6 +9,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.cybercity', path: '/city', label: 'City', section: 'Main', aliases: ['city', 'cybercity'], keywords: ['3d', 'visualization', 'cybercity'] },
{ id: 'nav.cybercity.settings', path: '/city/settings', label: 'City Settings', section: 'Main', aliases: ['city settings', 'cybercity settings', 'city-settings', 'cybercity-config'], keywords: ['cybercity', 'settings', '3d', 'configure'] },
{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },
+ { id: 'nav.templates', path: '/templates', label: 'Templates', section: 'Main', aliases: ['templates', 'app-templates'], keywords: ['app template', 'create app', 'pre-configured', 'starter'] },
{ id: 'nav.catalog', path: '/catalog', label: 'Catalog', section: 'Create', aliases: ['catalog', 'ingredients', 'cast', 'creative-catalog'], keywords: ['character', 'place', 'object', 'idea', 'scene', 'concept', 'inventory', 'reference', 'creative'] },
{ id: 'nav.catalog.ingest', path: '/catalog/ingest', label: 'Catalog Ingest', section: 'Create', aliases: ['catalog-ingest', 'ingest', 'paste-scrap', 'extract-ingredients'], keywords: ['paste', 'snippet', 'scene', 'idea', 'extract', 'scrap', 'import-catalog'] },
diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.js
index fc7e44212f..dc3ef42c23 100644
--- a/server/lib/navManifest.test.js
+++ b/server/lib/navManifest.test.js
@@ -293,7 +293,6 @@ const NAV_COVERAGE_OPT_OUT = new Map([
['/apps/create', 'create-app form, reached via the "New App" button on /apps'],
['/feature-agents/create', 'create-agent form, reached via the "New Agent" button'],
['/login', 'auth gate — surfaced only when settings.secrets.auth is enabled, reached via 401 redirect'],
- ['/templates', 'legacy templates page, intentionally not surfaced in nav'],
['/universes/new', 'create-mode sentinel for the Universe Builder editor'],
]);
diff --git a/server/lib/sseDownload.js b/server/lib/sseDownload.js
index 4305f7e829..ec12b14b67 100644
--- a/server/lib/sseDownload.js
+++ b/server/lib/sseDownload.js
@@ -11,12 +11,29 @@ import { downloadHfRepo } from './hfDownload.js';
const inFlight = new Map(); // repo -> { promise, kill }
-const SSE_HEADERS = {
+export const SSE_HEADERS = {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
};
+/**
+ * Open an SSE response and return write-safe helpers. Canonical replacement
+ * for the per-route `writeHead → send → safeEnd` boilerplate: `send` JSON-
+ * encodes one event per frame and both helpers no-op after the response ends.
+ *
+ * @param {import('http').ServerResponse} res - Express/HTTP response
+ * @returns {{ send: (event: object) => void, safeEnd: () => void }}
+ */
+export function openSseStream(res) {
+ res.writeHead(200, SSE_HEADERS);
+ const send = (event) => {
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
+ };
+ const safeEnd = () => { if (!res.writableEnded) res.end(); };
+ return { send, safeEnd };
+}
+
export async function startHfDownloadStream({ req, res, repo, repos, alreadyDownloadedMessage }) {
// Caller passes either `repo` (single string, legacy callers) OR `repos`
// (ordered array, used when a model has auxiliary repos that must be
@@ -26,11 +43,7 @@ export async function startHfDownloadStream({ req, res, repo, repos, alreadyDown
const targets = Array.isArray(repos)
? repos.filter((r) => typeof r === 'string' && r.length > 0)
: (typeof repo === 'string' && repo.length > 0 ? [repo] : []);
- res.writeHead(200, SSE_HEADERS);
- const send = (event) => {
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
- };
- const safeEnd = () => { if (!res.writableEnded) res.end(); };
+ const { send, safeEnd } = openSseStream(res);
if (targets.length === 0) {
send({ type: 'error', message: 'No repo specified for download.' });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index c49ee76367..60d8f06df0 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2064,3 +2064,11 @@ export const storyIssuesGenerateSchema = z.object({
// on the arc.
seasonId: z.preprocess(emptyToUndefined, z.string().trim().max(64).optional()),
}).strict();
+
+// Per-request LLM provider/model override. Shared by universe-builder expand
+// routes and pipeline arc-planning routes. Optional so callers that omit the
+// llm field fall back to the server's active provider.
+export const llmSchema = z.object({
+ provider: z.string().trim().max(80).nullable().optional(),
+ model: z.string().trim().max(200).nullable().optional(),
+}).optional();
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 8f31ece14d..3c43277bce 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -11,22 +11,21 @@
import { Router } from 'express';
import { z } from 'zod';
-import { copyFile, unlink } from 'fs/promises';
-import { randomUUID } from 'crypto';
+import { unlink, stat } from 'fs/promises';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import {
validateRequest, imageEdgeSchema, refineImagePixelCap, PIXEL_CAP_MESSAGE,
} from '../lib/validation.js';
import { optionalUploadFields } from '../lib/multipart.js';
import * as imageGen from '../services/imageGen/index.js';
-import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveImageCleaners } from '../services/imageGen/index.js';
+import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';
import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';
import { usesDiffusersRunner } from '../lib/runners.js';
import { inspectModelCache } from '../lib/hfCache.js';
-import { startHfDownloadStream } from '../lib/sseDownload.js';
+import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
import {
REQUIRED_PACKAGES, detectPython, installPackages,
createVenv, isAllowedPython, pipNameFor,
@@ -34,19 +33,16 @@ import {
detectArm64Python, HOST_ARCH, probePythonHealth,
} from '../lib/pythonSetup.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../lib/fileUtils.js';
+import { prepareGenerateParams } from '../services/imageGen/prepareParams.js';
+import { applyImageClean, applyWatermarkRemoval, applyLightRegenVariant } from '../services/imageGen/variants.js';
import { join } from 'node:path';
-import { readFile, writeFile, stat } from 'fs/promises';
import { STYLE_PRESETS } from '../lib/writersRoomStylePresets.js';
-import { cleanImageBuffer } from '../lib/imageClean.js';
-import { removeCornerWatermark } from '../lib/imageWatermark.js';
import {
resolveRegenBackend, getRegenAvailability, readImageDimensions, buildRegenParams,
REGEN_STRENGTH_MIN, REGEN_STRENGTH_MAX,
- resolveRegenStrengthDefault, applyLightRegen, computePixelDelta,
+ resolveRegenStrengthDefault,
} from '../services/imageGen/regen.js';
import { purgeImageRefFromAllUniverses } from '../services/universeCanon.js';
-import { listCollections, addItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
-import { itemKey } from '../lib/mediaItemKey.js';
const router = Router();
@@ -226,129 +222,11 @@ const queuedImageResponse = ({ jobId, position, status, mode, model }) => ({
router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
const data = validateRequest(generateSchema, coerceFormFields(req.body));
- // Resolve init image source: uploaded file > gallery filename. The local
- // service double-checks that the path stays under PATHS.images.
- let initImagePath = null;
- const uploadedTempPaths = [];
- const initUpload = req.files?.initImage;
- const referenceImagePaths = [];
- const referenceImageStrengths = [];
- // Pair strengths by PACK position (post-filter), not slot position — the
- // client renumbers populated slots into `referenceImage1..N` and sends a
- // parallel `referenceStrengths` array sized N. A curl user could leave a
- // gap (`referenceImage2` + `referenceImage4` only); the strength at index 0
- // still pairs with the first surviving upload in slot order.
- const referenceUploads = REFERENCE_IMAGE_FIELDS
- .map((field) => req.files?.[field])
- .filter(Boolean)
- .map((upload, packedIndex) => ({ upload, strength: data.referenceStrengths?.[packedIndex] }));
-
- // Best-effort cleanup of every multer-staged file currently on `req.files`.
- // The multipart parser writes uploads to `os.tmpdir()` as they stream in,
- // so a 400 thrown from validation BEFORE we've registered the `res.on('close')`
- // sweep would otherwise leak those temp files. Call this from any pre-stage
- // throw site (FLUX.2-only gate, non-local-backend gate).
- const cleanupReqFilesTemp = () => {
- if (!req.files) return;
- for (const f of Object.values(req.files)) {
- if (f?.path) unlink(f.path).catch(() => {});
- }
- };
-
- // Resolve the effective backend BEFORE staging reference uploads — only the
- // local FLUX.2 runner consumes `referenceImagePaths`; an `external` or `codex`
- // request that uploaded refs would otherwise stage files under
- // `PATHS.imageRefs` and write sidecar metadata claiming references were used,
- // while the actual generation silently ignored them. (Reading settings here
- // is cheap — it's already read again below for the per-mode dispatch.)
- const settings = await getSettings();
- const mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
- // Resolve cleaners ONCE at the route layer so all three dispatch paths
- // (synchronous external, codex queue, local queue) see the same values.
- // Stamp onto `data` so they flow through the spread-into-params calls
- // below verbatim.
- const cleaners = resolveImageCleaners(data, settings, mode);
- data.cleanC2PA = cleaners.cleanC2PA;
- data.denoise = cleaners.denoise;
- delete data.autoClean; // legacy field — already mapped into both flags above
-
- // Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
- // buildArgs only emits --reference-images/--reference-strengths inside the
- // isFlux2 branch, and codex/external backends don't read these fields at all.
- // Reject up-front rather than copying the uploads to PATHS.imageRefs and
- // silently dropping them downstream (which would orphan files on disk and
- // produce metadata sidecars that lie about how the render was conditioned).
- if (referenceUploads.length) {
- if (mode !== IMAGE_GEN_MODE.LOCAL) {
- cleanupReqFilesTemp();
- throw new ServerError(
- 'Reference images are only supported for local FLUX.2 renders',
- { status: 400, code: 'REFERENCE_IMAGES_LOCAL_ONLY' },
- );
- }
- const candidate = getImageModels().find((m) => m.id === data.modelId)
- ?? getImageModels().find((m) => m.id === 'dev')
- ?? getImageModels()[0];
- if (!isFlux2(candidate)) {
- cleanupReqFilesTemp();
- throw new ServerError(
- 'Reference images are only supported for FLUX.2 models',
- { status: 400, code: 'REFERENCE_IMAGES_FLUX2_ONLY' },
- );
- }
- }
-
- if (initUpload) await ensureDir(PATHS.images);
- if (referenceUploads.length) await ensureDir(PATHS.imageRefs);
- if (initUpload) {
- // Trust the validated mimetype from the fileFilter — picking the ext
- // off the original filename can mismatch the bytes (e.g. HEIC saved
- // as .jpg). MIME_TO_EXT only contains formats the fileFilter accepts.
- const ext = MIME_TO_EXT[(initUpload.mimetype || '').toLowerCase()] || '.png';
- const initFilename = `init-${randomUUID()}${ext}`;
- initImagePath = join(PATHS.images, initFilename);
- await copyFile(initUpload.path, initImagePath);
- uploadedTempPaths.push(initUpload.path);
- } else if (data.initImageFile) {
- const resolved = resolveGalleryImage(data.initImageFile);
- if (!resolved) {
- throw new ServerError('Init image not found in gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });
- }
- initImagePath = resolved;
- }
- // Multi-reference editing (FLUX.2). Walk packed slot entries in submit
- // order — each contributes a path + its parallel strength. Empty slots
- // are filtered out above so the runner sees `referenceImagePaths: [p1, ...]`
- // and aligns strengths by index.
- for (const { upload, strength } of referenceUploads) {
- const ext = MIME_TO_EXT[(upload.mimetype || '').toLowerCase()] || '.png';
- const refFilename = `ref-${randomUUID()}${ext}`;
- const refPath = join(PATHS.imageRefs, refFilename);
- await copyFile(upload.path, refPath);
- uploadedTempPaths.push(upload.path);
- referenceImagePaths.push(refPath);
- // Default to 1.0 when the client didn't send a parallel strength entry,
- // matching the "full influence" intent of an uploaded reference.
- referenceImageStrengths.push(typeof strength === 'number' ? strength : 1.0);
- }
- // Strip the route-only fields — providers expect normalized `…Path(s)`.
- delete data.initImageFile;
- delete data.referenceStrengths;
- if (initImagePath) data.initImagePath = initImagePath;
- if (referenceImagePaths.length) {
- data.referenceImagePaths = referenceImagePaths;
- data.referenceImageStrengths = referenceImageStrengths;
- }
- // Empty prompt is allowed for i2i / local / external, but Codex text-to-image
- // (no init image) still needs one — reject synchronously here so direct API
- // callers get a 400 instead of a 200-then-async-job-failure. Mirrors the guard
- // in codex.js and the client's codexNeedsPrompt gate.
- if (mode === IMAGE_GEN_MODE.CODEX && !initImagePath && !data.prompt?.trim()) {
- throw new ServerError('Prompt is required for Codex text-to-image', { status: 400, code: 'VALIDATION_ERROR' });
- }
- if (data.guidance == null && data.cfgScale != null) {
- data.guidance = data.cfgScale;
- }
+ const { data: params, mode, settings, uploadedTempPaths } = await prepareGenerateParams({
+ data,
+ files: req.files,
+ referenceImageFields: REFERENCE_IMAGE_FIELDS,
+ });
// Multer's tmp upload is no longer needed once we've copied it into
// PATHS.images. Use res.on('close') so the temp files are cleaned up whether
@@ -384,7 +262,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
mode: IMAGE_GEN_MODE.CODEX,
codexPath: c.codexPath,
model: c.model,
- ...data,
+ ...params,
},
});
return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.CODEX, model: c.model || null }));
@@ -398,21 +276,21 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// 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 (data.modelId && !allModels.some((m) => m.id === data.modelId)) {
+ if (params.modelId && !allModels.some((m) => m.id === params.modelId)) {
throw new ServerError(
- `Unknown modelId: ${data.modelId}`,
+ `Unknown modelId: ${params.modelId}`,
{ status: 400, code: 'IMAGE_GEN_UNKNOWN_MODEL' },
);
}
- const selectedModel = allModels.find((m) => m.id === data.modelId)
+ 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. `data.initImagePath`
+ // 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) && !data.initImagePath) {
+ 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' },
@@ -426,7 +304,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
}
const queued = enqueueJob({
kind: 'image',
- params: { pythonPath: py, ...data },
+ 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
@@ -434,10 +312,10 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
return res.json(queuedImageResponse({
...queued,
mode: IMAGE_GEN_MODE.LOCAL,
- model: selectedModel?.id || data.modelId || 'dev',
+ model: selectedModel?.id || params.modelId || 'dev',
}));
}
- res.json(await imageGen.generateImage(data));
+ res.json(await imageGen.generateImage(params));
}));
router.post('/avatar', asyncHandler(async (req, res) => {
@@ -588,78 +466,8 @@ router.post('/:filename/visibility', asyncHandler(async (req, res) => {
router.post('/:filename/clean', asyncHandler(async (req, res) => {
const filename = req.params.filename;
local.assertGalleryFilename(filename);
-
- const sourcePath = join(PATHS.images, filename);
- const [buffer, { metadata: sourceMeta }] = await Promise.all([
- readFile(sourcePath).catch((err) => {
- if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
- throw err;
- }),
- local.readImageSidecar(filename),
- ]);
-
- const result = await cleanImageBuffer(buffer);
- if (result.format !== 'png') {
- throw new ServerError('Gallery images must be PNG', { status: 400, code: 'UNSUPPORTED_FORMAT' });
- }
-
- // The `_clean-aggressive` filename suffix and `cleanLevel: 'aggressive'`
- // sidecar field survive the light/aggressive collapse so already-cleaned
- // images on disk keep round-tripping through the gallery unchanged. A future
- // rename to `_cleaned.png` would need a backfill migration.
- const base = filename.slice(0, -'.png'.length);
- const outFilename = `${base}_clean-aggressive.png`;
- const outPath = join(PATHS.images, outFilename);
- const sidecarPath = join(PATHS.images, `${base}_clean-aggressive.metadata.json`);
-
- const createdAt = new Date().toISOString();
- // Strip `hidden` so a clean of a hidden source still surfaces in the gallery
- // — cleaning is a deliberate user action that implies wanting to see the result.
- // Strip `filename`/`id` so listGallery's `...metadata` spread doesn't overwrite
- // the disk-derived filename for the cleaned copy with the source's filename.
- const { hidden: _hidden, filename: _srcFilename, id: _srcId, ...sourceMetaForCleaned } = sourceMeta;
- const cleanedMeta = {
- ...sourceMetaForCleaned,
- createdAt,
- cleanedFrom: filename,
- cleanLevel: 'aggressive',
- c2paStripped: result.c2paStripped,
- };
-
- await Promise.all([
- writeFile(outPath, result.data),
- writeFile(sidecarPath, JSON.stringify(cleanedMeta, null, 2)),
- ]);
-
- // Auto-file the cleaned copy into every collection that contained the
- // source. Without this, users who built a collection around an original
- // would have to manually re-add the cleaned variant — the prior behavior
- // surprised users (cleaned image vanished from "their" view). Best-effort:
- // a collection-add failure must not fail the clean itself. ERR_DUPLICATE
- // is silently swallowed so re-cleans of an already-filed pair are no-ops.
- const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
- console.warn(`⚠️ Auto-file cleaned ${outFilename} → source collections failed: ${err?.message || err}`);
- return [];
- });
-
- console.log(`🧼 Cleaned ${filename} → ${outFilename} (${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
-
- // sourceMeta first so explicit fields below win on key collisions (the
- // cleaned copy's createdAt must reflect the cleaning, not the original).
- res.json({
- ...sourceMetaForCleaned,
- filename: outFilename,
- path: `/data/images/${outFilename}`,
- createdAt,
- sizeBefore: result.sizeBefore,
- sizeAfter: result.sizeAfter,
- sizeBytes: result.sizeAfter,
- width: result.width,
- height: result.height,
- cleanedFrom: filename,
- cleanLevel: 'aggressive',
- c2paStripped: result.c2paStripped,
- });
+ const { metadata: sourceMeta } = await local.readImageSidecar(filename);
+ res.json(await applyImageClean({ filename, sourceMeta }));
}));
// Visible-watermark removal — erases the Gemini / Nano-Banana bottom-right ✦.
@@ -673,143 +481,10 @@ router.post('/:filename/remove-watermark', asyncHandler(async (req, res) => {
const filename = req.params.filename;
local.assertGalleryFilename(filename);
const body = validateRequest(removeWatermarkSchema, req.body || {});
-
- const sourcePath = join(PATHS.images, filename);
- const [buffer, { metadata: sourceMeta }] = await Promise.all([
- readFile(sourcePath).catch((err) => {
- if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
- throw err;
- }),
- local.readImageSidecar(filename),
- ]);
-
- const result = await removeCornerWatermark(buffer, { size: body.size, region: body.region });
-
- const base = filename.slice(0, -'.png'.length);
- const outFilename = `${base}_nowatermark.png`;
- const outPath = join(PATHS.images, outFilename);
- const sidecarPath = join(PATHS.images, `${base}_nowatermark.metadata.json`);
- // Anchor the variant group at the root original (same rule as /clean):
- // de-watermarking a cleaned/regenerated variant groups under the root.
- const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
- ? sourceMeta.cleanedFrom : filename;
- const createdAt = new Date().toISOString();
- // Strip hidden/filename/id so listGallery's `...metadata` spread doesn't
- // overwrite the disk-derived filename or re-hide the deliberate variant. Also
- // drop the regen lineage fields: de-watermarking a REGENERATED source would
- // otherwise inherit `regenerated:true` + stale fidelity numbers, and both the
- // lightbox lineage (`describeCleanedLineage`) and variant grouping check
- // `regenerated` BEFORE `watermarkRemoved` — so the variant would mislabel as
- // "Regenerated … % changed" instead of "Watermark removed from …".
- const {
- hidden: _hidden, filename: _srcFilename, id: _srcId,
- regenerated: _regenerated, regenStrength: _regenStrength,
- regenSteps: _regenSteps, regenModelId: _regenModelId,
- regenPixelDeltaPct: _regenPixelDeltaPct, regenPsnr: _regenPsnr,
- regenMethod: _regenMethod,
- ...sourceMetaForVariant
- } = sourceMeta;
- const variantMeta = {
- ...sourceMetaForVariant,
- createdAt,
- cleanedFrom: groupRoot,
- watermarkRemoved: true,
- watermarkRegion: result.region,
- };
- await Promise.all([
- writeFile(outPath, result.data),
- writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
- ]);
-
- const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
- console.warn(`⚠️ Auto-file de-watermarked ${outFilename} → collections failed: ${err?.message || err}`);
- return [];
- });
- console.log(`✦ Removed watermark ${filename} → ${outFilename} (${result.region.w}×${result.region.h} @ ${result.region.x},${result.region.y}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
-
- res.json({
- ...variantMeta,
- filename: outFilename,
- path: `/data/images/${outFilename}`,
- sizeBefore: result.sizeBefore,
- sizeAfter: result.sizeAfter,
- sizeBytes: result.sizeAfter,
- width: result.width,
- height: result.height,
- });
+ const { metadata: sourceMeta } = await local.readImageSidecar(filename);
+ res.json(await applyWatermarkRemoval({ filename, sourceMeta, size: body.size, region: body.region }));
}));
-// CPU-only "light" regen (issue #912). The no-GPU fallback: applies sharp's
-// spatial-domain disruption stack (resize-squeeze + color nudge + median/sharpen)
-// to overwrite SynthID's resolution-dependent carriers without a FLUX runner.
-// Synchronous like Clean — writes a `_regen-light.png` variant + sidecar and
-// returns it. Honestly LESS reliable than the GPU round-trip (no FFT phase
-// subtraction); the sidecar stamps `regenMethod: 'light-spatial'` so the UI
-// never overclaims. Mirrors the manual-clean route's file/sidecar/collection shape.
-async function runLightRegen({ filename, sourceAbsPath, sourceMeta }) {
- const buffer = await readFile(sourceAbsPath).catch((err) => {
- if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
- throw err;
- });
- const result = await applyLightRegen(buffer);
- if (!result) {
- throw new ServerError('Could not decode image for light regen', { status: 400, code: 'INVALID_IMAGE' });
- }
-
- const base = filename.slice(0, -'.png'.length);
- const outFilename = `${base}_regen-light.png`;
- const outPath = join(PATHS.images, outFilename);
- const sidecarPath = join(PATHS.images, `${base}_regen-light.metadata.json`);
- // Anchor the variant group at the root original (same rule as buildRegenParams):
- // regenerating a cleaned/regenerated variant must group under the root, not orphan.
- const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
- ? sourceMeta.cleanedFrom : filename;
- const createdAt = new Date().toISOString();
- // Strip hidden/filename/id so the listGallery `...metadata` spread doesn't
- // overwrite the disk-derived filename or re-hide the deliberate variant.
- // Also strip the FLUX-regen-specific fields: when the source is itself a
- // prior FLUX regen, carrying its regenStrength/Steps/ModelId + stale
- // delta into a SPATIAL pass would make the lineage row falsely read
- // "· N% denoise" (a light pass has no denoise) and show a stale fidelity.
- const {
- hidden: _hidden, filename: _srcFilename, id: _srcId,
- regenStrength: _rs, regenSteps: _rst, regenModelId: _rm,
- regenPixelDeltaPct: _rpd, regenPsnr: _rp,
- ...sourceMetaForVariant
- } = sourceMeta;
-
- // Compare the in-memory source/output buffers — no need to re-read outPath
- // off disk just to measure the delta.
- const delta = await computePixelDelta(buffer, result.data).catch(() => null);
- const variantMeta = {
- ...sourceMetaForVariant,
- createdAt,
- cleanedFrom: groupRoot,
- regenerated: true,
- regenMethod: 'light-spatial',
- ...(delta ? { regenPixelDeltaPct: delta.pixelDeltaPct, regenPsnr: delta.psnr } : {}),
- };
- await Promise.all([
- writeFile(outPath, result.data),
- writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
- ]);
-
- const filedCollections = await autoFileCleanedToSourceCollections(filename, outFilename).catch((err) => {
- console.warn(`⚠️ Auto-file light-regen ${outFilename} → collections failed: ${err?.message || err}`);
- return [];
- });
- console.log(`♻️ Light-regen ${filename} → ${outFilename} (${delta ? `${delta.pixelDeltaPct}% changed` : 'fidelity n/a'}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''})`);
-
- // Response is the sidecar record plus the disk-derived fields listGallery adds.
- return {
- ...variantMeta,
- filename: outFilename,
- path: `/data/images/${outFilename}`,
- width: result.width,
- height: result.height,
- };
-}
-
// SynthID-defeat regeneration (issue #912). Round-trips an existing gallery
// image through local FLUX img2img at low–moderate denoise so the per-pixel
// watermark is overwritten by fresh sampling — the only honest defeat path
@@ -837,7 +512,7 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
// for installs that can't run the GPU round-trip — synchronous like Clean:
// it writes a `_regen-light.png` variant inline and returns it (no queue).
if (body.method === 'light') {
- return res.json(await runLightRegen({ filename, sourceAbsPath, sourceMeta }));
+ return res.json(await applyLightRegenVariant({ filename, sourceAbsPath, sourceMeta }));
}
const backend = await resolveRegenBackend({ sourceModelId: sourceMeta.modelId });
@@ -865,29 +540,6 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.LOCAL, model: backend.model.id }));
}));
-// Add the cleaned-image filename to every collection that already contains
-// the source filename. Returns the ids of the collections that received the
-// new entry (excluding ones that already contained the cleaned filename).
-// Cross-collection writes run in parallel — addItem serializes per file write
-// internally, so concurrent calls on different collections are safe.
-async function autoFileCleanedToSourceCollections(sourceFilename, cleanedFilename) {
- const sourceKey = itemKey({ kind: 'image', ref: sourceFilename });
- const all = await listCollections();
- const matching = all.filter((c) => c.items.some((it) => itemKey(it) === sourceKey));
- if (matching.length === 0) return [];
- const results = await Promise.all(matching.map(async (c) => {
- try {
- await addItem(c.id, { kind: 'image', ref: cleanedFilename });
- return c.id;
- } catch (err) {
- if (err?.code === ERR_DUPLICATE) return null;
- console.warn(`⚠️ Auto-file ${cleanedFilename} → collection ${c.id} failed: ${err?.message || err}`);
- return null;
- }
- }));
- return results.filter(Boolean);
-}
-
// --- Local-mode setup automation ---
router.get('/setup/python', asyncHandler(async (_req, res) => {
@@ -909,15 +561,7 @@ router.get('/setup/python', asyncHandler(async (_req, res) => {
let flux2InstallInFlight = null;
router.get('/setup/flux2-install', asyncHandler(async (req, res) => {
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- });
- const send = (event) => {
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
- };
- const safeEnd = () => { if (!res.writableEnded) res.end(); };
+ const { send, safeEnd } = openSseStream(res);
// Skip only when the venv binary AND the import work — a half-broken venv
// (binary present, packages missing from a killed mid-install) needs to
@@ -1156,19 +800,10 @@ router.get('/setup/install', (req, res) => {
return res.end(JSON.stringify({ error: `Packages not in allowlist: ${disallowed.join(', ')}` }));
}
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- });
- // `send` and `safeEnd` no-op once the response has ended so a late
- // pip-output line (or the promise.then below) doesn't trigger
+ // `send` and `safeEnd` from openSseStream no-op once the response has ended
+ // so a late pip-output line (or the promise.then below) doesn't trigger
// ERR_STREAM_WRITE_AFTER_END or double-end the response.
- const send = (event) => {
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
- };
- const safeEnd = () => { if (!res.writableEnded) res.end(); };
-
+ const { send, safeEnd } = openSseStream(res);
const { promise, kill } = installPackages(parsed.data.pythonPath, parsed.data.packages, send);
promise.then(() => {
// Drop the now-stale setup-check snapshot before the client re-runs the
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index a21140b9b7..6f592841fe 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -3,6 +3,8 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import imageGenRoutes from './imageGen.js';
+import * as fileUtils from '../lib/fileUtils.js';
+import * as regen from '../services/imageGen/regen.js';
vi.mock('../services/imageGen/index.js', () => ({
checkConnection: vi.fn(),
@@ -519,7 +521,7 @@ describe('Image Gen Routes', () => {
expect(response.body.path).toBe('/data/images/avatar.png');
});
- it('should accept empty body for default avatar', async () => {
+ it('should accept empty body for default avatar and return a response shape', async () => {
imageGen.generateAvatar.mockResolvedValue({
generationId: 'gen-004',
filename: 'default.png',
@@ -531,6 +533,9 @@ describe('Image Gen Routes', () => {
.send({});
expect(response.status).toBe(200);
+ expect(response.body.generationId).toBe('gen-004');
+ expect(response.body.filename).toBe('default.png');
+ expect(response.body.path).toBe('/data/images/default.png');
});
});
@@ -846,5 +851,43 @@ describe('Image Gen Routes', () => {
expect(response.status).toBe(404);
expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
});
+
+ it('enqueues a regen job and returns the queued response shape', async () => {
+ // Arrange — stand in for the real filesystem and regen helpers.
+ const resolveGallerySpy = vi.spyOn(fileUtils, 'resolveGalleryImage')
+ .mockReturnValueOnce('/fake/gallery/source.png');
+ imageGen.local.readImageSidecar.mockResolvedValueOnce({
+ path: '/fake/gallery/source.png.json',
+ metadata: { modelId: 'flux-dev', prompt: 'a robot' },
+ });
+ const readDimsSpy = vi.spyOn(regen, 'readImageDimensions')
+ .mockResolvedValueOnce({ width: 1024, height: 1024 });
+ const resolveBackendSpy = vi.spyOn(regen, 'resolveRegenBackend')
+ .mockResolvedValueOnce({ available: true, model: { id: 'flux-dev' }, pythonPath: '/fake/venv/python' });
+ const buildParamsSpy = vi.spyOn(regen, 'buildRegenParams')
+ .mockReturnValueOnce({ kind: 'image', regenJob: true, filename: 'source.png' });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'regen-job-001', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/source.png/regenerate')
+ .send({ strength: 0.25 });
+
+ expect(response.status).toBe(200);
+ // Response must carry the queuedImageResponse shape: jobId, generationId,
+ // filename, path, mode, model, status, position.
+ expect(response.body.jobId).toBe('regen-job-001');
+ expect(response.body.generationId).toBe('regen-job-001');
+ expect(response.body.filename).toBe('regen-job-001.png');
+ expect(response.body.mode).toBe('local');
+ expect(response.body.model).toBe('flux-dev');
+ expect(response.body.status).toBe('queued');
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledTimes(1);
+ expect(buildParamsSpy).toHaveBeenCalledWith(expect.objectContaining({ strength: 0.25 }));
+
+ resolveGallerySpy.mockRestore();
+ readDimsSpy.mockRestore();
+ resolveBackendSpy.mockRestore();
+ buildParamsSpy.mockRestore();
+ });
});
});
diff --git a/server/routes/pipeline.js b/server/routes/pipeline.js
index c2e853226e..28ced0aa26 100644
--- a/server/routes/pipeline.js
+++ b/server/routes/pipeline.js
@@ -98,7 +98,7 @@ import {
LENGTH_PROFILE_NAMES,
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
} from '../lib/issueLength.js';
-import { llmSchema } from './universeBuilder.js';
+import { llmSchema } from '../lib/validation.js';
import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, ARC_ROLES, SEASON_STATUSES } from '../lib/storyArc.js';
// Inline until better/code-quality lands and exports this from validation.js
@@ -1491,45 +1491,12 @@ router.post('/series/:id/seasons/:seasonId/episodes/generate', asyncHandler(asyn
// failure must not invalidate the user's accepted breakdown. Phase B.4:
// canon lives on the linked universe — orphan series (no universeId)
// skip extraction.
- const corpus = result.episodes
- .map((ep) => `## E${ep.number} — ${ep.title}\n\n${ep.logline || ''}\n\n${ep.synopsis || ''}`.trim())
- .filter(Boolean)
- .join('\n\n');
- if (corpus.trim() && series?.universeId) {
- // Fall back to the series' configured LLM when the client doesn't pass an
- // explicit override — matches the extract-canon and extract-scenes routes
- // so continuity extraction honors the provider/model picked in the series
- // header instead of the global active provider. A model id is
- // provider-specific, so only inherit the series model when the effective
- // provider is still the series provider; an override that switches
- // providers without naming a model leaves it blank so the new provider's
- // default resolves.
- const { provider, model } = resolveSeriesLlmOverride(series, {
- overrideProvider: body.providerOverride,
- overrideModel: body.modelOverride,
- });
- // Stamp new inserts as series-extracted (autoLock + sourceSeriesId) so
- // continuity-derived canon survives later AI refines and stays
- // attributable to this series. Matches the pre-B.4 series-side
- // extract semantics.
- const extractRes = await extractCanonFromProse(series.universeId, {
- corpus,
- providerOverride: provider,
- modelOverride: model,
- parallel: true,
- autoLock: true,
- sourceSeriesId: series.id,
- }).catch((err) => {
- console.warn(`⚠️ Continuity extraction failed for season ${req.params.seasonId}: ${err.message}`);
- return null;
- });
- if (extractRes) {
- bibleExtracted = {
- ...countExtractedCanon(extractRes.results),
- universe: extractRes.universe,
- };
- }
- }
+ bibleExtracted = await arcPlanner.extractEpisodeCanon({
+ series,
+ episodes: result.episodes,
+ providerOverride: body.providerOverride,
+ modelOverride: body.modelOverride,
+ });
}
res.json({
diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.js
index 00ea1000fc..bf6804e0f3 100644
--- a/server/routes/universeBuilder.js
+++ b/server/routes/universeBuilder.js
@@ -15,7 +15,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { randomUUID } from 'crypto';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
-import { validateRequest, optionalBooleanMap } from '../lib/validation.js';
+import { validateRequest, optionalBooleanMap, llmSchema } from '../lib/validation.js';
import * as svc from '../services/universeBuilder.js';
import * as canonSvc from '../services/universeCanon.js';
import { expandUniverseCharacter } from '../services/universeCharacterExpand.js';
@@ -117,11 +117,6 @@ const categoriesSchema = z.record(
message: `categories cannot exceed ${svc.WORLD_CATEGORY_COUNT_MAX} buckets`,
});
-export const llmSchema = z.object({
- provider: z.string().trim().max(80).nullable().optional(),
- model: z.string().trim().max(200).nullable().optional(),
-}).optional();
-
// `locked` is a sparse map of `{ field: true }` for the LOCKABLE_FIELDS list.
// `false` is treated the same as omitted — only `true` records a lock so the
// stored shape stays minimal and additive. Accept legacy `influences` key as
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 65fda11c85..44c84ce0d4 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -41,7 +41,7 @@ import {
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
import { inspectModelCache } from '../lib/hfCache.js';
-import { startHfDownloadStream } from '../lib/sseDownload.js';
+import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
const router = Router();
@@ -229,15 +229,7 @@ const runtimeInstallInFlight = new Map();
router.get('/setup/runtime-install', asyncHandler(async (req, res) => {
const runtime = String(req.query?.runtime || '');
const info = BYOV_RUNTIME_INFO[runtime];
- res.writeHead(200, {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- });
- const send = (event) => {
- if (!res.writableEnded) res.write(`data: ${JSON.stringify(event)}\n\n`);
- };
- const safeEnd = () => { if (!res.writableEnded) res.end(); };
+ const { send, safeEnd } = openSseStream(res);
if (!info) {
send({ type: 'error', message: `Unknown runtime: ${runtime}` });
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
new file mode 100644
index 0000000000..94394c87da
--- /dev/null
+++ b/server/services/imageGen/prepareParams.js
@@ -0,0 +1,174 @@
+/**
+ * prepareGenerateParams — 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
+ * - gate reference-image uploads to local FLUX.2 only
+ * - stage multer temp uploads into PATHS.images / PATHS.imageRefs
+ * - resolve initImagePath from upload or gallery filename
+ * - enforce the Codex text-to-image prompt requirement
+ *
+ * Returns:
+ * {
+ * data - mutated validated body (initImageFile/referenceStrengths
+ * stripped; initImagePath/referenceImagePaths/Strengths added)
+ * mode - resolved IMAGE_GEN_MODE string
+ * settings - raw settings object (caller reuses for dispatch)
+ * uploadedTempPaths - multer temp paths to unlink after the response closes
+ * }
+ *
+ * On validation failure throws ServerError so the route's asyncHandler
+ * middleware translates it to a 4xx response.
+ */
+
+import { copyFile, unlink } from 'fs/promises';
+import { randomUUID } from 'crypto';
+import { join } from 'node:path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';
+import { getSettings } from '../settings.js';
+import { IMAGE_GEN_MODE, resolveImageCleaners } from './index.js';
+import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
+
+// Only the formats mflux can decode — mirrors the route's MIME_TO_EXT map
+// so the route never silently relabels (e.g. HEIC) bytes as ".png".
+const MIME_TO_EXT = { 'image/png': '.png', 'image/jpeg': '.jpg', 'image/webp': '.webp' };
+
+/**
+ * @param {object} opts
+ * @param {object} opts.data - validated + coerced body from Zod (mutated in place)
+ * @param {object} opts.files - req.files from multer (may be undefined)
+ * @param {string[]} opts.referenceImageFields - field names for multi-ref slots
+ * @returns {Promise<{ data, mode, settings, uploadedTempPaths }>}
+ */
+export async function prepareGenerateParams({ data, files, referenceImageFields }) {
+ let initImagePath = null;
+ const uploadedTempPaths = [];
+ const initUpload = files?.initImage;
+ const referenceImagePaths = [];
+ const referenceImageStrengths = [];
+
+ // Pair strengths by PACK position (post-filter), not slot position — the
+ // client renumbers populated slots into `referenceImage1..N` and sends a
+ // parallel `referenceStrengths` array sized N. A curl user could leave a
+ // gap (`referenceImage2` + `referenceImage4` only); the strength at index 0
+ // still pairs with the first surviving upload in slot order.
+ const referenceUploads = referenceImageFields
+ .map((field) => files?.[field])
+ .filter(Boolean)
+ .map((upload, packedIndex) => ({ upload, strength: data.referenceStrengths?.[packedIndex] }));
+
+ // Best-effort cleanup of every multer-staged file currently on `files`.
+ // The multipart parser writes uploads to `os.tmpdir()` as they stream in,
+ // so a 400 thrown from validation BEFORE we've registered the `res.on('close')`
+ // sweep would otherwise leak those temp files. Call this from any pre-stage
+ // throw site (FLUX.2-only gate, non-local-backend gate).
+ const cleanupReqFilesTemp = () => {
+ if (!files) return;
+ for (const f of Object.values(files)) {
+ if (f?.path) unlink(f.path).catch(() => {});
+ }
+ };
+
+ // Resolve the effective backend BEFORE staging reference uploads — only the
+ // local FLUX.2 runner consumes `referenceImagePaths`; an `external` or `codex`
+ // request that uploaded refs would otherwise stage files under
+ // `PATHS.imageRefs` and write sidecar metadata claiming references were used,
+ // while the actual generation silently ignored them. (Reading settings here
+ // is cheap — it's already read again below for the per-mode dispatch.)
+ const settings = await getSettings();
+ const mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
+
+ // Resolve cleaners ONCE at the route layer so all three dispatch paths
+ // (synchronous external, codex queue, local queue) see the same values.
+ // Stamp onto `data` so they flow through the spread-into-params calls
+ // below verbatim.
+ const cleaners = resolveImageCleaners(data, settings, mode);
+ data.cleanC2PA = cleaners.cleanC2PA;
+ data.denoise = cleaners.denoise;
+ delete data.autoClean; // legacy field — already mapped into both flags above
+
+ // Multi-reference is a FLUX.2-only, local-backend-only feature — local.js's
+ // buildArgs only emits --reference-images/--reference-strengths inside the
+ // isFlux2 branch, and codex/external backends don't read these fields at all.
+ // Reject up-front rather than copying the uploads to PATHS.imageRefs and
+ // silently dropping them downstream (which would orphan files on disk and
+ // produce metadata sidecars that lie about how the render was conditioned).
+ if (referenceUploads.length) {
+ if (mode !== IMAGE_GEN_MODE.LOCAL) {
+ cleanupReqFilesTemp();
+ throw new ServerError(
+ 'Reference images are only supported for local FLUX.2 renders',
+ { status: 400, code: 'REFERENCE_IMAGES_LOCAL_ONLY' },
+ );
+ }
+ const candidate = getImageModels().find((m) => m.id === data.modelId)
+ ?? getImageModels().find((m) => m.id === 'dev')
+ ?? getImageModels()[0];
+ if (!isFlux2(candidate)) {
+ cleanupReqFilesTemp();
+ throw new ServerError(
+ 'Reference images are only supported for FLUX.2 models',
+ { status: 400, code: 'REFERENCE_IMAGES_FLUX2_ONLY' },
+ );
+ }
+ }
+
+ if (initUpload) await ensureDir(PATHS.images);
+ if (referenceUploads.length) await ensureDir(PATHS.imageRefs);
+ if (initUpload) {
+ // Trust the validated mimetype from the fileFilter — picking the ext
+ // off the original filename can mismatch the bytes (e.g. HEIC saved
+ // as .jpg). MIME_TO_EXT only contains formats the fileFilter accepts.
+ const ext = MIME_TO_EXT[(initUpload.mimetype || '').toLowerCase()] || '.png';
+ const initFilename = `init-${randomUUID()}${ext}`;
+ initImagePath = join(PATHS.images, initFilename);
+ await copyFile(initUpload.path, initImagePath);
+ uploadedTempPaths.push(initUpload.path);
+ } else if (data.initImageFile) {
+ const resolved = resolveGalleryImage(data.initImageFile);
+ if (!resolved) {
+ throw new ServerError('Init image not found in gallery', { status: 400, code: 'INIT_IMAGE_NOT_FOUND' });
+ }
+ initImagePath = resolved;
+ }
+
+ // Multi-reference editing (FLUX.2). Walk packed slot entries in submit
+ // order — each contributes a path + its parallel strength. Empty slots
+ // are filtered out above so the runner sees `referenceImagePaths: [p1, ...]`
+ // and aligns strengths by index.
+ for (const { upload, strength } of referenceUploads) {
+ const ext = MIME_TO_EXT[(upload.mimetype || '').toLowerCase()] || '.png';
+ const refFilename = `ref-${randomUUID()}${ext}`;
+ const refPath = join(PATHS.imageRefs, refFilename);
+ await copyFile(upload.path, refPath);
+ uploadedTempPaths.push(upload.path);
+ referenceImagePaths.push(refPath);
+ // Default to 1.0 when the client didn't send a parallel strength entry,
+ // matching the "full influence" intent of an uploaded reference.
+ referenceImageStrengths.push(typeof strength === 'number' ? strength : 1.0);
+ }
+
+ // Strip the route-only fields — providers expect normalized `…Path(s)`.
+ delete data.initImageFile;
+ delete data.referenceStrengths;
+ if (initImagePath) data.initImagePath = initImagePath;
+ if (referenceImagePaths.length) {
+ data.referenceImagePaths = referenceImagePaths;
+ data.referenceImageStrengths = referenceImageStrengths;
+ }
+
+ // Empty prompt is allowed for i2i / local / external, but Codex text-to-image
+ // (no init image) still needs one — reject synchronously here so direct API
+ // callers get a 400 instead of a 200-then-async-job-failure. Mirrors the guard
+ // in codex.js and the client's codexNeedsPrompt gate.
+ if (mode === IMAGE_GEN_MODE.CODEX && !initImagePath && !data.prompt?.trim()) {
+ throw new ServerError('Prompt is required for Codex text-to-image', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ if (data.guidance == null && data.cfgScale != null) {
+ data.guidance = data.cfgScale;
+ }
+
+ return { data, mode, settings, uploadedTempPaths };
+}
diff --git a/server/services/imageGen/variants.js b/server/services/imageGen/variants.js
new file mode 100644
index 0000000000..1f0e9416ed
--- /dev/null
+++ b/server/services/imageGen/variants.js
@@ -0,0 +1,313 @@
+/**
+ * Image variant helpers — shared logic for the three synchronous variant
+ * endpoints: clean, remove-watermark, and light-regen.
+ *
+ * Each produces an on-disk `_<suffix>.png` + a `_<suffix>.metadata.json`
+ * sidecar, auto-files the new copy into every collection that held the source,
+ * and returns a gallery-compatible response object. The three operations share
+ * an identical persist-variant tail:
+ *
+ * await Promise.all([writeFile(outPath, data), writeFile(sidecarPath, …)])
+ * const filed = await autoFileCleanedToSourceCollections(src, out)
+ * console.log(…)
+ * return { …variantMeta, filename, path, width, height, … }
+ *
+ * `persistVariant` owns that tail; `applyImageClean`, `applyWatermarkRemoval`,
+ * and `applyLightRegenVariant` each build the inputs and delegate to it.
+ *
+ * The route handlers become: validate → read source → call helper → res.json.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'node:path';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/fileUtils.js';
+import { cleanImageBuffer } from '../../lib/imageClean.js';
+import { removeCornerWatermark } from '../../lib/imageWatermark.js';
+import { applyLightRegen, computePixelDelta } from './regen.js';
+import { listCollections, addItem, ERR_DUPLICATE } from '../mediaCollections.js';
+import { itemKey } from '../../lib/mediaItemKey.js';
+
+// ---------------------------------------------------------------------------
+// Internal helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Add `cleanedFilename` to every collection that already contains
+ * `sourceFilename`. Returns the ids of collections that received the new
+ * entry; silently skips duplicates and swallows per-collection failures so
+ * a collection error never blocks the variant write itself.
+ */
+export async function autoFileCleanedToSourceCollections(sourceFilename, cleanedFilename) {
+ const sourceKey = itemKey({ kind: 'image', ref: sourceFilename });
+ const all = await listCollections();
+ const matching = all.filter((c) => c.items.some((it) => itemKey(it) === sourceKey));
+ if (matching.length === 0) return [];
+ const results = await Promise.all(matching.map(async (c) => {
+ try {
+ await addItem(c.id, { kind: 'image', ref: cleanedFilename });
+ return c.id;
+ } catch (err) {
+ if (err?.code === ERR_DUPLICATE) return null;
+ console.warn(`⚠️ Auto-file ${cleanedFilename} → collection ${c.id} failed: ${err?.message || err}`);
+ return null;
+ }
+ }));
+ return results.filter(Boolean);
+}
+
+/**
+ * Write the variant PNG + sidecar, auto-file into source collections, and
+ * return a gallery-compatible record.
+ *
+ * @param {object} opts
+ * @param {string} opts.sourceFilename - original gallery basename (e.g. "abc.png")
+ * @param {string} opts.outFilename - variant basename (e.g. "abc_clean-aggressive.png")
+ * @param {Buffer} opts.data - variant PNG bytes
+ * @param {object} opts.variantMeta - sidecar JSON (already built by caller)
+ * @param {number} [opts.width] - pixel width from transform result
+ * @param {number} [opts.height] - pixel height from transform result
+ * @param {number} [opts.sizeBefore] - source byte size (optional, for response)
+ * @param {number} [opts.sizeAfter] - variant byte size (optional, for response)
+ * @param {string} opts.logLine - single console.log message
+ * @param {object} [opts.extraFields] - additional fields merged into the response
+ * @returns {Promise<object>} gallery-compatible record for res.json
+ */
+export async function persistVariant({
+ sourceFilename,
+ outFilename,
+ data,
+ variantMeta,
+ width,
+ height,
+ sizeBefore,
+ sizeAfter,
+ logLine,
+ extraFields = {},
+}) {
+ const outPath = join(PATHS.images, outFilename);
+ const sidecarBase = outFilename.slice(0, -'.png'.length);
+ const sidecarPath = join(PATHS.images, `${sidecarBase}.metadata.json`);
+
+ await Promise.all([
+ writeFile(outPath, data),
+ writeFile(sidecarPath, JSON.stringify(variantMeta, null, 2)),
+ ]);
+
+ const filedCollections = await autoFileCleanedToSourceCollections(sourceFilename, outFilename).catch((err) => {
+ console.warn(`⚠️ Auto-file ${outFilename} → source collections failed: ${err?.message || err}`);
+ return [];
+ });
+
+ console.log(`${logLine}${filedCollections.length ? `, filed to ${filedCollections.length} collection(s)` : ''}`);
+
+ return {
+ ...variantMeta,
+ filename: outFilename,
+ path: `/data/images/${outFilename}`,
+ ...(width != null ? { width } : {}),
+ ...(height != null ? { height } : {}),
+ ...(sizeBefore != null ? { sizeBefore } : {}),
+ ...(sizeAfter != null ? { sizeAfter, sizeBytes: sizeAfter } : {}),
+ ...extraFields,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Variant operations
+// ---------------------------------------------------------------------------
+
+/**
+ * C2PA-strip + denoise clean for /:filename/clean.
+ * Reads the source, applies cleanImageBuffer, builds the variant record,
+ * and delegates to persistVariant.
+ *
+ * @param {object} opts
+ * @param {string} opts.filename - gallery basename
+ * @param {object} opts.sourceMeta - from local.readImageSidecar(filename)
+ * @returns {Promise<object>} gallery-compatible record for res.json
+ */
+export async function applyImageClean({ filename, sourceMeta }) {
+ const sourcePath = join(PATHS.images, filename);
+ const buffer = await readFile(sourcePath).catch((err) => {
+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
+ throw err;
+ });
+
+ const result = await cleanImageBuffer(buffer);
+ if (result.format !== 'png') {
+ throw new ServerError('Gallery images must be PNG', { status: 400, code: 'UNSUPPORTED_FORMAT' });
+ }
+
+ // The `_clean-aggressive` filename suffix and `cleanLevel: 'aggressive'`
+ // sidecar field survive the light/aggressive collapse so already-cleaned
+ // images on disk keep round-tripping through the gallery unchanged.
+ const base = filename.slice(0, -'.png'.length);
+ const outFilename = `${base}_clean-aggressive.png`;
+ const createdAt = new Date().toISOString();
+
+ // Strip `hidden` so a clean of a hidden source still surfaces in the gallery
+ // — cleaning is a deliberate user action that implies wanting to see the result.
+ // Strip `filename`/`id` so listGallery's `...metadata` spread doesn't overwrite
+ // the disk-derived filename for the cleaned copy with the source's filename.
+ const { hidden: _hidden, filename: _srcFilename, id: _srcId, ...sourceMetaForCleaned } = sourceMeta;
+ const variantMeta = {
+ ...sourceMetaForCleaned,
+ createdAt,
+ cleanedFrom: filename,
+ cleanLevel: 'aggressive',
+ c2paStripped: result.c2paStripped,
+ };
+
+ return persistVariant({
+ sourceFilename: filename,
+ outFilename,
+ data: result.data,
+ variantMeta,
+ width: result.width,
+ height: result.height,
+ sizeBefore: result.sizeBefore,
+ sizeAfter: result.sizeAfter,
+ logLine: `🧼 Cleaned ${filename} → ${outFilename} (${result.sizeBefore}B → ${result.sizeAfter}B, c2pa=${result.c2paStripped})`,
+ extraFields: {
+ // sourceMeta fields already in variantMeta; these explicit fields win on
+ // key collisions so createdAt reflects the cleaning, not the original.
+ createdAt,
+ cleanedFrom: filename,
+ cleanLevel: 'aggressive',
+ c2paStripped: result.c2paStripped,
+ },
+ });
+}
+
+/**
+ * Visible-watermark removal for /:filename/remove-watermark.
+ * Reads the source, applies removeCornerWatermark, builds the variant record,
+ * and delegates to persistVariant.
+ *
+ * @param {object} opts
+ * @param {string} opts.filename - gallery basename
+ * @param {object} opts.sourceMeta - from local.readImageSidecar(filename)
+ * @param {number|undefined} opts.size - optional override for the corner box side
+ * @param {object|undefined} opts.region - optional explicit bounding box
+ * @returns {Promise<object>} gallery-compatible record for res.json
+ */
+export async function applyWatermarkRemoval({ filename, sourceMeta, size, region }) {
+ const sourcePath = join(PATHS.images, filename);
+ const buffer = await readFile(sourcePath).catch((err) => {
+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
+ throw err;
+ });
+
+ const result = await removeCornerWatermark(buffer, { size, region });
+
+ const base = filename.slice(0, -'.png'.length);
+ const outFilename = `${base}_nowatermark.png`;
+
+ // Anchor the variant group at the root original — de-watermarking a
+ // cleaned/regenerated variant groups under the root.
+ const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
+ ? sourceMeta.cleanedFrom : filename;
+ const createdAt = new Date().toISOString();
+
+ // Strip hidden/filename/id so listGallery's `...metadata` spread doesn't
+ // overwrite the disk-derived filename or re-hide the deliberate variant. Also
+ // drop the regen lineage fields: de-watermarking a REGENERATED source would
+ // otherwise inherit `regenerated:true` + stale fidelity numbers, and both the
+ // lightbox lineage (`describeCleanedLineage`) and variant grouping check
+ // `regenerated` BEFORE `watermarkRemoved` — so the variant would mislabel as
+ // "Regenerated … % changed" instead of "Watermark removed from …".
+ const {
+ hidden: _hidden, filename: _srcFilename, id: _srcId,
+ regenerated: _regenerated, regenStrength: _regenStrength,
+ regenSteps: _regenSteps, regenModelId: _regenModelId,
+ regenPixelDeltaPct: _regenPixelDeltaPct, regenPsnr: _regenPsnr,
+ regenMethod: _regenMethod,
+ ...sourceMetaForVariant
+ } = sourceMeta;
+ const variantMeta = {
+ ...sourceMetaForVariant,
+ createdAt,
+ cleanedFrom: groupRoot,
+ watermarkRemoved: true,
+ watermarkRegion: result.region,
+ };
+
+ return persistVariant({
+ sourceFilename: filename,
+ outFilename,
+ data: result.data,
+ variantMeta,
+ width: result.width,
+ height: result.height,
+ sizeBefore: result.sizeBefore,
+ sizeAfter: result.sizeAfter,
+ logLine: `✦ Removed watermark ${filename} → ${outFilename} (${result.region.w}×${result.region.h} @ ${result.region.x},${result.region.y})`,
+ });
+}
+
+/**
+ * CPU-only light regen for the `method: 'light'` branch of /:filename/regenerate.
+ * Reads the source, applies applyLightRegen, builds the variant record, and
+ * delegates to persistVariant.
+ *
+ * @param {object} opts
+ * @param {string} opts.filename - gallery basename
+ * @param {string} opts.sourceAbsPath - absolute path to the source PNG
+ * @param {object} opts.sourceMeta - from local.readImageSidecar(filename)
+ * @returns {Promise<object>} gallery-compatible record for res.json
+ */
+export async function applyLightRegenVariant({ filename, sourceAbsPath, sourceMeta }) {
+ const buffer = await readFile(sourceAbsPath).catch((err) => {
+ if (err.code === 'ENOENT') throw new ServerError('Image not found', { status: 404, code: 'NOT_FOUND' });
+ throw err;
+ });
+ const result = await applyLightRegen(buffer);
+ if (!result) {
+ throw new ServerError('Could not decode image for light regen', { status: 400, code: 'INVALID_IMAGE' });
+ }
+
+ const base = filename.slice(0, -'.png'.length);
+ const outFilename = `${base}_regen-light.png`;
+
+ // Anchor the variant group at the root original — regenerating a
+ // cleaned/regenerated variant must group under the root, not orphan.
+ const groupRoot = typeof sourceMeta.cleanedFrom === 'string' && sourceMeta.cleanedFrom
+ ? sourceMeta.cleanedFrom : filename;
+ const createdAt = new Date().toISOString();
+
+ // Strip hidden/filename/id so the listGallery `...metadata` spread doesn't
+ // overwrite the disk-derived filename or re-hide the deliberate variant.
+ // Also strip the FLUX-regen-specific fields: when the source is itself a
+ // prior FLUX regen, carrying its regenStrength/Steps/ModelId + stale
+ // delta into a SPATIAL pass would make the lineage row falsely read
+ // "· N% denoise" (a light pass has no denoise) and show a stale fidelity.
+ const {
+ hidden: _hidden, filename: _srcFilename, id: _srcId,
+ regenStrength: _rs, regenSteps: _rst, regenModelId: _rm,
+ regenPixelDeltaPct: _rpd, regenPsnr: _rp,
+ ...sourceMetaForVariant
+ } = sourceMeta;
+
+ // Compare the in-memory source/output buffers — no need to re-read the
+ // written file off disk just to measure the delta.
+ const delta = await computePixelDelta(buffer, result.data).catch(() => null);
+ const variantMeta = {
+ ...sourceMetaForVariant,
+ createdAt,
+ cleanedFrom: groupRoot,
+ regenerated: true,
+ regenMethod: 'light-spatial',
+ ...(delta ? { regenPixelDeltaPct: delta.pixelDeltaPct, regenPsnr: delta.psnr } : {}),
+ };
+
+ return persistVariant({
+ sourceFilename: filename,
+ outFilename,
+ data: result.data,
+ variantMeta,
+ width: result.width,
+ height: result.height,
+ logLine: `♻️ Light-regen ${filename} → ${outFilename} (${delta ? `${delta.pixelDeltaPct}% changed` : 'fidelity n/a'})`,
+ });
+}
diff --git a/server/services/pipeline/arcPlanner.js b/server/services/pipeline/arcPlanner.js
index 71be422a59..1b6c8b2393 100644
--- a/server/services/pipeline/arcPlanner.js
+++ b/server/services/pipeline/arcPlanner.js
@@ -44,6 +44,8 @@ import { runPromptRefineRaw, trimChanges } from './refineHelpers.js';
import { recommendStructure, describeStructure } from '../../lib/seasonStructure.js';
import { LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE } from '../../lib/issueLength.js';
import { getUniverse } from '../universeBuilder.js';
+import { extractCanonFromProse } from '../universeCanon.js';
+import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';
import { getSeriesCanon } from './seriesCanon.js';
import { renderCategoriesForPrompt, renderCompositesForPrompt, renderCanonForPrompt, renderEntitiesSummary } from '../../lib/universePromptRenderers.js';
@@ -1243,6 +1245,77 @@ export async function commitEpisodesToIssues(seriesId, seasonId, episodes = [],
return created;
}
+/**
+ * Collapse `extractCanonFromProse` result counts into { characters, places, objects }.
+ * Mirrors the `countExtractedCanon` helper in the pipeline route.
+ */
+function countExtractedCanon(results) {
+ return {
+ characters: results.characters?.extracted?.length || 0,
+ places: results.places?.extracted?.length || 0,
+ objects: results.objects?.extracted?.length || 0,
+ };
+}
+
+/**
+ * Post-commit canon extraction for season-episode generation. Called after
+ * commitEpisodesToIssues succeeds to run continuity extraction on the newly
+ * committed episode corpus. Non-fatal: episode creation already succeeded, so
+ * extraction failure must not invalidate the user's accepted breakdown.
+ *
+ * Orphan series (no universeId) and empty episode corpora skip extraction and
+ * return `null`. On success returns
+ * `{ characters, places, objects, universe }` (the `bibleExtracted` shape the
+ * route sends down to the client).
+ *
+ * @param {object} opts
+ * @param {object} opts.series - full series record (preloaded by caller)
+ * @param {object[]} opts.episodes - committed episode list from generateSeasonEpisodes
+ * @param {string|undefined} opts.providerOverride - explicit provider override from client body
+ * @param {string|undefined} opts.modelOverride - explicit model override from client body
+ * @returns {Promise<{characters,places,objects,universe}|null>}
+ */
+export async function extractEpisodeCanon({ series, episodes, providerOverride, modelOverride }) {
+ const corpus = episodes
+ .map((ep) => `## E${ep.number} — ${ep.title}\n\n${ep.logline || ''}\n\n${ep.synopsis || ''}`.trim())
+ .filter(Boolean)
+ .join('\n\n');
+ if (!corpus.trim() || !series?.universeId) return null;
+
+ // Fall back to the series' configured LLM when the client doesn't pass an
+ // explicit override — matches the extract-canon and extract-scenes routes so
+ // continuity extraction honors the provider/model picked in the series header
+ // instead of the global active provider. A model id is provider-specific, so
+ // only inherit the series model when the effective provider is still the series
+ // provider; an override that switches providers without naming a model leaves it
+ // blank so the new provider's default resolves.
+ const { provider, model } = resolveSeriesLlmOverride(series, {
+ overrideProvider: providerOverride,
+ overrideModel: modelOverride,
+ });
+
+ // Stamp new inserts as series-extracted (autoLock + sourceSeriesId) so
+ // continuity-derived canon survives later AI refines and stays attributable
+ // to this series. Matches the pre-B.4 series-side extract semantics.
+ const extractRes = await extractCanonFromProse(series.universeId, {
+ corpus,
+ providerOverride: provider,
+ modelOverride: model,
+ parallel: true,
+ autoLock: true,
+ sourceSeriesId: series.id,
+ }).catch((err) => {
+ console.warn(`⚠️ Continuity extraction failed for series ${series.id}: ${err.message}`);
+ return null;
+ });
+ if (!extractRes) return null;
+
+ return {
+ ...countExtractedCanon(extractRes.results),
+ universe: extractRes.universe,
+ };
+}
+
/**
* Generate FRONT + BACK cover-art concepts for one volume (season). Returns
* the proposed text without persisting; pass `commit: true` to write the