Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([image-gen-mode-enum-unify]): adopt typed IMAGE_GEN_MODE enum across server + client
[._.]/ Adam Eivyb125a50b52db
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e474290c16..1838e80855 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **[image-gen-mode-enum-unify] Unify the image-gen mode enum across server + client.** The bare `'codex'` / `'local'` / `'external'` string literals that lived at ~25 dispatch sites across `server/services/imageGen/{index,codex,local,external}.js`, `server/services/mediaJobQueue/index.js`, `server/services/pipeline/visualStages.js`, `server/services/universeCharacterSheet.js`, `server/routes/{imageGen,universeBuilder,sdapi}.js`, and the matching client surfaces (`ImageGen.jsx`, `ImageGenTab.jsx`, `VisualGenSettings.jsx`, `ImageGenControls.jsx`, `MediaJobsQueue.jsx`, `MediaLightbox.jsx`, `PromptRefineModal.jsx`, `normalize.js`, `imageGenResolutions.js`, `wrImageDefaults.js`, `ComicScriptStage.jsx`) now flow through a typed enum. Server adds `IMAGE_GEN_MODE = Object.freeze({ EXTERNAL, LOCAL, CODEX })` in a new `server/services/imageGen/modes.js` (standalone so the dispatcher and the provider modules can both import without a cycle), re-exported from `imageGen/index.js`; `IMAGE_GEN_MODES` (the Zod-validator alphabet) is now derived from `Object.values(IMAGE_GEN_MODE)` so the two can't drift. Client `IMAGE_GEN_MODE` in `client/src/lib/imageGenBackends.js` is `Object.freeze`d to match. `IMAGE_GEN_MODES` is preserved as-is for Zod + the OpenAI tool-spec enum. Provider binary names (`DEFAULT_BIN = 'codex'`) and model-fallback strings stay as bare literals — they're not modes. Two test mocks (`imageGen.test.js`, `sdapi.test.js`) updated to export the new constant. 6096/6096 server tests + 240/240 client tests pass.+- **[imagegen-local-defer-module-load-side-effects] Drop the module-load `IMAGE_MODELS` snapshot in `server/services/imageGen/local.js`.** The `export const IMAGE_MODELS = Object.fromEntries(getImageModels().map(...))` line ran `loadMediaModels()` at import time — which `mkdirSync`s the registry dir and `writeFileSync`s a default registry on first run. Any importer reaching `imageGen/local.js` via a test that mocks `PATHS.data` to a non-writable path (e.g. `routes/pipeline.test.js → routes/pipeline.js → universeBuilderCollectionHook.js`) failed on `mkdirSync('/mock/data')`. The export was dead (zero callers — grep confirmed) and `generateImage()` already reads the live registry via `getImageModels()`. Removed the export, reverted the 2026-05-19 lazy-import workaround in `services/universeBuilderCollectionHook.js` (now a normal static `import { readImageSidecar }`). Also tightened `enrichSidecar` to use `atomicWrite` (temp+rename) instead of `writeFile` — the prior plain write had a flaky race in tests where five-at-a-time batch enrichment let concurrent readers observe a mid-truncate empty file. 6090/6090 server tests + 234/234 client tests pass; the previously-flaky `enriches every sidecar in a batch` test now passes 10/10 runs.- **[promote-provider-type-constants-to-shared-module] Promote provider-type literals to a shared `PROVIDER_TYPES` enum.** `server/lib/aiToolkit/constants.js#PROVIDER_TYPES` grows `TUI: 'tui'` alongside the existing `CLI`/`API`, and the object is now `Object.freeze`d so callers can't mutate the shared enum. Server-side `LIGHT_CONTEXT_PROVIDER_TYPES` set + the `isTui` / `providerType` default in `server/services/agentPromptBuilder.js` now read from `PROVIDER_TYPES.{CLI,TUI,API}` instead of bare string literals. A mirror `PROVIDER_TYPES` is exported from `client/src/utils/providers.js` (the toolkit dir is intentionally kept self-contained per CLAUDE.md, so the client can't import the server copy directly), and the four client helpers (`isTuiProvider`, `isCliProvider`, `isProcessProvider`, `providerTypeClass`) now read from it. A new `providers.test.js` case statically imports the server enum and asserts the two enums stay in lockstep, so a future divergence fails CI instead of silently drifting. 13/13 provider helper tests pass; 25/25 agentPromptBuilder tests pass.diff --git a/PLAN.md b/PLAN.mdindex 15eec91022..9528b92808 100644--- a/PLAN.md+++ b/PLAN.md@@ -15,7 +15,6 @@ _Nothing currently parked — pick the next item from the Backlog._- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.- [ ] [extract-readcertmeta-helper] **Extract a shared `readCertMeta()` helper from `data/certs/meta.json` readers.** Three independent readers exist: `server/lib/peerSelfHost.js:13-18` (hostname only), `server/services/certRenewer.js:30-31` (mode + hostname), `server/lib/networkExposure.js:25-29` (mode + hostname + ips). Each does its own `statSync({ throwIfNoEntry: false }) + readFileSync + safeJSONParse`. Consolidate into `server/lib/certMeta.js` exporting `readCertMeta() → { mode, hostname, ips } | null`. Surfaced by /simplify during `[codex5-network-exposure-ui]`; deferred to keep that PR scoped. Note `peerSelfHost.js` is in a hot path — verify perf when consolidating.- [ ] [hoist-loopback-host-helper-to-client-lib] **Hoist `isLoopbackHost` to `client/src/lib/loopbackHost.js`.** `server/lib/networkExposure.js` exports `isLoopbackHost`, but `client/src/components/NetworkExposureWidget.jsx:22-30` re-declares the same `LOOPBACK_HOSTS` Set and `describeMicAvailability()` helper inline (server export isn't reachable from browser). Move the client copy into `client/src/lib/loopbackHost.js` + add a barrel entry so future secure-context callers (voiceClient, etc.) can reuse it. When hoisting, broaden the IPv4 check from a single literal `127.0.0.1` to the full `127.0.0.0/8` loopback range to match browser secure-context behavior — easy `/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/` regex. Surfaced by /simplify and the codex review during `[codex5-network-exposure-ui]`.-- [ ] [image-gen-mode-enum-unify] **Unify image-gen mode enum across server + client.** Server has `IMAGE_GEN_MODES = ['external','local','codex']` (a Zod-validator alphabet) at `server/services/imageGen/index.js:21`; client has `IMAGE_GEN_MODE` constants at `client/src/lib/imageGenBackends.js:3`. Code reads strings (`'codex'`, `'local'`, `'external'`) inline at ~10 sites across `server/services/imageGen/{codex,local,external}.js`, `server/routes/imageGen.js`, and several client pages. `IMAGE_GEN_MODES` is actively used (Zod enum + voice tool enum), so the choice is "export a typed enum object on the server (`IMAGE_GEN_MODE = Object.freeze({ CODEX: 'codex', ... })`) alongside `IMAGE_GEN_MODES` and adopt it at dispatch sites" — not "drop `IMAGE_GEN_MODES`". Surfaced by /simplify after the per-render checkbox PR.- [ ] [unknown-instance-id-sentinel-extract] **Extract the `'unknown'` instanceId sentinel to a named constant.** The literal string `'unknown'` appears at 7+ sites across `server/services/instances.js#getInstanceId` (the default), `server/services/mediaAnnotations.js` (heal check in `readAll`, peer-merge guard, `setAnnotation` precondition), and `server/services/sharing/annotationsSync.js#flushAll` (export-refusal guard). Promote to `export const UNKNOWN_INSTANCE_ID = 'unknown'` in `instances.js` and import where compared, so the contract is greppable and typo-proof. Surfaced by /simplify during `[med-migration-scripts-migrations-014-attribute]`.### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsxindex 01c09a7c74..086fe79b42 100644--- a/client/src/components/imageGen/ImageGenControls.jsx+++ b/client/src/components/imageGen/ImageGenControls.jsx@@ -12,6 +12,7 @@ import { Dice5 } from 'lucide-react';import { filterResolutions, resolveResolutionLabel } from '../../lib/imageGenResolutions';import { randomSeed } from '../../lib/genUtils';import { RUNNER_FAMILIES } from '../../lib/runnerFamilies';+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';const QUANTIZE_OPTIONS = [{ value: '3', label: '3-bit' },@@ -39,8 +40,8 @@ export default function ImageGenControls({// Pass e.g. "grid-cols-2 sm:grid-cols-4" to fit a denser layout.className = 'grid grid-cols-2 sm:grid-cols-3 gap-3',}) {- const isLocal = mode === 'local';- const isCodex = mode === 'codex';+ const isLocal = mode === IMAGE_GEN_MODE.LOCAL;+ const isCodex = mode === IMAGE_GEN_MODE.CODEX;const currentModel = models.find((m) => m.id === modelId);const isFlux2 = currentModel?.runner === RUNNER_FAMILIES.FLUX2;diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 3ea62148a4..59b4891b19 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState, useCallback } from 'react';import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';import toast from '../ui/Toast';import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';const STATUS_BADGE = {queued: 'bg-port-border text-port-text-muted',@@ -18,7 +19,7 @@ const KIND_ICON = { video: Film, image: ImageIcon };// jobs carry `params.modelId`. Trims long HF repo paths to the tail segment.function modelLabel(params) {if (!params) return null;- if (params.mode === 'codex') {+ if (params.mode === IMAGE_GEN_MODE.CODEX) {const m = (params.model || '').trim();return m ? `codex / ${m}` : 'codex';}@@ -191,7 +192,7 @@ function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {const canDelete = (job.status === 'failed' || job.status === 'canceled' || job.status === 'completed')&& typeof onDelete === 'function';// Run-now is codex-only — GPU jobs serialize on the single MLX runtime.- const isQueuedCodex = job.status === 'queued' && job.kind === 'image' && job.params?.mode === 'codex';+ const isQueuedCodex = job.status === 'queued' && job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX;const canRunNow = isQueuedCodex && typeof onRunNow === 'function';// Inline edit form for retry-with-overrides.const [editing, setEditing] = useState(false);@@ -304,7 +305,7 @@ function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {// fields out of the patch so the original job's values ride through.function EditRetryForm({ job, onSubmit, onCancel }) {const p = job.params || {};- const isCodex = p.mode === 'codex';+ const isCodex = p.mode === IMAGE_GEN_MODE.CODEX;const [prompt, setPrompt] = useState(p.prompt || '');const [negativePrompt, setNegativePrompt] = useState(p.negativePrompt || '');const [model, setModel] = useState(p.model || '');diff --git a/client/src/components/media/MediaLightbox.jsx b/client/src/components/media/MediaLightbox.jsxindex 7c45d13a7e..dc11c2b234 100644--- a/client/src/components/media/MediaLightbox.jsx+++ b/client/src/components/media/MediaLightbox.jsx@@ -8,6 +8,7 @@ import AddToCollectionMenu from './AddToCollectionMenu';import { useScrollLock } from '../../hooks/useScrollLock';import { useSwipeNav } from '../../hooks/useSwipeNav';import { copyToClipboard } from '../../lib/clipboard';+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';// Intentionally NOT migrated to <ui/Modal> or <components/Drawer>. The// prev/next buttons sit as viewport-edge siblings of the card (not children@@ -138,7 +139,7 @@ export default function MediaLightbox({copyToClipboard(text, `${label} copied`);};- const isCodex = item.mode === 'codex';+ const isCodex = item.mode === IMAGE_GEN_MODE.CODEX;// Map raw `entryKind` tokens to user-facing labels — the sidecar stores// 'canon' / 'variation' / 'sheet' (ENTRY_REF_KIND values) for parity with// the server contract; users shouldn't see the wire tokens.diff --git a/client/src/components/media/PromptRefineModal.jsx b/client/src/components/media/PromptRefineModal.jsxindex 8f515a537d..4833e4d3ea 100644--- a/client/src/components/media/PromptRefineModal.jsx+++ b/client/src/components/media/PromptRefineModal.jsx@@ -6,6 +6,7 @@ import Modal from '../ui/Modal';import useProviderModels from '../../hooks/useProviderModels';import { generateImage, generateVideo, refineMediaPrompt } from '../../services/api';import { getRenderConfigForItem } from './normalize';+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';// Refine→queue forces text-to-video; the source image/last-frame from the// original render isn't carried into the modal, so image-to-video can't be@@ -95,7 +96,7 @@ export default function PromptRefineModal({ item, open, onClose }) {// external image-gen mode returns synchronously with the filename and// no queue position — the render already completed by the time this// resolves. Local / codex / video return a queued jobId+position.- const isAlreadyDone = item.kind === 'image' && result?.mode === 'external';+ const isAlreadyDone = item.kind === 'image' && result?.mode === IMAGE_GEN_MODE.EXTERNAL;const message = isAlreadyDone? 'Render complete': result.position ? `Queued #${result.position}` : 'Render queued';diff --git a/client/src/components/media/normalize.js b/client/src/components/media/normalize.jsindex 0f61141d5d..662008ff86 100644--- a/client/src/components/media/normalize.js+++ b/client/src/components/media/normalize.js@@ -1,3 +1,5 @@+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';+// Friendly display name for a LoRA basename. The on-disk filenames look like// `lora-realstagram-v7.safetensors` — strip the `lora-` prefix, the version// suffix (`-v123`), and the extension, then re-spaceify dashes. Idempotent@@ -22,7 +24,7 @@ export function normalizeImage(i) {// 3. mode — pre-model-field codex sidecars saved before the default// was added; surface the provider tag so the card still// shows where the image came from.- const modelId = i.modelId || i.model || (i.mode && i.mode !== 'local' ? i.mode : null);+ const modelId = i.modelId || i.model || (i.mode && i.mode !== IMAGE_GEN_MODE.LOCAL ? i.mode : null);return {kind: 'image',key: `image:${i.filename}`,@@ -132,7 +134,7 @@ export function getRenderConfigForItem(item) {const raw = item.raw || {};if (item.kind === 'image') {return {- mode: item.mode || 'local',+ mode: item.mode || IMAGE_GEN_MODE.LOCAL,modelId: item.modelId,width: item.width,height: item.height,diff --git a/client/src/components/pipeline/stages/ComicScriptStage.jsx b/client/src/components/pipeline/stages/ComicScriptStage.jsxindex 9ce0076ebd..0658bba9af 100644--- a/client/src/components/pipeline/stages/ComicScriptStage.jsx+++ b/client/src/components/pipeline/stages/ComicScriptStage.jsx@@ -32,7 +32,7 @@ import usePreviewRoute from '../../../hooks/usePreviewRoute';import Drawer from '../../Drawer';import ImageGenSettingsForm from '../../imageGen/ImageGenSettingsForm';import ExtractCanonButton from './ExtractCanonButton';-import { deriveAvailableBackends } from '../../../lib/imageGenBackends';+import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../../../lib/imageGenBackends';import {PIPELINE_IMAGE_DEFAULTS,readPipelineImageSettings,@@ -800,7 +800,7 @@ function PageRow({if (res) {onStageUpdate?.('comicPages', res.stage);const suffix = useProofAsBase ? ' (from proof)' : '';- toast.success(`Page ${pageIndex + 1} ${target}${suffix} render queued (${res.mode || renderOpts.mode || 'local'})`);+ toast.success(`Page ${pageIndex + 1} ${target}${suffix} render queued (${res.mode || renderOpts.mode || IMAGE_GEN_MODE.LOCAL})`);}};diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsxindex baa04a4f37..7b937196fd 100644--- a/client/src/components/pipeline/stages/VisualGenSettings.jsx+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx@@ -19,7 +19,7 @@ import {getSettings, listImageModels, getProviders,} from '../../../services/api';import { filterSelectableModels } from '../../../utils/providers';-import { deriveAvailableBackends } from '../../../lib/imageGenBackends';+import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../../../lib/imageGenBackends';import BackendChipStrip from '../../media/BackendChipStrip';import ProviderModelSelector from '../../ProviderModelSelector';@@ -78,8 +78,8 @@ const loadLookups = () => {const resolveAutoLabel = (s) => {const codexEnabled = s?.imageGen?.codex?.enabled === true;const pinned = s?.imageGen?.mode;- if (pinned === 'codex' && codexEnabled) return 'Codex';- if (pinned === 'local') return 'Local diffusion';+ if (pinned === IMAGE_GEN_MODE.CODEX && codexEnabled) return 'Codex';+ if (pinned === IMAGE_GEN_MODE.LOCAL) return 'Local diffusion';if (codexEnabled) return 'Codex';if (s?.imageGen?.local?.pythonPath) return 'Local diffusion';return 'Local diffusion (not configured)';@@ -92,7 +92,7 @@ const summarizeMode = (cfg, autoResolution) => {const head = cfg.imageMode === 'auto'? `auto → ${autoResolution.toLowerCase()}`: cfg.imageMode;- const tail = cfg.imageMode === 'local' && cfg.imageModelId ? ` / ${cfg.imageModelId}` : '';+ const tail = cfg.imageMode === IMAGE_GEN_MODE.LOCAL && cfg.imageModelId ? ` / ${cfg.imageModelId}` : '';return `Pinned: ${head}${tail}`;};@@ -109,20 +109,20 @@ function VisualGenSettingsBody({ cfg, update, stageLabel, systemSettings, imageM<BackendChipStripavailableBackends={availableBackends}value={cfg.imageMode}- onChange={(id) => update({ imageMode: id, ...(id !== 'local' ? { imageModelId: null } : {}) })}+ onChange={(id) => update({ imageMode: id, ...(id !== IMAGE_GEN_MODE.LOCAL ? { imageModelId: null } : {}) })}size="sm"ariaLabel={`${stageLabel} image backend`}titlePrefix="Render images via"/><p className="text-[10px] text-gray-500 mt-1">{blurb}</p>- {cfg.imageMode === 'codex' && !systemSettings?.imageGen?.codex?.enabled && (+ {cfg.imageMode === IMAGE_GEN_MODE.CODEX && !systemSettings?.imageGen?.codex?.enabled && (<p className="text-[10px] text-port-warning mt-1">Codex Imagegen is disabled in Settings — renders will fall back to local diffusion.</p>)}</div>- {cfg.imageMode === 'local' && (+ {cfg.imageMode === IMAGE_GEN_MODE.LOCAL && (<div><div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Local image model@@ -309,7 +309,7 @@ export function genConfigToImageOptions(cfg) {if (!cfg) return {};const out = {};if (cfg.imageMode && cfg.imageMode !== 'auto') out.mode = cfg.imageMode;- if (cfg.imageMode === 'local' && cfg.imageModelId) out.modelId = cfg.imageModelId;+ if (cfg.imageMode === IMAGE_GEN_MODE.LOCAL && cfg.imageModelId) out.modelId = cfg.imageModelId;return out;}diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 832d2d930b..c2353e8972 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -19,6 +19,7 @@ import {registerTool, updateTool, getToolsList,getHfTokenStatus, saveHfToken, clearHfToken,} from '../../services/api';+import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';const SDAPI_TOOL_ID = 'sdapi';const CODEX_TOOL_ID = 'codex-imagegen';@@ -37,7 +38,7 @@ export function ImageGenTab() {const [saving, setSaving] = useState(false);// Mode + per-mode config- const [mode, setMode] = useState('external');+ const [mode, setMode] = useState(IMAGE_GEN_MODE.EXTERNAL);const [sdapiUrl, setSdapiUrl] = useState('');const [pythonPath, setPythonPath] = useState('');const [exposeA1111, setExposeA1111] = useState(false);@@ -70,7 +71,7 @@ export function ImageGenTab() {// Snapshot of saved values so we can show the "dirty" stateconst [saved, setSaved] = useState({- mode: 'external', sdapiUrl: '', pythonPath: '', exposeA1111: false,+ mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', exposeA1111: false,codexEnabled: false, codexPath: '', codexModel: '', codexParallelLimit: 1,autoCleanByMode: { external: false, local: false, codex: false },});@@ -132,7 +133,7 @@ export function ImageGenTab() {Promise.all([getSettings(), getToolsList()]).then(([s, tools]) => {const ig = s?.imageGen || {};- const m = ig.mode || 'external';+ const m = ig.mode || IMAGE_GEN_MODE.EXTERNAL;const url = normalizeUrl(ig.external?.sdapiUrl || ig.sdapiUrl);const py = ig.local?.pythonPath || '';const expose = ig.expose?.a1111 === true;@@ -243,9 +244,9 @@ export function ImageGenTab() {// Both tool entries are independent — sync them in parallel so a// tailnet save doesn't pay two sequential HTTP round-trips.- const sdEnabled = mode === 'external' ? !!url : (mode === 'local' ? !!pythonPath : false);+ const sdEnabled = mode === IMAGE_GEN_MODE.EXTERNAL ? !!url : (mode === IMAGE_GEN_MODE.LOCAL ? !!pythonPath : false);const sdToolData = {- name: mode === 'external' ? 'Stable Diffusion (External)' : (mode === 'local' ? 'Stable Diffusion (Local mflux)' : 'Stable Diffusion'),+ name: mode === IMAGE_GEN_MODE.EXTERNAL ? 'Stable Diffusion (External)' : (mode === IMAGE_GEN_MODE.LOCAL ? 'Stable Diffusion (Local mflux)' : 'Stable Diffusion'),category: 'image-generation',description: 'Generate images via the active PortOS image gen backend',enabled: sdEnabled,@@ -308,7 +309,7 @@ export function ImageGenTab() {// mark the render complete on the `complete` event (or fail on// `error`). External mode awaits internally and the file is on disk// by the time generateImage resolves, so we can short-circuit.- const isAsync = (result?.mode === 'local' || result?.mode === 'codex');+ const isAsync = (result?.mode === IMAGE_GEN_MODE.LOCAL || result?.mode === IMAGE_GEN_MODE.CODEX);if (isAsync && result?.generationId) {await new Promise((resolve, reject) => {const es = new EventSource(`/api/image-gen/${result.generationId}/events`);@@ -377,8 +378,8 @@ export function ImageGenTab() {<div className={`grid grid-cols-1 sm:grid-cols-2 ${codexEnabled ? 'lg:grid-cols-3' : ''} gap-3`}><buttontype="button"- onClick={() => setMode('external')}- className={`text-left p-4 rounded-lg border transition-colors ${mode === 'external' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ onClick={() => setMode(IMAGE_GEN_MODE.EXTERNAL)}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.EXTERNAL ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}><div className="flex items-center gap-2"><Cloud className="w-4 h-4" />@@ -388,8 +389,8 @@ export function ImageGenTab() {</button><buttontype="button"- onClick={() => setMode('local')}- className={`text-left p-4 rounded-lg border transition-colors ${mode === 'local' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ onClick={() => setMode(IMAGE_GEN_MODE.LOCAL)}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.LOCAL ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}><div className="flex items-center gap-2"><Cpu className="w-4 h-4" />@@ -400,8 +401,8 @@ export function ImageGenTab() {{codexEnabled && (<buttontype="button"- onClick={() => setMode('codex')}- className={`text-left p-4 rounded-lg border transition-colors ${mode === 'codex' ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}+ onClick={() => setMode(IMAGE_GEN_MODE.CODEX)}+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.CODEX ? 'border-port-accent bg-port-accent/10 text-white' : 'border-port-border text-gray-400 hover:bg-port-border/30 hover:text-white'}`}><div className="flex items-center gap-2"><Terminal className="w-4 h-4" />@@ -414,7 +415,7 @@ export function ImageGenTab() {</div>{/* External-mode config */}- {mode === 'external' && (+ {mode === IMAGE_GEN_MODE.EXTERNAL && (<div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4"><h3 className="text-sm font-medium text-gray-300">External AUTOMATIC1111 / Forge URL</h3><input@@ -425,12 +426,12 @@ export function ImageGenTab() {placeholder="http://localhost:7860"/><p className="text-xs text-gray-500">Base URL for the SD WebUI server PortOS should send generation requests to.</p>- <AutoCleanToggle checked={autoCleanByMode.external} onChange={setAutoCleanFor('external')} />+ <AutoCleanToggle checked={autoCleanByMode.external} onChange={setAutoCleanFor(IMAGE_GEN_MODE.EXTERNAL)} /></div>)}{/* Local-mode config */}- {mode === 'local' && (+ {mode === IMAGE_GEN_MODE.LOCAL && (<div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4"><h3 className="text-sm font-medium text-gray-300">Local Python (mflux + mlx_video)</h3><p className="text-xs text-gray-500">@@ -439,7 +440,7 @@ export function ImageGenTab() {and are surfaced in <a href="/media/models" className="text-port-accent hover:underline">Media → Models</a>.</p><LocalSetupPanel pythonPath={pythonPath} onPythonPathChange={setPythonPath} />- <AutoCleanToggle checked={autoCleanByMode.local} onChange={setAutoCleanFor('local')} />+ <AutoCleanToggle checked={autoCleanByMode.local} onChange={setAutoCleanFor(IMAGE_GEN_MODE.LOCAL)} /></div>)}@@ -471,10 +472,9 @@ export function ImageGenTab() {// external if a URL is set, else external as a last resort// (so the user lands on a non-broken default rather than// sticking with codex or hopping to an unconfigured backend).- if (!v && mode === 'codex') {+ if (!v && mode === IMAGE_GEN_MODE.CODEX) {const hasLocal = !!pythonPath?.trim();- const hasExternal = !!normalizeUrl(sdapiUrl);- setMode(hasLocal ? 'local' : (hasExternal ? 'external' : 'external'));+ setMode(hasLocal ? IMAGE_GEN_MODE.LOCAL : IMAGE_GEN_MODE.EXTERNAL);}}}className="rounded"@@ -535,7 +535,7 @@ export function ImageGenTab() {)}</p></div>- <AutoCleanToggle checked={autoCleanByMode.codex} onChange={setAutoCleanFor('codex')} />+ <AutoCleanToggle checked={autoCleanByMode.codex} onChange={setAutoCleanFor(IMAGE_GEN_MODE.CODEX)} /></div>)}</div>diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.jsindex 3b06e5ed3f..c92ba9bba0 100644--- a/client/src/lib/imageGenBackends.js+++ b/client/src/lib/imageGenBackends.js@@ -1,6 +1,6 @@import { Cpu, Terminal, Cloud } from 'lucide-react';-export const IMAGE_GEN_MODE = { LOCAL: 'local', CODEX: 'codex', EXTERNAL: 'external' };+export const IMAGE_GEN_MODE = Object.freeze({ LOCAL: 'local', CODEX: 'codex', EXTERNAL: 'external' });const META = {[IMAGE_GEN_MODE.LOCAL]: { label: 'Local', icon: Cpu },diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.jsindex 33c6aa3c7c..f68ddcecf8 100644--- a/client/src/lib/imageGenResolutions.js+++ b/client/src/lib/imageGenResolutions.js@@ -7,6 +7,7 @@// ERNIE were trained at 1024² and degrade past ~1280, and gpt-image-2's// native sizes are 1024² / 1024×1536 / 1536×1024.import { RUNNER_FAMILIES } from './runnerFamilies';+import { IMAGE_GEN_MODE } from './imageGenBackends';// `flux1` and `external` aren't members of RUNNER_FAMILIES — they're synthetic// compatibility-only keys ('flux1' = mflux/diffusers fallback when no `runner`@@ -44,8 +45,8 @@ export const RESOLUTIONS = [// Flux 1 (mflux/diffusers, `dev` / `schnell`) has no `runner` field — it's// the fallback for local mode when nothing more specific matches.export const compatibilityKey = (mode, runner) => {- if (mode === 'codex') return 'codex';- if (mode === 'external') return 'external';+ if (mode === IMAGE_GEN_MODE.CODEX) return 'codex';+ if (mode === IMAGE_GEN_MODE.EXTERNAL) return 'external';if (runner === RUNNER_FAMILIES.FLUX2|| runner === RUNNER_FAMILIES.Z_IMAGE|| runner === RUNNER_FAMILIES.ERNIE) {diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.jsindex 98a12d68c6..e23b69165c 100644--- a/client/src/lib/wrImageDefaults.js+++ b/client/src/lib/wrImageDefaults.js@@ -5,6 +5,8 @@// the /api/image-gen/style-presets endpoint at runtime; only the two// special discriminators live here.+import { IMAGE_GEN_MODE } from './imageGenBackends';+export const STYLE_ID = Object.freeze({ NONE: 'none', CUSTOM: 'custom' });export const EMPTY_IMAGE_STYLE = Object.freeze({ presetId: STYLE_ID.NONE, prompt: '', negativePrompt: '' });@@ -15,7 +17,7 @@ export const EMPTY_IMAGE_STYLE = Object.freeze({ presetId: STYLE_ID.NONE, prompt// for seed. Parsed to numbers at the generateImage boundary in SceneCard.export const WR_IMAGE_DEFAULTS = Object.freeze({modelId: 'flux2-klein-4b',- mode: 'local',+ mode: IMAGE_GEN_MODE.LOCAL,width: 768,height: 512,steps: '',diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 7ca83d0349..70490973a7 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -193,9 +193,9 @@ export default function ImageGen() {// selectedMode is null until settings load — fall back to status.mode// so the form doesn't flicker between defaults.- const effectiveMode = selectedMode || status?.mode || 'external';- const isLocalMode = effectiveMode === 'local';- const isCodexMode = effectiveMode === 'codex';+ const effectiveMode = selectedMode || status?.mode || IMAGE_GEN_MODE.EXTERNAL;+ const isLocalMode = effectiveMode === IMAGE_GEN_MODE.LOCAL;+ const isCodexMode = effectiveMode === IMAGE_GEN_MODE.CODEX;const isAsyncMode = isLocalMode || isCodexMode;// Prefer the socket-driven hook (carries currentImage for both modes since// local mflux now writes stepwise frames). Fall back to the local SSE's@@ -590,7 +590,7 @@ export default function ImageGen() {prompt: composed.prompt,negativePrompt: composed.negativePrompt || undefined,width, height,- mode: 'codex',+ mode: IMAGE_GEN_MODE.CODEX,autoClean,} : {prompt: composed.prompt,@@ -603,7 +603,7 @@ export default function ImageGen() {quantize,loraFilenames: selectedLoras.map((l) => l.filename),loraScales: selectedLoras.map((l) => l.scale),- mode: 'local',+ mode: IMAGE_GEN_MODE.LOCAL,autoClean,};const hasInitImage = isLocalMode && initImage.source != null;@@ -747,7 +747,7 @@ export default function ImageGen() {width, height,steps: steps ? Number(steps) : 25,cfgScale,- mode: 'external',+ mode: IMAGE_GEN_MODE.EXTERNAL,autoClean,};if (seed && Number(seed) >= 0) payload.seed = Number(seed);@@ -865,7 +865,7 @@ export default function ImageGen() {: 'border-port-error/40 bg-port-error/10 text-port-error'}`}>{status.connected ? (- <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === 'local' ? 'mflux/local' : status.mode === 'codex' ? 'codex CLI' : 'external SD API')}</>+ <><span className="w-2 h-2 rounded-full bg-port-success" /> {status.model || (status.mode === IMAGE_GEN_MODE.LOCAL ? 'mflux/local' : status.mode === IMAGE_GEN_MODE.CODEX ? 'codex CLI' : 'external SD API')}</>) : (<><AlertTriangle className="w-3 h-3" />diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 1f444e4d58..bd47ba2cb7 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -19,7 +19,7 @@ import {} from '../lib/validation.js';import { optionalUploadFields } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';-import { local, IMAGE_GEN_MODES, resolveAutoClean } from '../services/imageGen/index.js';+import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES, resolveAutoClean } from '../services/imageGen/index.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getSettings, saveSettings } from '../services/settings.js';import { getHfToken, getHfTokenInfo, HF_TOKEN_REGEX } from '../lib/hfToken.js';@@ -195,7 +195,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// 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 || 'external';+ const mode = data.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;// Resolve autoClean ONCE at the route layer so all three dispatch paths// (synchronous external, codex queue, local queue) see the same value.// Stamp onto `data` so the value flows through the spread-into-params@@ -209,7 +209,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// 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 !== 'local') {+ if (mode !== IMAGE_GEN_MODE.LOCAL) {cleanupReqFilesTemp();throw new ServerError('Reference images are only supported for local FLUX.2 renders',@@ -287,7 +287,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// call with no local single-flight constraint to absorb. `settings` and// `mode` were already resolved above (so the FLUX.2 + local-backend gate// could fire before staging any uploads).- if (mode === 'codex') {+ if (mode === IMAGE_GEN_MODE.CODEX) {// Reject up-front rather than enqueueing a doomed job — codex is gated// behind an explicit toggle since not every Codex account has access to// the image_gen tool.@@ -300,19 +300,19 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {}const queued = enqueueJob({kind: 'image',- // `mode: 'codex'` is the queue's discriminator — laneForJob() routes- // codex jobs to the codex lane, and runJob's image branch dispatches- // to imageGen/codex.js when it sees this flag.+ // `mode: IMAGE_GEN_MODE.CODEX` is the queue's discriminator —+ // laneForJob() routes codex jobs to the codex lane, and runJob's image+ // branch dispatches to imageGen/codex.js when it sees this flag.params: {- mode: 'codex',+ mode: IMAGE_GEN_MODE.CODEX,codexPath: c.codexPath,model: c.model,...data,},});- return res.json(queuedImageResponse({ ...queued, mode: 'codex', model: c.model || null }));+ return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.CODEX, model: c.model || null }));}- if (mode === 'local') {+ 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@@ -345,7 +345,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// modelId → 'dev' → allModels[0]) rather than just the requested id.return res.json(queuedImageResponse({...queued,- mode: 'local',+ mode: IMAGE_GEN_MODE.LOCAL,model: selectedModel?.id || data.modelId || 'dev',}));}diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.jsindex 13cbb03eb0..c1a69240e0 100644--- a/server/routes/imageGen.test.js+++ b/server/routes/imageGen.test.js@@ -9,6 +9,7 @@ vi.mock('../services/imageGen/index.js', () => ({generateAvatar: vi.fn(),attachSseClient: vi.fn(() => false),cancel: vi.fn(() => false),+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },IMAGE_GEN_MODES: ['external', 'local', 'codex'],// Mirror the real precedence so route-level resolution behaves correctly// under test: explicit body bool wins, otherwise fall back to settings.diff --git a/server/routes/sdapi.js b/server/routes/sdapi.jsindex 0605879935..0f0ba261c0 100644--- a/server/routes/sdapi.js+++ b/server/routes/sdapi.js@@ -22,7 +22,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { PATHS, tryReadFile } from '../lib/fileUtils.js';import { getSettings } from '../services/settings.js';-import { generateImage, getMode, getActiveJob } from '../services/imageGen/index.js';+import { generateImage, getMode, getActiveJob, IMAGE_GEN_MODE } from '../services/imageGen/index.js';import { local as localImage } from '../services/imageGen/index.js';import { createImageGenWaiter } from '../services/imageGenWaiter.js';import { listVideoModels, defaultVideoModelId } from '../services/videoGen/local.js';@@ -55,7 +55,7 @@ router.use(asyncHandler(async (req, res, next) => {router.get('/options', asyncHandler(async (_req, res) => {const mode = await getMode();const models = localImage.listImageModels();- const defaultModel = mode === 'local' ? `portos-local-${models[0]?.id || 'dev'}` : 'portos-external';+ const defaultModel = mode === IMAGE_GEN_MODE.LOCAL ? `portos-local-${models[0]?.id || 'dev'}` : 'portos-external';res.json({sd_model_checkpoint: defaultModel,sampler_name: 'Euler',@@ -74,7 +74,7 @@ router.post('/options', (_req, res) => {// a model picker; the external mode shows a single "remote-passthrough" stub.router.get('/sd-models', asyncHandler(async (_req, res) => {const mode = await getMode();- if (mode === 'local') {+ if (mode === IMAGE_GEN_MODE.LOCAL) {return res.json(localImage.listImageModels().map((m) => ({title: `portos-local-${m.id} [flux]`,model_name: `portos-local-${m.id}`,@@ -175,7 +175,7 @@ router.post('/txt2img', asyncHandler(async (req, res) => {// file is on disk by the time generateImage resolves, so the wait is a// no-op there.const mode = await getMode();- const isAsyncMode = mode === 'local' || mode === 'codex';+ const isAsyncMode = mode === IMAGE_GEN_MODE.LOCAL || mode === IMAGE_GEN_MODE.CODEX;const localWait = isAsyncMode? createCompletionWaiter(): { register: () => {}, promise: Promise.resolve(), cleanup: () => {} };diff --git a/server/routes/sdapi.test.js b/server/routes/sdapi.test.jsindex 30ac89854b..b7277d5483 100644--- a/server/routes/sdapi.test.js+++ b/server/routes/sdapi.test.js@@ -10,6 +10,7 @@ vi.mock('../services/imageGen/index.js', () => ({generateImage: vi.fn(),getMode: vi.fn(),getActiveJob: vi.fn(),+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },local: { listImageModels: vi.fn(() => [{ id: 'dev', name: 'Flux 1 Dev' }]) },}));diff --git a/server/routes/universeBuilder.js b/server/routes/universeBuilder.jsindex 7c6938a499..c67fa2b890 100644--- a/server/routes/universeBuilder.js+++ b/server/routes/universeBuilder.js@@ -31,6 +31,7 @@ import { getSettings } from '../services/settings.js';import { findOrCreateUniverseCollection } from '../services/mediaCollections.js';import { registerUniverseBuilderRun } from '../services/universeBuilderCollectionHook.js';import { getImageModels, isFlux2, isZImage, isErnie } from '../lib/mediaModels.js';+import { IMAGE_GEN_MODE } from '../services/imageGen/modes.js';import { getStylePresetById } from '../lib/writersRoomStylePresets.js';const router = Router();@@ -440,12 +441,12 @@ router.post('/:id/render', asyncHandler(async (req, res) => {}const settings = await getSettings();- const mode = body.mode || settings.imageGen?.mode || 'external';+ const mode = body.mode || settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;// Reject `external` mode upfront — batch rendering against a remote SD-API// would block this request for the entire batch, and we don't want to leave// an orphaned media collection behind when we discover this mid-loop below.- if (mode !== 'local' && mode !== 'codex') {+ if (mode !== IMAGE_GEN_MODE.LOCAL && mode !== IMAGE_GEN_MODE.CODEX) {throw new ServerError('Batch render requires local or codex mode — switch image-gen mode in Settings → Image Gen',{ status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },@@ -454,13 +455,13 @@ router.post('/:id/render', asyncHandler(async (req, res) => {// Mirror the upfront validation /api/image-gen/generate does so a doomed// batch fails before any jobs land in the queue.- if (mode === 'codex' && !settings.imageGen?.codex?.enabled) {+ if (mode === IMAGE_GEN_MODE.CODEX && !settings.imageGen?.codex?.enabled) {throw new ServerError('Codex Imagegen is disabled — enable it in Settings → Image Gen first',{ status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },);}- if (mode === 'local') {+ 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)) {@@ -554,14 +555,14 @@ router.post('/:id/render', asyncHandler(async (req, res) => {},};let queued;- if (mode === 'codex') {+ if (mode === IMAGE_GEN_MODE.CODEX) {const c = settings.imageGen?.codex || {};queued = enqueueJob({kind: 'image',- params: { mode: 'codex', codexPath: c.codexPath, model: c.model, ...params },+ params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, ...params },});} else {- // mode === 'local' (validated upfront).+ // mode === IMAGE_GEN_MODE.LOCAL (validated upfront).const py = settings.imageGen?.local?.pythonPath || null;queued = enqueueJob({kind: 'image',diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 01b2b87e16..0a31542708 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -29,6 +29,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';+import { IMAGE_GEN_MODE } from './modes.js';// 20 minutes — built-in `image_gen` typically returns in 30–90s, but with the// parallel codex lane several renders share OpenAI throughput and a single@@ -109,11 +110,11 @@ export async function checkConnection({ codexPath } = {}) {proc.stdout.on('data', (c) => { out += c.toString(); });proc.stderr.on('data', (c) => { out += c.toString(); });return new Promise((resolve) => {- proc.on('error', (err) => resolve({ connected: false, mode: 'codex', reason: `Codex CLI not found (${err.message})` }));+ proc.on('error', (err) => resolve({ connected: false, mode: IMAGE_GEN_MODE.CODEX, reason: `Codex CLI not found (${err.message})` }));proc.on('close', (code) => {- if (code !== 0) return resolve({ connected: false, mode: 'codex', reason: `codex --version exited ${code}` });+ if (code !== 0) return resolve({ connected: false, mode: IMAGE_GEN_MODE.CODEX, reason: `codex --version exited ${code}` });const versionMatch = out.match(/codex-cli\s+([\d.]+)/i) || out.match(/(\d+\.\d+\.\d+)/);- resolve({ connected: true, mode: 'codex', model: versionMatch ? `codex-cli ${versionMatch[1]}` : 'codex-cli' });+ resolve({ connected: true, mode: IMAGE_GEN_MODE.CODEX, model: versionMatch ? `codex-cli ${versionMatch[1]}` : 'codex-cli' });});});}@@ -185,7 +186,7 @@ export async function generateImage({const meta = {id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',width: width ? Number(width) : null, height: height ? Number(height) : null,- filename, mode: 'codex', model: model || 'codex',+ filename, mode: IMAGE_GEN_MODE.CODEX, model: model || 'codex',createdAt: new Date().toISOString(),};const job = { ...meta, clients: [], status: 'running' };@@ -205,7 +206,7 @@ export async function generateImage({return {jobId, filename, path: `/data/images/${filename}`, generationId: jobId,- mode: 'codex', model: model || null,+ mode: IMAGE_GEN_MODE.CODEX, model: model || null,// Async callers gate UI state on `status`; without 'running' they flip// to 'done' before the PNG lands. SSE / socket 'completed' fires later.status: 'running',@@ -314,7 +315,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { aut// SSE complete + completed events so subscribers see the cleaned bytes.// codex output is the highest-value target for cleaning because gpt-image// is the one provider that embeds C2PA provenance.- await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: 'codex' });+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.CODEX });job.status = 'complete';if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);activeJobs.delete(jobId);diff --git a/server/services/imageGen/external.js b/server/services/imageGen/external.jsindex 004d5d257b..ea878a82c1 100644--- a/server/services/imageGen/external.js+++ b/server/services/imageGen/external.js@@ -14,6 +14,7 @@ import { ServerError } from '../../lib/errorHandler.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';+import { IMAGE_GEN_MODE } from './modes.js';const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';const PROGRESS_POLL_INTERVAL = 500;@@ -54,7 +55,7 @@ export async function checkConnection(sdapiUrl) {const options = await res.json().catch(() => null);const model = options?.sd_model_checkpoint || 'unknown';cachedModel = { name: model, timestamp: Date.now(), baseUrl };- return { connected: true, model, mode: 'external', baseUrl };+ return { connected: true, model, mode: IMAGE_GEN_MODE.EXTERNAL, baseUrl };}function startProgressPolling(baseUrl, generationId) {@@ -128,7 +129,7 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, hgenerationId, prompt, negativePrompt,width: payload.width, height: payload.height, steps: payload.steps,cfgScale: payload.cfg_scale, seed: payload.seed,- modelId: model, mode: 'external',+ modelId: model, mode: IMAGE_GEN_MODE.EXTERNAL,step: 0, progress: 0, totalSteps: payload.steps, currentImage: null,createdAt: new Date().toISOString(),};@@ -171,10 +172,10 @@ export async function generateImage({ sdapiUrl, prompt, negativePrompt, width, h// Auto-clean BEFORE the SSE complete fires so the URL the client opens// serves the cleaned bytes. External mode has no sidecar — pass null so// the helper just patches the PNG in place.- await autoCleanGeneratedImage({ enabled: autoClean, pngPath, sidecarPath: null, mode: 'external' });+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath, sidecarPath: null, mode: IMAGE_GEN_MODE.EXTERNAL });const path = `/data/images/${filename}`;console.log(`🖼️ Image saved: ${filename}`);activeJob = null;imageGenEvents.emit('completed', { generationId, path, filename });- return { generationId, filename, path, mode: 'external', model };+ return { generationId, filename, path, mode: IMAGE_GEN_MODE.EXTERNAL, model };}diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 07de1d671e..37f3c7efcd 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -17,9 +17,15 @@ import { ServerError } from '../../lib/errorHandler.js';import * as external from './external.js';import * as local from './local.js';import * as codex from './codex.js';+import { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from './modes.js';-export const IMAGE_GEN_MODES = Object.freeze(['external', 'local', 'codex']);-const DEFAULT_MODE = 'external';+// Re-export the enum + array so the existing import surface from this module+// keeps working. `IMAGE_GEN_MODE.X` is the preferred form at dispatch sites+// (server + client); `IMAGE_GEN_MODES` is the alphabet for Zod / OpenAI+// tool-spec enums. Defined in `./modes.js` to avoid a circular import with+// the provider modules above.+export { IMAGE_GEN_MODE, IMAGE_GEN_MODES };+const DEFAULT_MODE = IMAGE_GEN_MODE.EXTERNAL;const cfg = (s) => s?.imageGen || {};const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;@@ -43,12 +49,12 @@ export async function getMode() {export async function checkConnection({ mode: modeOverride } = {}) {const s = await getSettings();const mode = modeOverride || cfg(s).mode || DEFAULT_MODE;- if (mode === 'local') {+ if (mode === IMAGE_GEN_MODE.LOCAL) {const py = pythonPath(s);if (!py) return { connected: false, mode, reason: 'Python path not configured' };return { connected: true, mode, model: 'mflux/local', pythonPath: py };}- if (mode === 'codex') {+ if (mode === IMAGE_GEN_MODE.CODEX) {const c = codexCfg(s);if (!c.enabled) return { connected: false, mode, reason: 'Codex Imagegen is disabled in settings' };return codex.checkConnection({ codexPath: c.codexPath });@@ -74,7 +80,7 @@ export async function generateImage(params) {// (gpt-image-2 image-edit via codex CLI's -i flag). External SD-API has no// i2i wiring in this codebase, so drop the init image there rather than// failing the whole render — the prompt still produces a useful txt2img.- if (mode === 'external' && (normalized.initImagePath || normalized.initImageStrength != null)) {+ if (mode === IMAGE_GEN_MODE.EXTERNAL && (normalized.initImagePath || normalized.initImageStrength != null)) {delete normalized.initImagePath;delete normalized.initImageStrength;}@@ -85,7 +91,7 @@ export async function generateImage(params) {// the spread.const autoClean = resolveAutoClean(normalized.autoClean, s, mode);delete normalized.autoClean;- if (mode === 'codex') {+ if (mode === IMAGE_GEN_MODE.CODEX) {const c = codexCfg(s);if (!c.enabled) {throw new ServerError(@@ -95,7 +101,7 @@ export async function generateImage(params) {}return codex.generateImage({ codexPath: c.codexPath, model: c.model, autoClean, ...normalized });}- if (mode === 'local') {+ if (mode === IMAGE_GEN_MODE.LOCAL) {return local.generateImage({ pythonPath: pythonPath(s), autoClean, ...normalized });}return external.generateImage({ sdapiUrl: sdapiUrl(s), autoClean, ...normalized });diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 023dcd65c2..fe4da2401b 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -25,6 +25,7 @@ import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';import { resolveFlux2Python, FLUX2_VENV_DEFAULT } from '../../lib/pythonSetup.js';import { hfTokenEnv } from '../../lib/hfToken.js';+import { IMAGE_GEN_MODE } from './modes.js';const IS_WIN = process.platform === 'win32';@@ -333,7 +334,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mconsole.log(`🎨 Generating image [${jobId.slice(0, 8)}] local: ${modelId} ${width}x${height} steps=${actualSteps}`);imageGenEvents.emit('started', { generationId: jobId, totalSteps: actualSteps });- activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: 'local' };+ activeJob = { ...meta, generationId: jobId, totalSteps: actualSteps, step: 0, progress: 0, currentImage: null, mode: IMAGE_GEN_MODE.LOCAL };const proc = spawn(bin, args, { env: { ...process.env, ...(await hfTokenEnv()) }, stdio: ['ignore', 'pipe', 'pipe'] });activeProcess = proc;@@ -559,7 +560,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mawait writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});// Auto-clean (settings.imageGen.local.autoClean) — runs BEFORE the// SSE complete + completed events so subscribers see the cleaned bytes.- await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: 'local' });+ await autoCleanGeneratedImage({ enabled: autoClean, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.LOCAL });console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename}`);const result = { filename, seed: actualSeed, path: `/data/images/${filename}` };broadcastSse(job, { type: 'complete', result });@@ -570,7 +571,7 @@ export async function generateImage({ pythonPath, prompt, negativePrompt = '', mcloseJobAfterDelay(jobs, jobId);});- return { jobId, filename, path: `/data/images/${filename}`, generationId: jobId, mode: 'local', model: modelId, seed: actualSeed };+ return { jobId, filename, path: `/data/images/${filename}`, generationId: jobId, mode: IMAGE_GEN_MODE.LOCAL, model: modelId, seed: actualSeed };}// Validate a gallery filename: PNG-only, basename only, no path separators.diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsnew file mode 100644index 0000000000..644adfb3e9--- /dev/null+++ b/server/services/imageGen/modes.js@@ -0,0 +1,19 @@+/**+ * Image Gen — mode enum.+ *+ * Standalone so the dispatcher (`index.js`) and the provider modules+ * (`codex.js`, `local.js`, `external.js`) can both import without forming a+ * cycle (index.js already imports from each provider).+ *+ * `IMAGE_GEN_MODE.X` is the preferred form at branching/tagging sites.+ * `IMAGE_GEN_MODES` is the alphabet for Zod / OpenAI tool-spec enums.+ * Single source of truth: derive the array from `Object.values(...)`.+ */++export const IMAGE_GEN_MODE = Object.freeze({+ EXTERNAL: 'external',+ LOCAL: 'local',+ CODEX: 'codex',+});++export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 634dc6fc4a..16f08d4b78 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -41,8 +41,9 @@ import {import { videoGenEvents } from '../videoGen/events.js';import { imageGenEvents } from '../imageGenEvents.js';import { getSettings } from '../settings.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';-const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === 'codex';+const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === IMAGE_GEN_MODE.CODEX;const JOBS_FILE = join(PATHS.data, 'media-jobs.json');const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;@@ -107,7 +108,7 @@ export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'fa// so a new provider addition is one edit instead of three.function getGenModuleForJob(job) {if (job.kind === 'video') return import('../videoGen/local.js');- if (job.kind === 'image' && job.params?.mode === 'codex') return import('../imageGen/codex.js');+ if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');if (job.kind === 'image') return import('../imageGen/local.js');return Promise.resolve(null);}diff --git a/server/services/pipeline/visualStages.js b/server/services/pipeline/visualStages.jsindex 7922842876..8fd0c66a5e 100644--- a/server/services/pipeline/visualStages.js+++ b/server/services/pipeline/visualStages.js@@ -44,6 +44,7 @@ import { runPromptRefine } from './refineHelpers.js';import { pickCanon } from './seriesCanon.js';import { STYLE_PROMPT_OVERRIDE_MODE_DEFAULT } from './series.js';import { ASPECT_PRESETS } from '../../lib/creativeDirectorPresets.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';const joinStyleParts = (...parts) =>parts.map((s) => (s || '').trim()).filter(Boolean).join(', ');@@ -87,13 +88,13 @@ const applyWorldStyle = (prompt, world, series = null) => {// local diffusion (flux-1) the way the original default behaved.const resolveMode = (options, settings) => {const codexEnabled = settings?.imageGen?.codex?.enabled === true;- if (options.mode === 'codex' && codexEnabled) return 'codex';- if (options.mode === 'local') return 'local';+ if (options.mode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (options.mode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;const settingsMode = settings?.imageGen?.mode;- if (settingsMode === 'codex' && codexEnabled) return 'codex';- if (settingsMode === 'local') return 'local';- if (codexEnabled) return 'codex';- return 'local';+ if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;+ if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;+ if (codexEnabled) return IMAGE_GEN_MODE.CODEX;+ return IMAGE_GEN_MODE.LOCAL;};// Defensive fallback — an unrecognized value must never land in the final@@ -178,8 +179,8 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin...(options.initImagePath ? { initImagePath: options.initImagePath } : {}),...(Number.isFinite(options.initImageStrength) ? { initImageStrength: options.initImageStrength } : {}),};- const params = mode === 'codex'- ? { mode: 'codex', codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, ...baseParams }+ const params = mode === IMAGE_GEN_MODE.CODEX+ ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, ...baseParams }: { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, ...baseParams };const { jobId } = enqueueJob({ kind: 'image', params, owner });console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex f7b90891a4..146a412aa0 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -24,6 +24,7 @@ import { buildStyleClause, purgeReferenceSheetFromAllUniverses } from './universimport { getImageModels } from '../lib/mediaModels.js';import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';import { findOrCreateUniverseCollection } from './mediaCollections.js';+import { IMAGE_GEN_MODE } from './imageGen/modes.js';import {flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,} from '../lib/canonPrompt.js';@@ -232,7 +233,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options// the media-job queue with the active mode set; codex and local are both// first-class. External SD-API has no multi-zone layout support, so it// gets a clear remediation rather than a silently-degraded render.- const activeMode = settings.imageGen?.mode || 'local';+ const activeMode = settings.imageGen?.mode || IMAGE_GEN_MODE.LOCAL;const baseParams = {mode: activeMode,prompt,@@ -243,7 +244,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, optionslet modelId = null;let params;- if (activeMode === 'codex') {+ if (activeMode === IMAGE_GEN_MODE.CODEX) {const c = settings.imageGen?.codex || {};if (!c.enabled) {throw new ServerError(@@ -253,7 +254,7 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options}modelId = c.model || 'codex';params = { ...baseParams, codexPath: c.codexPath, model: c.model };- } else if (activeMode === 'local') {+ } else if (activeMode === IMAGE_GEN_MODE.LOCAL) {const allModels = getImageModels();modelId = resolveSheetModelId({ override: options.modelId, settings, allModels });if (!modelId) {