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([issue-2859]): apply review-pass cleanups to the grok backend
[._.]/ Adam Eivy7d6c9fdf8018
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsxindex cb1e7d54bd..87924d4419 100644--- a/client/src/components/imageGen/ImageGenControls.jsx+++ b/client/src/components/imageGen/ImageGenControls.jsx@@ -12,7 +12,7 @@ import { Dice5 } from 'lucide-react';import { filterResolutions, MAX_IMAGE_EDGE, MAX_IMAGE_PIXELS } from '../../lib/imageGenResolutions';import { randomSeed } from '../../lib/genUtils';import { RUNNER_FAMILIES } from '../../lib/runnerFamilies';-import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';+import { IMAGE_GEN_MODE, isCloudCliMode } from '../../lib/imageGenBackends';import ModelDownloadBadge, { deriveSizeEstimate } from '../media/ModelDownloadBadge';import ResolutionField from '../media/ResolutionField';import { FormField } from '../ui/FormField';@@ -54,7 +54,7 @@ export default function ImageGenControls({const isLocal = mode === IMAGE_GEN_MODE.LOCAL;// Cloud-CLI backends (codex, grok) pick model/steps/seed internally — only// resolution + style fields apply, so the local-only knobs are hidden.- const isCodex = mode === IMAGE_GEN_MODE.CODEX || mode === IMAGE_GEN_MODE.GROK;+ const isCloudCli = isCloudCliMode(mode);const currentModel = models.find((m) => m.id === modelId);const isFlux2 = currentModel?.runner === RUNNER_FAMILIES.FLUX2;@@ -112,7 +112,7 @@ export default function ImageGenControls({{/* Codex's image_gen tool ignores seed/steps/guidance — only resolutionis honored, so the rest of the knobs are hidden in that mode. */}- {!isCodex && showSeed && (+ {!isCloudCli && showSeed && (<div><label htmlFor="image-gen-seed" className="block text-xs font-medium text-gray-400 mb-1">Seed</label><div className="flex items-center gap-1">@@ -138,7 +138,7 @@ export default function ImageGenControls({</div>)}- {!isCodex && (+ {!isCloudCli && (<FormFieldlabel={<>Steps {currentModel?.steps && `(default: ${currentModel.steps})`}</>}labelClassName="block text-xs font-medium text-gray-400 mb-1"@@ -158,7 +158,7 @@ export default function ImageGenControls({have classifier-free guidance baked in — the diffusers runner ignoresany guidance scale we pass and prints a warning. Hide the input forthose models so the user doesn't waste a knob-turn on a no-op. */}- {!isCodex && isLocal && !currentModel?.cfgDisabled && (+ {!isCloudCli && isLocal && !currentModel?.cfgDisabled && (<FormFieldlabel={<>Guidance {currentModel?.guidance != null && `(default: ${currentModel.guidance})`}</>}labelClassName="block text-xs font-medium text-gray-400 mb-1"@@ -174,7 +174,7 @@ export default function ImageGenControls({</FormField>)}- {!isCodex && isLocal && showQuantize && !isFlux2 && (+ {!isCloudCli && isLocal && showQuantize && !isFlux2 && (<FormField label="Quantize (bits)" labelClassName="block text-xs font-medium text-gray-400 mb-1"><selectvalue={quantize ?? '8'}@@ -187,7 +187,7 @@ export default function ImageGenControls({</FormField>)}- {!isCodex && !isLocal && onCfgScaleChange && (+ {!isCloudCli && !isLocal && onCfgScaleChange && (<FormFieldlabel={<>CFG Scale ({cfgScale})</>}labelClassName="block text-xs font-medium text-gray-400 mb-1"diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex a9f6a2d217..9b2d713158 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -5,7 +5,7 @@ import ConfirmButtonPair from '../ui/ConfirmButtonPair';import { FormField } from '../ui/FormField';import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';import { listLoraTrainingCheckpoints } from '../../services/apiLoraTraining.js';-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT } from '../../lib/imageGenBackends';+import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT } from '../../lib/imageGenBackends';import { CODEX_EFFORT_LEVELS } from '../../utils/providers';import { lossSparklineGeometry } from '../../lib/lossSparkline';import { useAutoRefetch } from '../../hooks/useAutoRefetch';@@ -320,8 +320,8 @@ 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 === IMAGE_GEN_MODE.CODEX || job.params?.mode === IMAGE_GEN_MODE.GROK);- const canRunNow = isQueuedCodex && typeof onRunNow === 'function';+ const isQueuedCloud = job.status === 'queued' && job.kind === 'image' && isCloudCliMode(job.params?.mode);+ const canRunNow = isQueuedCloud && typeof onRunNow === 'function';// Number.isFinite (not typeof === 'number') so a NaN from a hand-edited// media-jobs.json can't render as `NaN%` / `width: NaN%`.const progressPct = Number.isFinite(job.progress)diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsxindex 3b0f997199..89639d9bc1 100644--- a/client/src/components/settings/ImageGenTab.jsx+++ b/client/src/components/settings/ImageGenTab.jsx@@ -22,7 +22,7 @@ import {registerTool, updateTool, getToolsList,getHfTokenStatus, saveHfToken, clearHfToken,} from '../../services/api';-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS } from '../../lib/imageGenBackends';+import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, GROK_ASPECT_RATIOS } from '../../lib/imageGenBackends';import { resolveCleanersFromConfig } from '../../lib/imageCleaners';import { useMediaJobSse } from '../../hooks/useMediaJobSse';import { CODEX_EFFORT_LEVELS } from '../../utils/providers';@@ -427,7 +427,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 === IMAGE_GEN_MODE.LOCAL || result?.mode === IMAGE_GEN_MODE.CODEX || result?.mode === IMAGE_GEN_MODE.GROK);+ const isAsync = (result?.mode === IMAGE_GEN_MODE.LOCAL || isCloudCliMode(result?.mode));if (isAsync && result?.generationId) {const jobResult = await attachRenderSse(result.generationId, {onError: (msg) => new Error(msg.error || 'Generation failed'),diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.jsindex 2394e5eacc..f78688e370 100644--- a/client/src/lib/imageGenBackends.js+++ b/client/src/lib/imageGenBackends.js@@ -21,6 +21,14 @@ const META = {[IMAGE_GEN_MODE.EXTERNAL]: { label: 'External', icon: Cloud },};+// Client mirror of the server's CLOUD_IMAGE_GEN_MODES (imageGen/modes.js) —+// cloud-CLI backends (codex, grok) that pick model/steps/seed internally,+// run through the media queue's parallel cloud lane, and need a prompt for+// text-to-image. Use `isCloudCliMode` instead of hand-rolled+// `mode === CODEX || mode === GROK` disjunctions.+export const CLOUD_IMAGE_GEN_MODES = Object.freeze([IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);+export const isCloudCliMode = (mode) => CLOUD_IMAGE_GEN_MODES.includes(mode);+// Backends that support image-to-image (init image / reference editing). The// external SD-API path does not. Single source of truth for i2i gating in the UI.export const I2I_CAPABLE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex a701f581d5..30755969fa 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -37,7 +37,7 @@ import {AlertTriangle, X, Film,} from 'lucide-react';import { composeStyledPrompt } from '../lib/composeStyledPrompt';-import { deriveAvailableBackends, IMAGE_GEN_MODE, isI2iCapableMode, pickI2iMode } from '../lib/imageGenBackends';+import { isCloudCliMode, deriveAvailableBackends, IMAGE_GEN_MODE, isI2iCapableMode, pickI2iMode } from '../lib/imageGenBackends';import { clampImageDimensions, clampImageEdge } from '../lib/imageGenResolutions';import { DEFAULT_NEGATIVE_PROMPT } from '../lib/imageGenDefaults';import { resolveCleanersFromConfig } from '../lib/imageCleaners';@@ -223,9 +223,9 @@ export default function ImageGen() {// so the form doesn't flicker between defaults.const effectiveMode = selectedMode || status?.mode || IMAGE_GEN_MODE.EXTERNAL;const isLocalMode = effectiveMode === IMAGE_GEN_MODE.LOCAL;- const isCodexMode = effectiveMode === IMAGE_GEN_MODE.CODEX;const isGrokMode = effectiveMode === IMAGE_GEN_MODE.GROK;- const isAsyncMode = isLocalMode || isCodexMode || isGrokMode;+ const isCloudMode = isCloudCliMode(effectiveMode);+ const isAsyncMode = isLocalMode || isCloudMode;// Whether the active backend supports image-to-image (init image). Distinct// concept from isAsyncMode (queued vs sync) even though they coincide today.const i2iCapable = isI2iCapableMode(effectiveMode);@@ -611,7 +611,7 @@ export default function ImageGen() {// rule (codex.js requires a prompt only when there's no init image) so the user// sees a disabled button + hint instead of a failed job toast. Local runs// unconditionally and external (A1111) accepts an empty prompt, so neither gates.- const codexNeedsPrompt = (isCodexMode || isGrokMode) && initImage.source == null && !prompt.trim();+ const cloudNeedsPrompt = isCloudMode && initImage.source == null && !prompt.trim();// mflux is the default runner for entries with no explicit `runner` field.// LoraPicker filters compatible weights itself; we pass the family (for the// "install one matching X" copy) and the fine-grained compat key (which@@ -723,7 +723,7 @@ export default function ImageGen() {// payload hits imageEdgeSchema.const w = clampImageEdge(width);const h = clampImageEdge(height);- const payload = (isCodexMode || isGrokMode) ? {+ const payload = isCloudMode ? {prompt: composed.prompt,negativePrompt: composed.negativePrompt || undefined,width: w, height: h,@@ -786,7 +786,7 @@ export default function ImageGen() {// The gallery / sidecar would otherwise show steps=20,// guidance=3.5 (Flux 1 Dev defaults) on every codex image,// misleading the user about what actually produced it.- const localOnlyMeta = (isCodexMode || isGrokMode) ? {} : {+ const localOnlyMeta = isCloudMode ? {} : {steps: payload.steps ?? currentModel?.steps,guidance: payload.guidance ?? currentModel?.guidance,};@@ -840,7 +840,7 @@ export default function ImageGen() {// submit button blocks clicks, but an Enter keypress in a number input still// fires onSubmit — gate here too so an edit-only model without a source image// (or codex text-to-image with no prompt) hits the inline hint, not a 400 toast.- if (editImageMissing || codexNeedsPrompt) return;+ if (editImageMissing || cloudNeedsPrompt) return;const batchN = isAsyncMode ? Math.max(1, batchCount) : 1;if (generating) return queueAdditional(batchN);// Snap the custom-dimension state to the server's per-edge bounds up front@@ -1233,8 +1233,8 @@ export default function ImageGen() {<div className="flex items-center gap-2 pt-1 flex-wrap"><buttontype="submit"- disabled={notConnected || editImageMissing || codexNeedsPrompt}- title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : codexNeedsPrompt ? `${isGrokMode ? 'Grok' : 'Codex'} text-to-image needs a prompt — add one, or attach a source image to edit` : undefined}+ disabled={notConnected || editImageMissing || cloudNeedsPrompt}+ title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : cloudNeedsPrompt ? `${isGrokMode ? 'Grok' : 'Codex'} text-to-image needs a prompt — add one, or attach a source image to edit` : undefined}className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium rounded-lg min-h-[40px]"><Sparkles className="w-4 h-4" /> {generating ? 'Queue' : 'Generate'}@@ -1243,7 +1243,7 @@ export default function ImageGen() {{editImageMissing && (<span className="text-xs text-port-warning">Upload a source image to use this edit model</span>)}- {codexNeedsPrompt && (+ {cloudNeedsPrompt && (<span className="text-xs text-port-warning">Codex needs a prompt, or attach a source image to edit</span>)}{isAsyncMode && (diff --git a/server/lib/imageClean.js b/server/lib/imageClean.jsindex 2f07573509..7cd798b283 100644--- a/server/lib/imageClean.js+++ b/server/lib/imageClean.js@@ -32,9 +32,17 @@ import { tryReadFile, safeJSONParse, atomicWrite, detectImageFormat } from './fi* Mirrored verbatim in `client/src/lib/imageCleaners.js` — keep the two* copies in sync; the client tree can't import from server/lib.*/+// Backends that stamp a C2PA `caBX` chunk in current production. Grok+// (xAI Aurora) is deliberately NOT listed: unconfirmed as a C2PA emitter, so+// its renders skip the standalone strip walk even when the toggle is on —+// add it here (and flip its default) if/when confirmed. This set feeds both+// the per-mode cleanC2PA default below and the standalone-strip short-circuit+// in autoCleanGeneratedImage.+const C2PA_EMITTING_MODES = ['codex', 'external'];+export function resolveCleanersFromConfig(modeCfg, mode) {const cfg = modeCfg || {};- const cleanC2PADefault = mode === 'codex' || mode === 'external';+ const cleanC2PADefault = C2PA_EMITTING_MODES.includes(mode);return {cleanC2PA: typeof cfg.cleanC2PA === 'boolean' ? cfg.cleanC2PA : cleanC2PADefault,denoise: typeof cfg.denoise === 'boolean' ? cfg.denoise : false,@@ -468,16 +476,18 @@ export async function cleanImageBuffer(buffer, options = {}) {//// When `denoise` is on, C2PA is stripped implicitly by sharp's re-encode// regardless of `cleanC2PA` — both flags off short-circuits to a no-op.-// `mode` is one of 'codex' | 'local' | 'external'; only used in log lines.+// `mode` is one of 'codex' | 'grok' | 'local' | 'external'; used in log lines+// and the C2PA short-circuit below.// Logs and swallows errors — a clean failure must never fail the underlying// generation (the un-cleaned PNG stays on disk).export async function autoCleanGeneratedImage({ cleanC2PA = false, denoise = false, pngPath, sidecarPath, mode = 'unknown' }) {if (!cleanC2PA && !denoise) return { cleaned: false };- // Backends that can't produce a `caBX` chunk (local FLUX, external SD-API)- // shouldn't pay readFile + walk on every render when the user enabled- // cleanC2PA defensively. Only codex (gpt-image-2) emits the chunk in- // current production. Denoise still has to run regardless because it's a- // pixel pass, not a metadata pass.+ // Backends that can't produce a `caBX` chunk shouldn't pay readFile + walk+ // on every render when the user enabled cleanC2PA defensively. Only codex+ // (gpt-image-2) emits the chunk in current production — external is IN+ // C2PA_EMITTING_MODES for its default but its proxied output has never+ // carried the chunk here, so the walk-skip keys on codex alone. Denoise+ // still runs regardless because it's a pixel pass, not a metadata pass.if (!denoise && cleanC2PA && mode !== 'codex') return { cleaned: false };// Sidecar read has no data dependency on the PNG read/write — kick it offdiff --git a/server/routes/pipeline/covers.js b/server/routes/pipeline/covers.jsindex 0b04166ab9..2f66ab811a 100644--- a/server/routes/pipeline/covers.js+++ b/server/routes/pipeline/covers.js@@ -23,7 +23,7 @@ import {renderVolumeBackCover,} from '../../services/pipeline/visualStages.js';import { COMIC_PAGE_VARIANTS } from '../../services/pipeline/owners.js';-import { IMAGE_GEN_MODE } from '../../services/imageGen/modes.js';+import { QUEUEABLE_IMAGE_MODES } from '../../services/imageGen/modes.js';import { buildComicPdf, PAGE_SIZES, DEFAULT_PAGE_SIZE } from '../../services/pipeline/comicPdf.js';import { buildVolumePdf } from '../../services/pipeline/volumePdf.js';import { mapServiceError } from './shared.js';@@ -47,7 +47,7 @@ const makeCoverRenderSchema = (scriptField) => z.object({[scriptField]: z.string().max(8000).optional(),negativePrompt: z.string().trim().max(2000).optional(),extraStyle: z.string().trim().max(2000).optional(),- mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),modelId: z.string().trim().max(64).optional(),width: imageEdgeSchema,height: imageEdgeSchema,diff --git a/server/routes/pipeline/issues.js b/server/routes/pipeline/issues.jsindex bcd2318a96..d4582f063b 100644--- a/server/routes/pipeline/issues.js+++ b/server/routes/pipeline/issues.js@@ -39,7 +39,7 @@ import { getSeriesCanon } from '../../services/pipeline/seriesCanon.js';import { startEpisodeVideoForIssue } from '../../services/pipeline/episodeVideo.js';import { COMIC_PAGE_VARIANTS } from '../../services/pipeline/owners.js';import { ASPECT_RATIOS, QUALITIES } from '../../lib/creativeDirectorPresets.js';-import { IMAGE_GEN_MODE } from '../../services/imageGen/modes.js';+import { QUEUEABLE_IMAGE_MODES } from '../../services/imageGen/modes.js';import { extractScenes, scenesFromBeatSheet, SOURCE_KIND } from '../../lib/sceneExtractor.js';import { resolveSeriesLlmOverride } from '../../lib/seriesLlmOverride.js';import { parseComicScript } from '../../lib/comicScriptParser.js';@@ -103,7 +103,7 @@ const visualStageInputSchema = stageInputSchema.extend({// refine-LLM override. Sanitizer drops the field entirely when nothing// is set, so a `null` here clears it.genConfig: z.object({- imageMode: z.enum(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),+ imageMode: z.enum(['auto', ...QUEUEABLE_IMAGE_MODES]).optional(),imageModelId: z.string().trim().max(200).nullable().optional(),refineProvider: z.string().trim().max(200).nullable().optional(),refineModel: z.string().trim().max(200).nullable().optional(),@@ -192,7 +192,7 @@ const visualGenerateSchema = z.object({slugline: z.string().trim().max(200).optional(),negativePrompt: z.string().trim().max(2000).optional(),extraStyle: z.string().trim().max(2000).optional(),- mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),modelId: z.string().trim().max(64).optional(),width: imageEdgeSchema,height: imageEdgeSchema,@@ -219,7 +219,7 @@ const visualGenerateSchema = z.object({const comicPageRenderSchema = z.object({negativePrompt: z.string().trim().max(2000).optional(),extraStyle: z.string().trim().max(2000).optional(),- mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),modelId: z.string().trim().max(64).optional(),width: imageEdgeSchema,height: imageEdgeSchema,@@ -261,7 +261,7 @@ const comicPageRefineSchema = z.object({negativePrompt: z.string().trim().max(2000).optional(),// No `extraStyle`: the refine renders the LLM-adjusted prompt verbatim and// skips composeComicPagePrompt, so a style suffix would be silently dropped.- mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),+ mode: z.enum(QUEUEABLE_IMAGE_MODES).optional(),modelId: z.string().trim().max(64).optional(),width: imageEdgeSchema,height: imageEdgeSchema,diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 8c970a2c33..6515ecec7d 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -33,7 +33,7 @@ import { imageGenEvents } from '../imageGenEvents.js';import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';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 } from './modes.js';+import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_MODEL, CODEX_IMAGEGEN_DEFAULT_EFFORT, describeFidelity } 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@@ -119,19 +119,6 @@ export async function checkConnection({ codexPath } = {}) {const SESSION_ID_RE = /^session id:\s*([0-9a-f-]{36})/im;-// Codex CLI exposes no numeric i2i denoise knob, so map the local-runner-style-// strength (0..1, lower = more faithful to the source) onto a phrase the model-// reliably honors inside `$imagegen`. Mirrors PROOF_AS_BASE_DEFAULT_STRENGTH-// (0.25) defaulting toward composition-preserving edits. Exported for the-// grok provider, which faces the same "prompt phrase, not numeric knob"-// constraint for its image_edit tool.-export const describeFidelity = (strength) => {- const n = Number.isFinite(strength) ? Math.max(0, Math.min(1, Number(strength))) : 0.25;- if (n <= 0.2) return 'preserve composition, characters, and layout exactly — only refine detail and resolution';- if (n <= 0.4) return 'preserve composition and characters while adding rendered detail at higher fidelity';- if (n <= 0.7) return 'use the attached image as a strong reference while refining art and detail';- return 'use the attached image as a loose reference; you may reinterpret freely';-};// When `initImagePath` is set we attach the file via codex CLI's `-i <FILE>`// flag and reshape the prompt so the `$imagegen` skill feeds the attachmentdiff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex 85536a52f0..4ced0fec6f 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -23,8 +23,7 @@*/import { spawn } from 'child_process';-import { copyFile, stat, unlink } from 'fs/promises';-import { existsSync } from 'fs';+import { copyFile, rename, stat, unlink } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';import { randomUUID } from 'crypto';@@ -34,9 +33,10 @@ 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 { bufferedSpawn } from '../../lib/bufferedSpawn.js';import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';-import { IMAGE_GEN_MODE } from './modes.js';-import { describeFidelity } from './codex.js';+import { IMAGE_GEN_MODE, describeFidelity } from './modes.js';// 20 minutes — grok's image_gen typically returns in well under a minute, but// the agent turn wrapping it (skill load, tool call, file write) has no@@ -56,6 +56,10 @@ const DEFAULT_BIN = 'grok';// PortOS callers are mapped to the closest of these; a configured default// (`imageGen.grok.aspectRatio`) applies when the caller sent no dimensions.export const GROK_ASPECT_RATIOS = Object.freeze(['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3']);+const RATIO_VALUES = GROK_ASPECT_RATIOS.map((ratio) => {+ const [rw, rh] = ratio.split(':').map(Number);+ return { ratio, value: rw / rh };+});// Map a width/height pair to the closest supported grok aspect ratio, or null// when dimensions are absent/invalid (the tool then uses its own default).@@ -66,9 +70,8 @@ export function deriveAspectRatio(width, height) {const target = w / h;let best = null;let bestDelta = Infinity;- for (const ratio of GROK_ASPECT_RATIOS) {- const [rw, rh] = ratio.split(':').map(Number);- const delta = Math.abs(rw / rh - target);+ for (const { ratio, value } of RATIO_VALUES) {+ const delta = Math.abs(value - target);if (delta < bestDelta) {best = ratio;bestDelta = delta;@@ -119,33 +122,32 @@ export const cancelAll = () => {};export async function checkConnection({ grokPath } = {}) {- // Cheap probe: spawn `grok --version`. Avoids actually invoking image_gen- // (which would spend the user's Grok quota); the settings UI just wants- // "yes the binary exists and is reachable".+ // Cheap probe: `grok --version` via the shared bufferedSpawn (never+ // rejects; timeout-kills a hung binary so the settings "Test Connection"+ // can't pend forever). Avoids actually invoking image_gen, which would+ // spend the user's Grok quota.const bin = grokPath || DEFAULT_BIN;- const proc = spawn(bin, ['--version'], { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });- let out = '';- 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: IMAGE_GEN_MODE.GROK, reason: `Grok CLI not found (${err.message})` }));- proc.on('close', (code) => {- if (code !== 0) return resolve({ connected: false, mode: IMAGE_GEN_MODE.GROK, reason: `grok --version exited ${code}` });- const versionMatch = out.match(/(\d+\.\d+\.\d+)/);- resolve({ connected: true, mode: IMAGE_GEN_MODE.GROK, model: versionMatch ? `grok-cli ${versionMatch[1]}` : 'grok-cli' });- });- });+ const result = await bufferedSpawn(bin, ['--version'], { timeoutMs: 15_000 });+ if (result.error) {+ return { connected: false, mode: IMAGE_GEN_MODE.GROK, reason: `Grok CLI not found (${result.error})` };+ }+ if (result.timedOut) {+ return { connected: false, mode: IMAGE_GEN_MODE.GROK, reason: 'grok --version timed out' };+ }+ if (result.code !== 0) {+ return { connected: false, mode: IMAGE_GEN_MODE.GROK, reason: `grok --version exited ${result.code}` };+ }+ const versionMatch = `${result.stdout}${result.stderr}`.match(/(\d+\.\d+\.\d+)/);+ return { connected: true, mode: IMAGE_GEN_MODE.GROK, model: versionMatch ? `grok-cli ${versionMatch[1]}` : 'grok-cli' };}// Grok narrates its turn on stdout. Turn the tail into the most useful error// we can when the directed output file never landed — surfacing the model's// own words (content declines, tool-failure notes) instead of a fixed guess.-// eslint-disable-next-line no-control-regex-const ANSI_RE = /\u001b\[[0-9;]*m/g;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 = String(stdoutTail).replace(ANSI_RE, '').trim();+ const clean = stripAnsi(String(stdoutTail)).trim();const lines = clean.split('\n').map((l) => l.trim()).filter((l) => l && !/^-{2,}$/.test(l) && !/^[\d,]+$/.test(l));@@ -274,8 +276,7 @@ async function runGrok(job, jobId, bin, args, {const timeoutTimer = setTimeout(() => {if (activeProcs.get(jobId) === proc) {console.log(`⏱️ grok timed out after ${GROK_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);- proc.kill('SIGTERM');- setTimeout(() => { if (proc.exitCode === null) proc.kill('SIGKILL'); }, 5000);+ sigtermWithEscalation(jobId, proc);}}, GROK_TIMEOUT_MS);@@ -314,8 +315,13 @@ async function runGrok(job, jobId, bin, args, {if (!harvested) {return finalizeError(job, jobId, proc, noImageReason(stdoutTail));}- await copyFile(stagingPath, outputPath);- await unlink(stagingPath).catch(() => {});+ // Move, not copy — the staging file is PortOS-owned and disposable, so+ // rename is a metadata-only op when tmpdir and the gallery share a+ // filesystem. copyFile+unlink is the cross-device (EXDEV) fallback.+ await rename(stagingPath, outputPath).catch(async () => {+ await copyFile(stagingPath, outputPath);+ await unlink(stagingPath).catch(() => {});+ });// Sidecar metadata so the gallery can recover prompt/ratio/etc.const sidecar = join(PATHS.images, `${jobId}.metadata.json`);await atomicWrite(sidecar, meta).catch(() => {});@@ -352,14 +358,13 @@ const finalizeError = (job, jobId, proc, reason) => {};// Poll for the directed output file until it exists non-empty or timeoutMs-// elapses. Returns true when the file is ready.+// elapses. Returns true when the file is ready. A single stat() answers both+// "exists" and "non-empty" per tick.async function harvestStagedImage(stagingPath, timeoutMs) {const deadline = Date.now() + timeoutMs;while (Date.now() < deadline) {- if (existsSync(stagingPath)) {- const s = await stat(stagingPath).catch(() => null);- if (s && s.size > 0) return true;- }+ const s = await stat(stagingPath).catch(() => null);+ if (s && s.size > 0) return true;await new Promise((r) => setTimeout(r, 250));}return false;diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.jsindex 1363ee7c98..4facc8d053 100644--- a/server/services/imageGen/modes.js+++ b/server/services/imageGen/modes.js@@ -26,6 +26,26 @@ export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));// generateImage returns a job descriptor before the file lands.export const CLOUD_IMAGE_GEN_MODES = Object.freeze([IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);+// Modes the mediaJobQueue can run (external SD-API stays synchronous — a+// remote HTTP call with no local single-flight constraint to absorb). Single+// source for the pipeline routes' Zod enums and batch-render guards, so a+// future backend is one edit here instead of a sweep of enum literals.+export const QUEUEABLE_IMAGE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, ...CLOUD_IMAGE_GEN_MODES]);++// Cloud-CLI providers expose no numeric i2i denoise knob, so map the+// local-runner-style strength (0..1, lower = more faithful to the source)+// onto a phrase the model reliably honors. Mirrors+// PROOF_AS_BASE_DEFAULT_STRENGTH (0.25) defaulting toward+// composition-preserving edits. Lives here (the shared no-dependency module)+// so codex.js and grok.js both import it without a provider→provider import.+export const describeFidelity = (strength) => {+ const n = Number.isFinite(strength) ? Math.max(0, Math.min(1, Number(strength))) : 0.25;+ if (n <= 0.2) return 'preserve composition, characters, and layout exactly — only refine detail and resolution';+ if (n <= 0.4) return 'preserve composition and characters while adding rendered detail at higher fidelity';+ if (n <= 0.7) return 'use the attached image as a strong reference while refining art and detail';+ return 'use the attached image as a loose reference; you may reinterpret freely';+};+// Shipped defaults for the Codex imagegen backend. Codex's built-in image_gen// tool otherwise runs whatever model its logged-in session defaults to — often// the heaviest, most expensive tier — at default reasoning effort. Pin the cheapdiff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 5165c6ce89..286fe4ba5b 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -9,7 +9,7 @@* an immediate `queued` ack and watch progress via SSE.** Lanes: GPU jobs (video + local image) drain serially through `running` since- * they share the MLX runtime. Codex image jobs run in a parallel `codexRunning`+ * they share the MLX runtime. Codex image jobs run in a parallel `cloudRunning`* lane — they shell out to an external CLI and don't compete for GPU memory,* so a long video render never blocks a Codex storyboard generation.*@@ -173,14 +173,14 @@ async function resolveLiveParams(job, safeParams) {export const mediaJobEvents = new EventEmitter();// GPU lane: serialized — `running` holds at most one job (the MLX runtime can't-// share VRAM). Codex lane: up to `codexParallelLimit` jobs in `codexRunning[]`+// share VRAM). Codex lane: up to `codexParallelLimit` jobs in `cloudRunning[]`// since each call shells out to its own external child process. `queue` is// shared submission order. `archive` is recently-finished jobs (~24h TTL),// including canceled ones so /api/media-jobs?status=canceled and the recent-// reel UI can still find them within the 24h window.const queue = [];let running = null;-const codexRunning = [];+const cloudRunning = [];const archive = [];export const CODEX_PARALLEL_MIN = 1;@@ -215,7 +215,7 @@ let initPromise = null;function findJob(jobId) {if (running && running.id === jobId) return running;- const codexHit = codexRunning.find((j) => j.id === jobId);+ const codexHit = cloudRunning.find((j) => j.id === jobId);if (codexHit) return codexHit;const inQueue = queue.find((j) => j.id === jobId);if (inQueue) return inQueue;@@ -229,7 +229,7 @@ export function getJob(jobId) {export function listJobs({ status, kind, owner } = {}) {const all = [...(running ? [running] : []),- ...codexRunning,+ ...cloudRunning,...queue,...archive,];@@ -264,7 +264,7 @@ async function persistImpl() {archive.push(...trimmedArchive);const live = [...(running ? [running] : []),- ...codexRunning,+ ...cloudRunning,...queue,...archive,];@@ -354,11 +354,11 @@ export async function initMediaJobQueue() {// event report accurate slots. Positions are lane-scoped: Codex image// jobs and GPU jobs each get their own counter so a queued Codex job// behind a running GPU job is restored as position 1 (not position 2).- let codexCounter = 0;+ let cloudCounter = 0;let gpuCounter = 0;for (const q of queue) {if (isCloudImageJob(q)) {- q.position = ++codexCounter;+ q.position = ++cloudCounter;} else {q.position = ++gpuCounter;}@@ -409,7 +409,7 @@ function startWorker() {function startLaneJob(job, { isCloud }) {// If the job isn't in the queue, it was already promoted (e.g. by a parallel// runJobNow). Skip — promoting again would double-start the job and corrupt- // the lane (push it onto codexRunning/running twice). Silently splice(-1)+ // the lane (push it onto cloudRunning/running twice). Silently splice(-1)// would also lop the wrong job off the queue.const idx = queue.indexOf(job);if (idx < 0) {@@ -423,13 +423,13 @@ function startLaneJob(job, { isCloud }) {job.progress = typeof job.progress === 'number' && Number.isFinite(job.progress) ? job.progress : 0;job.statusMsg = job.statusMsg || 'Starting';if (isCloud) {- codexRunning.push(job);+ cloudRunning.push(job);} else {running = job;}recomputeQueuePositions();const label = isCloud ? (job.params?.mode || 'cloud') : job.kind;- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${isCloud ? label : 'gpu'} start failed: ${e.message}`));+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} start failed: ${e.message}`));broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });mediaJobEvents.emit('started', job);console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${label} started`);@@ -450,8 +450,8 @@ function startLaneJob(job, { isCloud }) {}}if (isCloud) {- const idx = codexRunning.indexOf(job);- if (idx >= 0) codexRunning.splice(idx, 1);+ const idx = cloudRunning.indexOf(job);+ if (idx >= 0) cloudRunning.splice(idx, 1);} else {running = null;}@@ -469,19 +469,19 @@ async function drainLoop() {// Single queue scan, promote eligible codex jobs while there's room and a// GPU job if the lane is open. Stops cleanly on an empty queue.let gpuOpen = !running;- let codexSlots = codexParallelLimit - codexRunning.length;- if ((gpuOpen || codexSlots > 0) && queue.length > 0) {+ let cloudSlots = codexParallelLimit - cloudRunning.length;+ if ((gpuOpen || cloudSlots > 0) && queue.length > 0) {for (const job of queue.slice()) {if (isCloudImageJob(job)) {- if (codexSlots > 0) {+ if (cloudSlots > 0) {startLaneJob(job, { isCloud: true });- codexSlots -= 1;+ cloudSlots -= 1;}} else if (gpuOpen) {startLaneJob(job, { isCloud: false });gpuOpen = false;}- if (!gpuOpen && codexSlots <= 0) break;+ if (!gpuOpen && cloudSlots <= 0) break;}}await sleep(150);@@ -529,11 +529,11 @@ export function runJobNow(jobId) {// /:jobId/events would keep showing the position from its original enqueue// frame even after the line ahead of it cleared.function recomputeQueuePositions() {- const codexJobs = queue.filter(isCloudImageJob);+ const cloudJobs = queue.filter(isCloudImageJob);const gpuJobs = queue.filter((j) => !isCloudImageJob(j));- codexJobs.forEach((q, i) => {- const newPosition = i + 1 + codexRunning.length;+ cloudJobs.forEach((q, i) => {+ const newPosition = i + 1 + cloudRunning.length;if (q.position !== newPosition) {q.position = newPosition;const entry = sseJobs.get(q.id);@@ -901,7 +901,7 @@ export function enqueueJob({ kind, params, owner = null }) {position: (() => {const isCloud = isCloudImageJob({ kind, params });const laneQueue = queue.filter((j) => isCloudImageJob(j) === isCloud);- return laneQueue.length + (isCloud ? codexRunning.length : (running ? 1 : 0)) + 1;+ return laneQueue.length + (isCloud ? cloudRunning.length : (running ? 1 : 0)) + 1;})(),};queue.push(job);@@ -975,7 +975,7 @@ export async function cancelJob(jobId) {}// Cancel-while-running — check the GPU slot and every parallel codex slot.const runningJob = (running?.id === jobId ? running : null)- ?? codexRunning.find((j) => j.id === jobId)+ ?? cloudRunning.find((j) => j.id === jobId)?? null;if (runningJob) {// A terminal transition already started (completed/failed/watchdog): its@@ -1057,9 +1057,9 @@ export function attachSseClient(jobId, res) {export function __resetForTests() {queue.length = 0;running = null;- // `codexRunning` is a const array — clear it in place rather than reassigning,+ // `cloudRunning` is a const array — clear it in place rather than reassigning,// which would throw TypeError and break `findJob()` (.find on null).- codexRunning.length = 0;+ cloudRunning.length = 0;archive.length = 0;sseJobs.clear();workerStarted = false;diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.jsindex f0541f8b48..c02f994137 100644--- a/server/services/pipeline/issuesShared.js+++ b/server/services/pipeline/issuesShared.js@@ -20,7 +20,7 @@import { getIssuesStore } from './issuesStore/store.js';import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';+import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from '../imageGen/modes.js';import {LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,@@ -356,7 +356,7 @@ const QUALITY_VALUES = new Set(['draft', 'standard', 'high']);// `imageMode: 'auto'` defers to the server resolver (codex when enabled,// local otherwise). Returns null when nothing was set so the persisted// JSON stays clean for issues that never opened the panel.-const IMAGE_MODE_VALUES = new Set(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);+const IMAGE_MODE_VALUES = new Set(['auto', ...QUEUEABLE_IMAGE_MODES]);const GEN_CONFIG_STR_MAX = 200;const sanitizeGenConfig = (raw) => {if (!raw || typeof raw !== 'object') return null;diff --git a/server/services/universeBuilderRender.js b/server/services/universeBuilderRender.jsindex 74bfcb6ee1..c278e18794 100644--- a/server/services/universeBuilderRender.js+++ b/server/services/universeBuilderRender.js@@ -18,7 +18,7 @@ import { buildUniverseRunTag } from './universeRunTag.js';import { registerUniverseBuilderRun } from './universeBuilderCollectionHook.js';import { getImageModels, isFlux2 } from '../lib/mediaModels.js';import { usesDiffusersRunner } from '../lib/runners.js';-import { IMAGE_GEN_MODE } from './imageGen/modes.js';+import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from './imageGen/modes.js';import { resolveImageCleaners } from './imageGen/index.js';import { getStylePresetById } from '../lib/writersRoomStylePresets.js';import { ServerError } from '../lib/errorHandler.js';@@ -63,7 +63,7 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {// 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 !== IMAGE_GEN_MODE.LOCAL && mode !== IMAGE_GEN_MODE.CODEX && mode !== IMAGE_GEN_MODE.GROK) {+ if (!QUEUEABLE_IMAGE_MODES.includes(mode)) {throw new ServerError('Batch render requires local, codex, or grok mode — switch image-gen mode in Settings → Image Gen',{ status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },diff --git a/server/services/voice/tools/media.js b/server/services/voice/tools/media.jsindex 22eba54638..aa5b36c343 100644--- a/server/services/voice/tools/media.js+++ b/server/services/voice/tools/media.js@@ -51,20 +51,16 @@ export const MEDIA_TOOLS = [return { ok: false, summary: 'prompt must be 2000 characters or fewer' };}const requestedMode = (provider && provider !== 'auto') ? provider : undefined;- // Codex is gated separately — it costs against the user's Codex plan,- // and not every plan exposes image_gen. The dispatcher would also- // reject this, but catching it here lets us return a friendlier- // summary to the voice agent / palette.- if (requestedMode === imageGen.IMAGE_GEN_MODE.CODEX) {+ // Cloud-CLI providers (codex/grok) are gated separately — each costs+ // against the user's plan, and not every plan exposes the image tool.+ // The dispatcher would also reject this, but catching it here lets us+ // return a friendlier summary to the voice agent / palette. The+ // settings key equals the mode string for both.+ if (imageGen.CLOUD_IMAGE_GEN_MODES.includes(requestedMode)) {const s = await getSettings();- if (!s?.imageGen?.codex?.enabled) {- return { ok: false, summary: 'Codex Imagegen is disabled — enable it in Settings → Image Gen first.' };- }- }- if (requestedMode === imageGen.IMAGE_GEN_MODE.GROK) {- const s = await getSettings();- if (!s?.imageGen?.grok?.enabled) {- return { ok: false, summary: 'Grok Imagegen is disabled — enable it in Settings → Image Gen first.' };+ if (!s?.imageGen?.[requestedMode]?.enabled) {+ const label = requestedMode === imageGen.IMAGE_GEN_MODE.CODEX ? 'Codex' : 'Grok';+ return { ok: false, summary: `${label} Imagegen is disabled — enable it in Settings → Image Gen first.` };}}// LLMs/tool callers often hand back numeric args as strings ("512").