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: share one cloud-CLI image-provider config resolver across dispatch sites (#2881)
[._.]/ Adam Eivy52c64832f09b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0d00f8276f..7ceb411d38 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -77,3 +77,4 @@- **[issue-2842] Barrel-split `checkInfra`, `layeredIntelligence`, and `seriesAutopilot` by sub-domain** — the three remaining ~2.6k-line multi-domain server files each become a thin re-exporting barrel over a new same-named directory, mirroring the `arcPlanner.js` split (#1152). `server/lib/editorial/checkInfra.js` → `checkInfra/{externals,taxonomy,revealForeshadowing,craftStages,voiceCanon,structureStages,povAndNames,canonScaffolding,llmRunner,readability,rosterCast,sceneAnalysis,proseDensity,comic}.js`; `server/services/layeredIntelligence.js` → `layeredIntelligence/{constants,config,dedup,proposal,outcomes,awareness,gates,prompt,runCli,sources,semanticDedup,forgeFiler,jiraFiler,planFiler}.js`; `server/services/pipeline/seriesAutopilot.js` → `seriesAutopilot/{state,config,convergence,stepResolver,session,childRuns,editorialSteps,visualSteps,revisionSteps,dispatch,dryRun,orchestrator}.js`. No caller changes — every existing deep import still resolves through the barrel, and `seriesAutopilot`'s `__testing` bundle is reassembled from the split modules. Three new `*Barrel.test.js` suites pin the contract (every module export reachable through the barrel as the same object, no cross-module symbol collisions). The largest resulting module is 439 lines, down from 2,635.- **[issue-2841] Convert long positional parameter lists to options objects** — `appendIntervalOccurrences` (8 args) and its sibling `appendCronOccurrences` in `server/services/workflow.js`, `scaffoldVite` (7 args) and the equally-long `scaffoldPortOS` in `server/routes/`, and `createAgentRun` (6 args) in `server/services/agentRunTracking.js` now take a single destructured options object, matching the codebase's dominant convention and removing the "which of these five interchangeable numbers goes where" hazard at each call site. All call sites updated; `scaffold.test.js` gains two regression tests pinning the named-options dispatch shape. Behavior-preserving.- **[issue-2890] Take the held-back `undici` 8 bump** — the failing `safeUrlFetch` pin test turned out not to be about `connect.lookup` at all (undici 8's connector still honors it, so the DNS-rebinding IP pin is expressed exactly as before). undici 8 dropped v7's implicit wrapping of the legacy `onConnect`/`onHeaders`/`onComplete` request-handler shape, so a bare undici-8 `Agent` handed to the *built-in* `fetch` of any Node that still bundles undici 7 (22/24/25, including the 24.x CI matrix) throws `InvalidArgumentError: invalid onRequestStart method` — and because `fetchGuarded` swallows network errors to null, every guarded fetch would have silently returned null rather than falling back to an unpinned connect. The new exported `buildPinnedDispatcher()` wraps the pinned `Agent` in undici 8's documented `Dispatcher1Wrapper`, which both the legacy and the v8 handler contracts accept, so one build works across Node 22→26. The end-to-end pin proof now runs through that production factory instead of a hand-rolled `new Agent(...)`, so it also guards the runtime-compat half.+- **[issue-2881] Extract a shared cloud-CLI image-provider resolver** — `resolveCloudProviderConfig(settings, mode)` in the new `server/services/imageGen/cloudProviderConfig.js` owns the enable-gate + job-param bundle that seven dispatch sites (the image-gen route, the dispatcher's `generateImage`/`checkConnection`, first-pass gen, LoRA dataset gen, universe batch render, character reference sheets, pipeline visual stages) each duplicated once per cloud backend. `resolveMode` in `visualStageHelpers.js` becomes a candidate walk over an `isModeUsable` predicate instead of a ladder that grew two `if`s per backend, and the two providers' no-image error narrations now share `buildNoImageReason`. Behavior-preserving except that a queued grok render's response now reports `model: "grok-imagegen"` (it previously reported nothing) and a codex queue row records the effective model instead of an unset one — both already the value the provider renders with. The provider-module lifecycle harness (grok.js structurally copying codex.js) stays deferred until a third cloud CLI arrives, per the issue's acceptance criteria.diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex e148cb8087..423e3c900d 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -19,7 +19,7 @@ import {import { optionalUploadFields } from '../lib/multipart.js';import * as imageGen from '../services/imageGen/index.js';import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/index.js';-import { CODEX_IMAGEGEN_DEFAULT_MODEL } from '../services/imageGen/modes.js';+import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';import setupRouter from './imageGenSetup.js';import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';import { getImageModels, isFlux2, isEditOnly, repoForModel, requiredReposForModel } from '../lib/mediaModels.js';@@ -388,59 +388,19 @@ 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 === 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.- const c = settings.imageGen?.codex || {};- if (!c.enabled) {- throw new ServerError(- 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },- );- }- // Resolve the effective model so the queue row + response metadata report+ const cloud = resolveCloudProviderConfig(settings, mode);+ if (cloud) {+ // Reject up-front rather than enqueueing a doomed job — the cloud CLIs are+ // gated behind an explicit toggle each (not every Codex account has access+ // to the image_gen tool, and grok spends the user's Grok quota).+ if (!cloud.enabled) throw cloud.disabledError;+ // `mode` inside jobParams is the queue's discriminator — laneForJob()+ // routes cloud jobs to the parallel cloud lane, and runJob's image branch+ // dispatches to the matching imageGen provider module when it sees it.+ // `cloud.modelId` is the *effective* model so the response metadata reports// what actually renders (gpt-5.6-luna by default) instead of "codex"/null.- // codex.generateImage applies the same default, so this is display parity.- const codexModel = c.model || CODEX_IMAGEGEN_DEFAULT_MODEL;- const queued = enqueueJob({- kind: 'image',- // `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: IMAGE_GEN_MODE.CODEX,- codexPath: c.codexPath,- model: codexModel,- effort: c.effort,- ...params,- },- });- return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.CODEX, model: codexModel }));- }- if (mode === IMAGE_GEN_MODE.GROK) {- // Same up-front gate as codex — grok spends the user's Grok quota, so- // it's opt-in via an explicit settings toggle.- const g = settings.imageGen?.grok || {};- if (!g.enabled) {- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }- const queued = enqueueJob({- kind: 'image',- // `mode: IMAGE_GEN_MODE.GROK` is the queue's discriminator — the cloud- // lane routes it alongside codex, and runJob's image branch dispatches- // to imageGen/grok.js when it sees this flag.- params: {- mode: IMAGE_GEN_MODE.GROK,- grokPath: g.grokPath,- aspectRatio: g.aspectRatio,- ...params,- },- });- return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.GROK }));+ const queued = enqueueJob({ kind: 'image', params: { ...cloud.jobParams, ...params } });+ return res.json(queuedImageResponse({ ...queued, mode, model: cloud.modelId }));}if (mode === IMAGE_GEN_MODE.LOCAL) {const py = settings.imageGen?.local?.pythonPath || null;diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.jsindex 578d7b2aa4..17a286bf4d 100644--- a/server/services/creativeDirector/firstPassGen.js+++ b/server/services/creativeDirector/firstPassGen.js@@ -32,6 +32,7 @@ import { enqueueJob } from '../mediaJobQueue/index.js';import { getSettings } from '../settings.js';import { resolveImageCleaners } from '../imageGen/index.js';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { resolveCloudProviderConfig } from '../imageGen/cloudProviderConfig.js';import { getIngredient, listMediaForIngredient } from '../catalogDB.js';import { resolveAspectDimensions } from '../../lib/creativeDirectorPresets.js';import { payloadSnippet, getActiveCatalogType } from '../../lib/catalogTypes.js';@@ -72,25 +73,11 @@ export function buildPortraitPrompt(ingredient) {async function resolveQueueModeParams() {const settings = await getSettings();const mode = settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;- if (mode === IMAGE_GEN_MODE.CODEX) {- const c = settings.imageGen?.codex || {};- if (!c.enabled) return { mode, ready: false, reason: 'codex-disabled' };+ const cloud = resolveCloudProviderConfig(settings, mode);+ if (cloud) {+ if (!cloud.enabled) return { mode, ready: false, reason: cloud.disabledReason };const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- return {- mode,- ready: true,- jobParams: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, effort: c.effort, cleanC2PA, denoise },- };- }- if (mode === IMAGE_GEN_MODE.GROK) {- const g = settings.imageGen?.grok || {};- if (!g.enabled) return { mode, ready: false, reason: 'grok-disabled' };- const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- return {- mode,- ready: true,- jobParams: { mode: IMAGE_GEN_MODE.GROK, grokPath: g.grokPath, aspectRatio: g.aspectRatio, cleanC2PA, denoise },- };+ return { mode, ready: true, jobParams: { ...cloud.jobParams, cleanC2PA, denoise } };}if (mode === IMAGE_GEN_MODE.LOCAL) {// We pass no modelId, so the worker renders with its default ('dev') model —diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsnew file mode 100644index 0000000000..956765b1f5--- /dev/null+++ b/server/services/imageGen/cloudProviderConfig.js@@ -0,0 +1,116 @@+/**+ * Image Gen — shared cloud-CLI provider config resolver.+ *+ * Every surface that can enqueue (or directly run) a cloud-CLI image render+ * repeated the same three steps per provider: read `settings.imageGen.<mode>`,+ * reject when `enabled` isn't true, then assemble that provider's job-param+ * bundle. With two providers (codex, grok) that was ~7 sites × 2 branches of+ * copy-paste, and each new backend doubled it again.+ *+ * `resolveCloudProviderConfig(settings, mode)` collapses all of it into one+ * call. The per-provider knowledge lives in `CLOUD_PROVIDER_SPECS` below, so+ * adding a third cloud CLI is one spec entry instead of a sweep.+ *+ * Deliberately a sibling of `modes.js` rather than part of it: modes.js is the+ * no-dependency enum module both provider modules import, and this file needs+ * `ServerError`.+ */++import { ServerError } from '../../lib/errorHandler.js';+import {+ CLOUD_IMAGE_GEN_MODES,+ CODEX_IMAGEGEN_DEFAULT_MODEL,+ IMAGE_GEN_MODE,+ QUEUEABLE_IMAGE_MODES,+} from './modes.js';++/**+ * Per-provider knowledge, keyed by mode:+ * - `label` — user-facing provider name used in every disabled message.+ * - `modelId` — the *effective* model id for display/metadata (codex+ * defaults to the cheap tier; grok's backend is fixed).+ * - `params` — the provider's knob bundle for a queue job / direct call.+ * Codex's `model` carries the effective (defaulted) id so the+ * queue row reports what actually renders; the provider+ * re-applies the same default, so rendering is unchanged.+ */+export const CLOUD_PROVIDER_SPECS = Object.freeze({+ [IMAGE_GEN_MODE.CODEX]: Object.freeze({+ label: 'Codex Imagegen',+ errorCode: 'CODEX_IMAGEGEN_DISABLED',+ modelId: (c) => c.model || CODEX_IMAGEGEN_DEFAULT_MODEL,+ params: (c) => ({ codexPath: c.codexPath, model: c.model || CODEX_IMAGEGEN_DEFAULT_MODEL, effort: c.effort }),+ }),+ [IMAGE_GEN_MODE.GROK]: Object.freeze({+ label: 'Grok Imagegen',+ errorCode: 'GROK_IMAGEGEN_DISABLED',+ // Grok's image tools run on xAI's fixed image backend — no model knob.+ modelId: () => 'grok-imagegen',+ params: (g) => ({ grokPath: g.grokPath, aspectRatio: g.aspectRatio }),+ }),+});++export const isCloudImageMode = (mode) => Boolean(CLOUD_PROVIDER_SPECS[mode]);++/**+ * Resolve a cloud-CLI provider's settings slice into everything a call site+ * needs. Returns `null` for non-cloud modes (local / external) so callers can+ * keep their own branch for those.+ *+ * Shape:+ * - `enabled` — the settings toggle (strict boolean).+ * - `config` — the raw `settings.imageGen[mode]` slice (never null).+ * - `modelId` — effective model id for response/queue metadata.+ * - `providerParams` — knob bundle WITHOUT `mode` (direct provider calls,+ * which strip the dispatcher-only field).+ * - `jobParams` — `{ mode, ...providerParams }` for `enqueueJob`, where+ * `mode` is the queue's lane discriminator.+ * - `disabledError` — a ready-to-throw ServerError (null when enabled).+ * - `disabledReason` — `'<mode>-disabled'`, for callers that skip silently.+ * - `connectionReason` — reason string for `checkConnection` responses.+ */+export function resolveCloudProviderConfig(settings, mode) {+ const spec = CLOUD_PROVIDER_SPECS[mode];+ if (!spec) return null;+ const config = settings?.imageGen?.[mode] || {};+ const enabled = config.enabled === true;+ const providerParams = spec.params(config);+ return {+ mode,+ config,+ enabled,+ modelId: spec.modelId(config),+ providerParams,+ jobParams: { mode, ...providerParams },+ disabledError: enabled ? null : new ServerError(+ `${spec.label} is disabled — enable it in Settings → Image Gen first`,+ { status: 400, code: spec.errorCode },+ ),+ disabledReason: `${mode}-disabled`,+ connectionReason: `${spec.label} is disabled in settings`,+ };+}++/**+ * Can the queue-backed surfaces render in `mode` right now? Cloud CLIs need+ * their opt-in toggle; local is always usable (its own pythonPath/model+ * validation happens per call site); external isn't queueable at all.+ *+ * The predicate behind the candidate walk in `resolveMode`+ * (pipeline/visualStageHelpers.js), so the mode ladder no longer grows a+ * pairwise `if` per backend.+ */+export function isModeUsable(settings, mode) {+ if (!QUEUEABLE_IMAGE_MODES.includes(mode)) return false;+ const cloud = resolveCloudProviderConfig(settings, mode);+ return cloud ? cloud.enabled : true;+}++/**+ * First usable mode from an ordered candidate list, falling back to the+ * cloud providers (in `CLOUD_IMAGE_GEN_MODES` order) and finally local.+ */+export function pickUsableMode(settings, candidates = []) {+ const ordered = [...candidates, ...CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE.LOCAL];+ return ordered.find((m) => m && isModeUsable(settings, m)) || IMAGE_GEN_MODE.LOCAL;+}diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.jsnew file mode 100644index 0000000000..f0c664e70b--- /dev/null+++ b/server/services/imageGen/cloudProviderConfig.test.js@@ -0,0 +1,138 @@+import { describe, it, expect } from 'vitest';+import {+ isCloudImageMode,+ isModeUsable,+ pickUsableMode,+ resolveCloudProviderConfig,+} from './cloudProviderConfig.js';+import { CODEX_IMAGEGEN_DEFAULT_MODEL, IMAGE_GEN_MODE } from './modes.js';++const settingsWith = (imageGen) => ({ imageGen });++describe('resolveCloudProviderConfig', () => {+ it('returns null for non-cloud modes', () => {+ expect(resolveCloudProviderConfig(settingsWith({}), IMAGE_GEN_MODE.LOCAL)).toBeNull();+ expect(resolveCloudProviderConfig(settingsWith({}), IMAGE_GEN_MODE.EXTERNAL)).toBeNull();+ expect(resolveCloudProviderConfig(settingsWith({}), undefined)).toBeNull();+ });++ it('bundles codex job params and defaults the model for display + queue metadata', () => {+ const cloud = resolveCloudProviderConfig(+ settingsWith({ codex: { enabled: true, codexPath: '/bin/codex', effort: 'high' } }),+ IMAGE_GEN_MODE.CODEX,+ );+ expect(cloud.enabled).toBe(true);+ expect(cloud.disabledError).toBeNull();+ expect(cloud.modelId).toBe(CODEX_IMAGEGEN_DEFAULT_MODEL);+ expect(cloud.providerParams).toEqual({+ codexPath: '/bin/codex',+ model: CODEX_IMAGEGEN_DEFAULT_MODEL,+ effort: 'high',+ });+ expect(cloud.jobParams).toEqual({ mode: IMAGE_GEN_MODE.CODEX, ...cloud.providerParams });+ });++ it('keeps a saved codex model override', () => {+ const cloud = resolveCloudProviderConfig(+ settingsWith({ codex: { enabled: true, model: 'gpt-5.4' } }),+ IMAGE_GEN_MODE.CODEX,+ );+ expect(cloud.modelId).toBe('gpt-5.4');+ expect(cloud.providerParams.model).toBe('gpt-5.4');+ });++ it('bundles grok job params (no model knob — fixed backend id)', () => {+ const cloud = resolveCloudProviderConfig(+ settingsWith({ grok: { enabled: true, grokPath: '/bin/grok', aspectRatio: '16:9' } }),+ IMAGE_GEN_MODE.GROK,+ );+ expect(cloud.modelId).toBe('grok-imagegen');+ expect(cloud.jobParams).toEqual({+ mode: IMAGE_GEN_MODE.GROK,+ grokPath: '/bin/grok',+ aspectRatio: '16:9',+ });+ });++ it('produces a ready-to-throw ServerError + skip reason when disabled', () => {+ const cloud = resolveCloudProviderConfig(settingsWith({ grok: { enabled: false } }), IMAGE_GEN_MODE.GROK);+ expect(cloud.enabled).toBe(false);+ expect(cloud.disabledReason).toBe('grok-disabled');+ expect(cloud.connectionReason).toMatch(/Grok Imagegen is disabled/);+ expect(cloud.disabledError.status).toBe(400);+ expect(cloud.disabledError.code).toBe('GROK_IMAGEGEN_DISABLED');+ expect(cloud.disabledError.message).toMatch(/Settings → Image Gen/);+ });++ it('treats a missing settings slice as disabled rather than throwing', () => {+ const cloud = resolveCloudProviderConfig({}, IMAGE_GEN_MODE.CODEX);+ expect(cloud.enabled).toBe(false);+ expect(cloud.config).toEqual({});+ expect(cloud.disabledError.code).toBe('CODEX_IMAGEGEN_DISABLED');+ });++ it('only counts a strict `true` toggle as enabled', () => {+ const cloud = resolveCloudProviderConfig(settingsWith({ codex: { enabled: 'yes' } }), IMAGE_GEN_MODE.CODEX);+ expect(cloud.enabled).toBe(false);+ });+});++describe('isCloudImageMode', () => {+ it('is true for the cloud CLIs only', () => {+ expect(isCloudImageMode(IMAGE_GEN_MODE.CODEX)).toBe(true);+ expect(isCloudImageMode(IMAGE_GEN_MODE.GROK)).toBe(true);+ expect(isCloudImageMode(IMAGE_GEN_MODE.LOCAL)).toBe(false);+ expect(isCloudImageMode(IMAGE_GEN_MODE.EXTERNAL)).toBe(false);+ });+});++describe('isModeUsable', () => {+ it('gates cloud modes on their enable toggle', () => {+ const s = settingsWith({ codex: { enabled: true }, grok: { enabled: false } });+ expect(isModeUsable(s, IMAGE_GEN_MODE.CODEX)).toBe(true);+ expect(isModeUsable(s, IMAGE_GEN_MODE.GROK)).toBe(false);+ });++ it('always allows local and never allows the non-queueable external backend', () => {+ expect(isModeUsable(settingsWith({}), IMAGE_GEN_MODE.LOCAL)).toBe(true);+ expect(isModeUsable(settingsWith({}), IMAGE_GEN_MODE.EXTERNAL)).toBe(false);+ expect(isModeUsable(settingsWith({}), 'nonsense')).toBe(false);+ });+});++describe('pickUsableMode', () => {+ const bothOff = settingsWith({ codex: { enabled: false }, grok: { enabled: false } });++ it('honors the first usable candidate', () => {+ const s = settingsWith({ codex: { enabled: true }, grok: { enabled: true } });+ expect(pickUsableMode(s, [IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.CODEX])).toBe(IMAGE_GEN_MODE.GROK);+ });++ it('falls through a candidate whose provider is disabled', () => {+ const s = settingsWith({ codex: { enabled: true }, grok: { enabled: false } });+ expect(pickUsableMode(s, [IMAGE_GEN_MODE.GROK, IMAGE_GEN_MODE.CODEX])).toBe(IMAGE_GEN_MODE.CODEX);+ });++ it('skips undefined / unsupported candidates', () => {+ const s = settingsWith({ codex: { enabled: true } });+ expect(pickUsableMode(s, [undefined, IMAGE_GEN_MODE.EXTERNAL])).toBe(IMAGE_GEN_MODE.CODEX);+ });++ it('auto-defaults to an enabled cloud backend, codex first', () => {+ expect(pickUsableMode(settingsWith({ grok: { enabled: true } }), [])).toBe(IMAGE_GEN_MODE.GROK);+ expect(pickUsableMode(+ settingsWith({ codex: { enabled: true }, grok: { enabled: true } }),+ [],+ )).toBe(IMAGE_GEN_MODE.CODEX);+ });++ it('falls back to local when nothing else is usable', () => {+ expect(pickUsableMode(bothOff, [IMAGE_GEN_MODE.EXTERNAL])).toBe(IMAGE_GEN_MODE.LOCAL);+ expect(pickUsableMode(bothOff)).toBe(IMAGE_GEN_MODE.LOCAL);+ });++ it('honors an explicit local candidate over an enabled cloud backend', () => {+ const s = settingsWith({ codex: { enabled: true } });+ expect(pickUsableMode(s, [IMAGE_GEN_MODE.LOCAL])).toBe(IMAGE_GEN_MODE.LOCAL);+ });+});diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 6515ecec7d..5f0a4304a8 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -34,6 +34,7 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from 'import { killWithEscalation } from '../../lib/killWithEscalation.js';import { buildCodexStartupArgs, buildEffortArgs, CODEX_EFFORT_LEVELS } from '../../lib/providerModels.js';import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, describeFidelity } from './modes.js';+import { buildNoImageReason } from './noImageReason.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@@ -240,28 +241,24 @@ export async function generateImage({// into the most useful error we can — surfacing the model's own words (#imagegen// declines, content refusals, "generated" claims with no file) instead of a// fixed guess. The legacy account/enablement hint is kept as a fallback when-// codex said nothing usable.-// eslint-disable-next-line no-control-regex-const ANSI_RE = /\u001b\[[0-9;]*m/g;+// codex said nothing usable. The line walk itself lives in the shared+// `buildNoImageReason` so the codex and grok narrations cannot drift.const CODEX_NO_IMAGE_HINT ='Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.';-export function noImageReason(stdoutTail = '') {- const clean = String(stdoutTail).replace(ANSI_RE, '').trim();- // Keep the model's last few non-empty narration lines, dropping codex's own- // structural labels (`codex`, `user`, `tokens used`, dashed rules).- const lines = clean.split('\n')- .map((l) => l.trim())- .filter((l) => l && !/^(codex|user|-{2,})$/i.test(l) && !/^tokens used\b/i.test(l) && !/^[\d,]+$/.test(l));- const said = lines.slice(-4).join(' ').slice(-600);- if (!said) return CODEX_NO_IMAGE_HINT;- // Codex claims success but no file landed → the image tool wasn't actually- // run (image-gen unavailable / rate-limited on the account), even though the- // turn narrated a generation. Call that out specifically.- if (/\b(generated|created|here(?:'|’)s|i(?:'|’)ve (?:made|generated))\b/i.test(said)) {- return `Codex reported success but wrote no image file — the built-in image tool likely didn't run (image generation may be unavailable or rate-limited on your account, even though the feature is enabled). Codex said: "${said}"`;- }- return `Codex did not produce an image. Codex said: "${said}"`;-}+export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail, {+ hint: CODEX_NO_IMAGE_HINT,+ // Codex's own structural labels, on top of the shared dashed-rule /+ // bare-token-count filter.+ dropLine: (l) => /^(codex|user)$/i.test(l) || /^tokens used\b/i.test(l),+ describe: (said) => (+ // Codex claims success but no file landed → the image tool wasn't actually+ // run (image-gen unavailable / rate-limited on the account), even though the+ // turn narrated a generation. Call that out specifically.+ /\b(generated|created|here(?:'|’)s|i(?:'|’)ve (?:made|generated))\b/i.test(said)+ ? `Codex reported success but wrote no image file — the built-in image tool likely didn't run (image generation may be unavailable or rate-limited on your account, even though the feature is enabled). Codex said: "${said}"`+ : `Codex did not produce an image. Codex said: "${said}"`+ ),+});async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false } = {}) {const proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex e5e0571158..e3617f980a 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -41,7 +41,7 @@ import { autoCleanGeneratedImage } from '../../lib/imageClean.js';import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';import { killWithEscalation } from '../../lib/killWithEscalation.js';-import { stripAnsi } from '../../lib/ansiStrip.js';+import { buildNoImageReason } from './noImageReason.js';import sharp from 'sharp';import { bufferedSpawn, killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';@@ -163,15 +163,10 @@ export async function checkConnection({ grokPath } = {}) {// own words (content declines, tool-failure notes) instead of a fixed guess.const GROK_NO_IMAGE_HINT ='Grok returned no image — the image_gen tool may be unavailable on your Grok plan, or the model declined. Check Settings → Image Gen → Enable Grok Imagegen.';-export function noImageReason(stdoutTail = '') {- const clean = stripAnsi(String(stdoutTail)).trim();- const lines = clean.split('\n')- .map((l) => l.trim())- .filter((l) => l && !/^-{2,}$/.test(l) && !/^[\d,]+$/.test(l));- const said = lines.slice(-4).join(' ').slice(-600);- if (!said) return GROK_NO_IMAGE_HINT;- return `Grok did not produce an image at the directed path. Grok said: "${said}"`;-}+export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail, {+ hint: GROK_NO_IMAGE_HINT,+ describe: (said) => `Grok did not produce an image at the directed path. Grok said: "${said}"`,+});// Build the single-turn agent prompt that triggers image_gen (or image_edit// for i2i) and directs the output to a PortOS-chosen path. Grok is a generaldiff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 390014d502..7be0e22956 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -13,13 +13,17 @@*/import { getSettings } from '../settings.js';-import { ServerError } from '../../lib/errorHandler.js';import { resolveCleanersFromConfig } from '../../lib/imageClean.js';import * as external from './external.js';import * as local from './local.js';import * as codex from './codex.js';import * as grok from './grok.js';import { IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES } from './modes.js';+import { resolveCloudProviderConfig } from './cloudProviderConfig.js';++// Cloud-CLI provider modules keyed by mode, so the shared gate in+// checkConnection/generateImage dispatches without a per-provider branch.+const CLOUD_PROVIDERS = { [IMAGE_GEN_MODE.CODEX]: codex, [IMAGE_GEN_MODE.GROK]: grok };// 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@@ -32,8 +36,6 @@ const DEFAULT_MODE = IMAGE_GEN_MODE.EXTERNAL;const cfg = (s) => s?.imageGen || {};const sdapiUrl = (s) => cfg(s).external?.sdapiUrl || cfg(s).sdapiUrl || null;const pythonPath = (s) => cfg(s).local?.pythonPath || null;-const codexCfg = (s) => cfg(s).codex || {};-const grokCfg = (s) => cfg(s).grok || {};// Resolve the cleaner flags from body overrides + saved per-mode settings.// Body fields win when explicit (per-render checkbox); otherwise inherit@@ -61,15 +63,10 @@ export async function checkConnection({ mode: modeOverride } = {}) {if (!py) return { connected: false, mode, reason: 'Python path not configured' };return { connected: true, mode, model: 'mflux/local', pythonPath: py };}- 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 });- }- if (mode === IMAGE_GEN_MODE.GROK) {- const g = grokCfg(s);- if (!g.enabled) return { connected: false, mode, reason: 'Grok Imagegen is disabled in settings' };- return grok.checkConnection({ grokPath: g.grokPath });+ const cloudCheck = resolveCloudProviderConfig(s, mode);+ if (cloudCheck) {+ if (!cloudCheck.enabled) return { connected: false, mode, reason: cloudCheck.connectionReason };+ return CLOUD_PROVIDERS[mode].checkConnection(cloudCheck.providerParams);}const status = await external.checkConnection(sdapiUrl(s));return { ...status, mode };@@ -105,29 +102,14 @@ export async function generateImage(params) {delete normalized.cleanC2PA;delete normalized.denoise;delete normalized.autoClean; // legacy body field — accept-and-ignore- if (mode === IMAGE_GEN_MODE.CODEX) {- const c = codexCfg(s);- if (!c.enabled) {- throw new ServerError(- 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },- );- }- // model/effort default to the cheap gpt-5.6-luna / low path inside- // codex.generateImage when unset here; a saved override wins.- return codex.generateImage({ codexPath: c.codexPath, model: c.model, effort: c.effort, cleanC2PA, denoise, ...normalized });- }- if (mode === IMAGE_GEN_MODE.GROK) {- const g = grokCfg(s);- if (!g.enabled) {- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }- // No model/effort knobs — grok's image tools run on xAI's fixed image- // backend; only the binary path and a default aspect ratio are saved.- return grok.generateImage({ grokPath: g.grokPath, aspectRatio: g.aspectRatio, cleanC2PA, denoise, ...normalized });+ // Cloud CLIs (codex, grok) share one gate + param bundle — the per-provider+ // knobs (codexPath/model/effort vs grokPath/aspectRatio) come from the+ // resolver's spec, so a saved override always wins over the provider's own+ // internal defaults.+ const cloud = resolveCloudProviderConfig(s, mode);+ if (cloud) {+ if (!cloud.enabled) throw cloud.disabledError;+ return CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized });}if (mode === IMAGE_GEN_MODE.LOCAL) {return local.generateImage({ pythonPath: pythonPath(s), cleanC2PA, denoise, ...normalized });diff --git a/server/services/imageGen/noImageReason.js b/server/services/imageGen/noImageReason.jsnew file mode 100644index 0000000000..62239500c3--- /dev/null+++ b/server/services/imageGen/noImageReason.js@@ -0,0 +1,39 @@+/**+ * Image Gen — shared "the CLI exited without writing an image" narrator.+ *+ * Both cloud-CLI providers finish the same way when no PNG lands: they hold a+ * rolling tail of the child's stdout narration and have to turn it into the+ * most useful error they can — the model's own words (content declines,+ * tool-failure notes) beat a fixed guess, with a provider-specific enablement+ * hint as the fallback when it said nothing usable.+ *+ * `buildNoImageReason` owns that pipeline (strip ANSI → drop structural noise →+ * keep the last few narration lines → cap length) so the two error narrations+ * can't drift; each provider supplies only what actually differs: its own+ * structural line filter, its fallback hint, and how it phrases the result.+ */++import { stripAnsi } from '../../lib/ansiStrip.js';++// Structural noise every CLI emits: dashed rules and bare token counts.+const isStructuralNoise = (line) => /^-{2,}$/.test(line) || /^[\d,]+$/.test(line);++// How many trailing narration lines to quote, and the cap on the quote.+const NARRATION_LINES = 4;+const NARRATION_MAX_CHARS = 600;++/**+ * @param {string} stdoutTail rolling tail of the child's stdout+ * @param {object} opts+ * @param {string} opts.hint fallback message when nothing usable was said+ * @param {(line: string) => boolean} [opts.dropLine] extra per-provider filter+ * @param {(said: string) => string} opts.describe phrase the quoted output+ */+export function buildNoImageReason(stdoutTail = '', { hint, dropLine, describe }) {+ const clean = stripAnsi(String(stdoutTail)).trim();+ const lines = clean.split('\n')+ .map((l) => l.trim())+ .filter((l) => l && !isStructuralNoise(l) && !(dropLine?.(l)));+ const said = lines.slice(-NARRATION_LINES).join(' ').slice(-NARRATION_MAX_CHARS);+ return said ? describe(said) : hint;+}diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.jsindex 7da66a455b..6427dea865 100644--- a/server/services/loraDatasetGenerate.js+++ b/server/services/loraDatasetGenerate.js@@ -36,7 +36,8 @@ import {} from './universeCharacterSheet.js';import { getImageModels } from '../lib/mediaModels.js';import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL } from './imageGen/modes.js';+import { IMAGE_GEN_MODE } from './imageGen/modes.js';+import { resolveCloudProviderConfig } from './imageGen/cloudProviderConfig.js';import {datasetImagePath,datasetImagesDir,@@ -344,26 +345,10 @@ async function resolveRenderParams({ modelId: modelOverride = null } = {}) {cleanC2PA: true,denoise: false,};- if (activeMode === IMAGE_GEN_MODE.CODEX) {- const c = settings.imageGen?.codex || {};- if (!c.enabled) {- throw new ServerError(- 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },- );- }- return { base: { ...base, codexPath: c.codexPath, model: c.model, effort: c.effort }, activeMode, modelId: c.model || CODEX_IMAGEGEN_DEFAULT_MODEL };- }- if (activeMode === IMAGE_GEN_MODE.GROK) {- const g = settings.imageGen?.grok || {};- if (!g.enabled) {- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }- // Grok's image tools run on xAI's fixed image backend — no model knob.- return { base: { ...base, grokPath: g.grokPath, aspectRatio: g.aspectRatio }, activeMode, modelId: 'grok-imagegen' };+ const cloud = resolveCloudProviderConfig(settings, activeMode);+ if (cloud) {+ if (!cloud.enabled) throw cloud.disabledError;+ return { base: { ...base, ...cloud.providerParams }, activeMode, modelId: cloud.modelId };}if (activeMode === IMAGE_GEN_MODE.LOCAL) {const allModels = getImageModels();diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.jsindex 4e8fcd55db..ea4f24cef8 100644--- a/server/services/pipeline/visualStageHelpers.js+++ b/server/services/pipeline/visualStageHelpers.js@@ -21,7 +21,8 @@ import { getImageModels } from '../../lib/mediaModels.js';import { loraCompatKey } from '../../lib/runners.js';import { resolveCharacterLoras } from '../characterLoraResolver.js';import { pickCanon } from './seriesCanon.js';-import { IMAGE_GEN_MODE, resolveQueueImageMode } from '../imageGen/modes.js';+import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { pickUsableMode, resolveCloudProviderConfig } from '../imageGen/cloudProviderConfig.js';import { resolveImageCleaners } from '../imageGen/index.js';const joinStyleParts = (...parts) =>@@ -52,12 +53,24 @@ const applyWorldStyle = (prompt, world, series = null) => {return composeStyledPrompt(prompt, '', { prompt: stylePrompt, negativePrompt: '' }).prompt;};-// Resolution order for the image-gen mode on a pipeline visual stage:-// per-request override (enable-gated) → saved dispatcher default → codex →-// grok → local. The ladder itself is the shared `resolveQueueImageMode`-// (imageGen/modes.js) — hoisted in #2896 so sprite renders use the same-// policy; this wrapper just adapts the pipeline's `options` bag.-const resolveMode = (options, settings) => resolveQueueImageMode(options.mode, settings);+// Resolution order for the image-gen mode on a pipeline visual stage — a+// candidate walk (first usable wins) rather than a pairwise ladder, so a new+// cloud backend costs zero edits here:+// 1. Per-request override (`options.mode`) — set by the stage's persisted+// `genConfig` or an explicit UI selection. A cloud mode is only honored+// when its `imageGen.<mode>.enabled` toggle is on; a stale 'codex'+// override from before the toggle was turned off falls through.+// 2. Saved dispatcher default (`settings.imageGen.mode`) — same usability+// gate, and non-queueable modes (external SD-API, which this surface+// doesn't proxy) never qualify.+// 3. Auto-default — prefer an enabled cloud backend, since cloud image gen+// produces print-quality comic pages out of the box. Otherwise fall back+// to local diffusion (flux-1) the way the original default behaved.+// `pickUsableMode` appends the cloud-then-local tail, so this only lists the+// two explicit candidates. (Sprite renders use the equivalent+// `resolveQueueImageMode` ladder in imageGen/modes.js — #2896 hoisted that+// one first; this is the wider param-assembly consolidation from #2881.)+const resolveMode = (options, settings) => pickUsableMode(settings, [options.mode, settings?.imageGen?.mode]);/*** Resolve trained character LoRAs for a pipeline render. Local mode only —@@ -238,11 +251,10 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin// the saved settings.imageGen[mode].{cleanC2PA,denoise} would have no// effect on storyboard, comic-panel, or cover renders.const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- const params = mode === IMAGE_GEN_MODE.CODEX- ? { mode: IMAGE_GEN_MODE.CODEX, codexPath: settings.imageGen?.codex?.codexPath, model: settings.imageGen?.codex?.model, effort: settings.imageGen?.codex?.effort, cleanC2PA, denoise, ...baseParams }- : mode === IMAGE_GEN_MODE.GROK- ? { mode: IMAGE_GEN_MODE.GROK, grokPath: settings.imageGen?.grok?.grokPath, aspectRatio: settings.imageGen?.grok?.aspectRatio, cleanC2PA, denoise, ...baseParams }- : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };+ const cloud = resolveCloudProviderConfig(settings, mode);+ const params = cloud+ ? { ...cloud.jobParams, cleanC2PA, denoise, ...baseParams }+ : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, cleanC2PA, denoise, ...baseParams };const { jobId } = enqueueJob({ kind: 'image', params, owner });console.log(`${logLine} mode=${mode} jobId=${jobId.slice(0, 8)}`);return jobId;diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.jsindex c278e18794..cae3332d72 100644--- a/server/services/universeBuilderRender.js+++ b/server/services/universeBuilderRender.js@@ -19,6 +19,7 @@ import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import { usesDiffusersRunner } from '../lib/runners.js';import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from './imageGen/modes.js';+import { resolveCloudProviderConfig } from './imageGen/cloudProviderConfig.js';import { resolveImageCleaners } from './imageGen/index.js';import { getStylePresetById } from '../lib/writersRoomStylePresets.js';import { ServerError } from '../lib/errorHandler.js';@@ -72,18 +73,8 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {// Mirror the upfront validation /api/image-gen/generate does so a doomed// batch fails before any jobs land in the queue.- if (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 === IMAGE_GEN_MODE.GROK && !settings.imageGen?.grok?.enabled) {- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }+ const cloud = resolveCloudProviderConfig(settings, mode);+ if (cloud && !cloud.enabled) throw cloud.disabledError;if (mode === IMAGE_GEN_MODE.LOCAL) {const py = settings.imageGen?.local?.pythonPath || null;const allModels = getImageModels();@@ -186,17 +177,10 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {// settings apply to Universe Builder batch renders the same way they// do for /api/image-gen/generate and pipeline renders.const { cleanC2PA, denoise } = resolveImageCleaners(undefined, settings, mode);- if (mode === IMAGE_GEN_MODE.CODEX) {- const c = settings.imageGen?.codex || {};- queued = enqueueJob({- kind: 'image',- params: { mode: IMAGE_GEN_MODE.CODEX, codexPath: c.codexPath, model: c.model, effort: c.effort, cleanC2PA, denoise, ...params },- });- } else if (mode === IMAGE_GEN_MODE.GROK) {- const g = settings.imageGen?.grok || {};+ if (cloud) {queued = enqueueJob({kind: 'image',- params: { mode: IMAGE_GEN_MODE.GROK, grokPath: g.grokPath, aspectRatio: g.aspectRatio, cleanC2PA, denoise, ...params },+ params: { ...cloud.jobParams, cleanC2PA, denoise, ...params },});} else {// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.jsindex c7fc940360..9fba2ca205 100644--- a/server/services/universeCharacterSheet.js+++ b/server/services/universeCharacterSheet.js@@ -23,7 +23,8 @@ import { buildStyleClause, purgeReferenceSheetFromAllUniverses } from './universimport { getImageModels } from '../lib/mediaModels.js';import { enqueueJob, mediaJobEvents } from './mediaJobQueue/index.js';import { buildUniverseRunTag } from './universeRunTag.js';-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL } from './imageGen/modes.js';+import { IMAGE_GEN_MODE } from './imageGen/modes.js';+import { resolveCloudProviderConfig } from './imageGen/cloudProviderConfig.js';import {flattenStats, flattenPalette, flattenWardrobes, flattenProps, flattenNamedList,} from '../lib/canonPrompt.js';@@ -441,26 +442,11 @@ export async function renderCharacterReferenceSheet(universeId, entryId, optionslet modelId = null;let params;- if (activeMode === IMAGE_GEN_MODE.CODEX) {- const c = settings.imageGen?.codex || {};- if (!c.enabled) {- throw new ServerError(- 'Codex Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'CODEX_IMAGEGEN_DISABLED' },- );- }- modelId = c.model || CODEX_IMAGEGEN_DEFAULT_MODEL;- params = { ...baseParams, codexPath: c.codexPath, model: c.model, effort: c.effort };- } else if (activeMode === IMAGE_GEN_MODE.GROK) {- const g = settings.imageGen?.grok || {};- if (!g.enabled) {- throw new ServerError(- 'Grok Imagegen is disabled — enable it in Settings → Image Gen first',- { status: 400, code: 'GROK_IMAGEGEN_DISABLED' },- );- }- modelId = 'grok-imagegen';- params = { ...baseParams, grokPath: g.grokPath, aspectRatio: g.aspectRatio };+ const cloud = resolveCloudProviderConfig(settings, activeMode);+ if (cloud) {+ if (!cloud.enabled) throw cloud.disabledError;+ modelId = cloud.modelId;+ params = { ...baseParams, ...cloud.providerParams };} else if (activeMode === IMAGE_GEN_MODE.LOCAL) {const allModels = getImageModels();modelId = resolveSheetModelId({ override: options.modelId, settings, allModels });