Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-2859]): add xAI Grok Build CLI as an image generation backend

[._.]/ Adam Eivy873e033d54e2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e641321021..5d2d954682 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased
+## Image generation
+
+- **[issue-2859] xAI Grok (Grok Build CLI) is a new image-generation backend** — enable it in Settings → Image Gen → Grok CLI and every image surface (Image Gen page, pipeline renders, character sheets, universe builder batches, avatars, voice `image_generate`) can route through the Grok CLI's built-in `image_gen` tool, including image-to-image editing via `image_edit`. Configuration is just the binary path and an optional default aspect ratio — Grok picks the model internally. Grok renders run in the same parallel queue lane as Codex, and Grok video generation is planned as a follow-up phase.
+
## Tribe outreach
- **[issue-2831] Unanswered 1:1 emails to a Gmail alias now surface as outreach nudges** — a message delivered to one of your Gmail send-as aliases (not your primary address) is correctly treated as a one-on-one conversation instead of a group thread, so a genuinely unanswered email to an alias no longer gets silently skipped. Your own alias addresses never appear as a Tribe contact.
diff --git a/client/src/components/imageGen/ImageGenControls.jsx b/client/src/components/imageGen/ImageGenControls.jsx
index ccb5e06d6f..cb1e7d54bd 100644
--- a/client/src/components/imageGen/ImageGenControls.jsx
+++ b/client/src/components/imageGen/ImageGenControls.jsx
@@ -52,7 +52,9 @@ export default function ImageGenControls({
onModelDownloadCancel,
}) {
const isLocal = mode === IMAGE_GEN_MODE.LOCAL;
- const isCodex = mode === IMAGE_GEN_MODE.CODEX;
+ // 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 currentModel = models.find((m) => m.id === modelId);
const isFlux2 = currentModel?.runner === RUNNER_FAMILIES.FLUX2;
diff --git a/client/src/components/imageGen/ImageGenSettingsForm.jsx b/client/src/components/imageGen/ImageGenSettingsForm.jsx
index d85929f5d5..d56f960c63 100644
--- a/client/src/components/imageGen/ImageGenSettingsForm.jsx
+++ b/client/src/components/imageGen/ImageGenSettingsForm.jsx
@@ -56,6 +56,7 @@ export default function ImageGenSettingsForm({
const cfg = value || {};
const merge = (patch) => onChange?.({ ...cfg, ...patch });
const isCodex = cfg.mode === IMAGE_GEN_MODE.CODEX;
+ const isGrok = cfg.mode === IMAGE_GEN_MODE.GROK;
const isLocal = cfg.mode === IMAGE_GEN_MODE.LOCAL;
const labelCls = 'block text-xs font-medium text-gray-400 mb-1';
const textareaCls = 'w-full bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:outline-none focus:border-port-accent disabled:opacity-50 resize-y';
@@ -82,6 +83,10 @@ export default function ImageGenSettingsForm({
<p className="text-[10px] text-gray-500 mt-1">
Codex's <code className="text-gray-400">$imagegen</code> picks model, steps, and seed internally. Only resolution + style fields apply.
</p>
+ ) : isGrok ? (
+ <p className="text-[10px] text-gray-500 mt-1">
+ Grok's <code className="text-gray-400">image_gen</code> picks model, steps, and seed internally. Resolution maps to the nearest supported aspect ratio; style fields apply.
+ </p>
) : null}
</div>
) : null;
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 3c6ea2297a..a9f6a2d217 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -49,6 +49,12 @@ function modelLabel(params) {
const base = m ? `codex / ${m}` : 'codex';
return `${base} · ${eff}`;
}
+ if (params.mode === IMAGE_GEN_MODE.GROK) {
+ // No model/effort knobs — grok's image tools run on xAI's fixed backend;
+ // the aspect ratio is the only distinguishing render param.
+ const ratio = (typeof params.aspectRatio === 'string' ? params.aspectRatio.trim() : '');
+ return ratio ? `grok · ${ratio}` : 'grok';
+ }
const id = (params.modelId || '').trim();
if (!id) return 'local';
const tail = id.includes('/') ? id.slice(id.lastIndexOf('/') + 1) : id;
@@ -314,7 +320,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 === IMAGE_GEN_MODE.CODEX;
+ 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';
// Number.isFinite (not typeof === 'number') so a NaN from a hand-edited
// media-jobs.json can't render as `NaN%` / `width: NaN%`.
diff --git a/client/src/components/settings/ImageGenTab.jsx b/client/src/components/settings/ImageGenTab.jsx
index dc80462068..3b0f997199 100644
--- a/client/src/components/settings/ImageGenTab.jsx
+++ b/client/src/components/settings/ImageGenTab.jsx
@@ -22,13 +22,14 @@ import {
registerTool, updateTool, getToolsList,
getHfTokenStatus, saveHfToken, clearHfToken,
} from '../../services/api';
-import { IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT } from '../../lib/imageGenBackends';
+import { 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';
const SDAPI_TOOL_ID = 'sdapi';
const CODEX_TOOL_ID = 'codex-imagegen';
+const GROK_TOOL_ID = 'grok-imagegen';
// Mirror of server/services/imageGen/modes.js — shown as placeholder/default
// hints so the user sees what a blank Model / Effort field will actually use.
// The server owns the real default; these are display-only. The effort default
@@ -56,6 +57,7 @@ const MEDIA_TABS = [
{ id: 'external', label: 'External', icon: Cloud },
{ id: 'local', label: 'Local', icon: Cpu },
{ id: 'codex', label: 'Codex CLI', icon: Terminal },
+ { id: 'grok', label: 'Grok CLI', icon: Sparkles },
{ id: 'tokens', label: 'Tokens', icon: Key },
{ id: 'expose', label: 'Expose', icon: Globe },
{ id: 'test', label: 'Test', icon: Sparkles },
@@ -96,6 +98,13 @@ export function ImageGenTab() {
// Empty = use the shipped default effort (CODEX_IMAGEGEN_DEFAULT_EFFORT).
const [codexEffort, setCodexEffort] = useState('');
const [codexParallelLimit, setCodexParallelLimit] = useState(1);
+ // Grok Build CLI provider config — gated by `grokEnabled` the same way as
+ // Codex (renders spend the user's Grok quota). No model/effort fields:
+ // grok's image tools run on xAI's fixed image backend.
+ const [grokEnabled, setGrokEnabled] = useState(false);
+ const [grokPath, setGrokPath] = useState('');
+ // Empty = let the caller's width/height (or the tool default) decide.
+ const [grokAspectRatio, setGrokAspectRatio] = useState('');
// Per-provider cleaner toggles. Both run after the PNG lands and before
// the SSE complete event so subscribers see the cleaned bytes. SynthID
// (the gpt-image / Imagen / Gemini pixel-level watermark) is unaffected
@@ -105,8 +114,8 @@ export function ImageGenTab() {
// provenance chunk. Lossless — pixels untouched.
// - denoise (default OFF): median(3) + sharpen pass for AI-artifact
// reduction. LOSSY: blurs annotation text and small details.
- const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true });
- const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false });
+ const [cleanC2PAByMode, setCleanC2PAByMode] = useState({ external: true, local: true, codex: true, grok: false });
+ const [denoiseByMode, setDenoiseByMode] = useState({ external: false, local: false, codex: false, grok: false });
const setCleanC2PAFor = (m) => (v) => setCleanC2PAByMode((p) => ({ ...p, [m]: v }));
const setDenoiseFor = (m) => (v) => setDenoiseByMode((p) => ({ ...p, [m]: v }));
// Raw string held while the user is typing in the parallel-limit input.
@@ -122,19 +131,23 @@ export function ImageGenTab() {
const codexModelId = useId();
const codexEffortId = useId();
const codexParallelId = useId();
+ const grokPathId = useId();
+ const grokRatioId = useId();
// Snapshot of saved values so we can show the "dirty" state
const [saved, setSaved] = useState({
mode: IMAGE_GEN_MODE.EXTERNAL, sdapiUrl: '', pythonPath: '', exposeA1111: false,
codexEnabled: false, codexPath: '', codexModel: '', codexEffort: '', codexParallelLimit: 1,
- cleanC2PAByMode: { external: true, local: true, codex: true },
- denoiseByMode: { external: false, local: false, codex: false },
+ grokEnabled: false, grokPath: '', grokAspectRatio: '',
+ cleanC2PAByMode: { external: true, local: true, codex: true, grok: false },
+ denoiseByMode: { external: false, local: false, codex: false, grok: false },
});
const [status, setStatus] = useState(null);
const [checking, setChecking] = useState(false);
const [toolRegistered, setToolRegistered] = useState(false);
const [codexToolRegistered, setCodexToolRegistered] = useState(false);
+ const [grokToolRegistered, setGrokToolRegistered] = useState(false);
const [testPrompt, setTestPrompt] = useState(DEFAULT_TEST_PROMPT);
const [rendering, setRendering] = useState(false);
@@ -204,13 +217,18 @@ export function ImageGenTab() {
: PARALLEL_FALLBACK;
setParallelBounds(bounds);
const cxParallel = clampParallel(cx.parallelLimit, bounds);
+ const gk = ig.grok || {};
+ const gkEnabled = gk.enabled === true;
+ const gkPath = gk.grokPath || '';
+ const gkRatio = gk.aspectRatio || '';
// Per-mode cleaner reads via the shared helper (mirrored from
// server/lib/imageClean.js).
const codexClean = resolveCleanersFromConfig(cx, IMAGE_GEN_MODE.CODEX);
+ const grokClean = resolveCleanersFromConfig(gk, IMAGE_GEN_MODE.GROK);
const localClean = resolveCleanersFromConfig(ig.local, IMAGE_GEN_MODE.LOCAL);
const externalClean = resolveCleanersFromConfig(ig.external, IMAGE_GEN_MODE.EXTERNAL);
- const c2 = { codex: codexClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };
- const dn = { codex: codexClean.denoise, local: localClean.denoise, external: externalClean.denoise };
+ const c2 = { codex: codexClean.cleanC2PA, grok: grokClean.cleanC2PA, local: localClean.cleanC2PA, external: externalClean.cleanC2PA };
+ const dn = { codex: codexClean.denoise, grok: grokClean.denoise, local: localClean.denoise, external: externalClean.denoise };
setMode(m);
setSdapiUrl(url);
setPythonPath(py);
@@ -221,16 +239,21 @@ export function ImageGenTab() {
setCodexEffort(cxEffort);
setCodexParallelLimit(cxParallel);
setParallelLimitDraft(String(cxParallel));
+ setGrokEnabled(gkEnabled);
+ setGrokPath(gkPath);
+ setGrokAspectRatio(gkRatio);
setCleanC2PAByMode(c2);
setDenoiseByMode(dn);
setSaved({
mode: m, sdapiUrl: url, pythonPath: py, exposeA1111: expose,
codexEnabled: cxEnabled, codexPath: cxPath, codexModel: cxModel, codexEffort: cxEffort,
codexParallelLimit: cxParallel,
+ grokEnabled: gkEnabled, grokPath: gkPath, grokAspectRatio: gkRatio,
cleanC2PAByMode: c2, denoiseByMode: dn,
});
setToolRegistered(tools.some((t) => t.id === SDAPI_TOOL_ID));
setCodexToolRegistered(tools.some((t) => t.id === CODEX_TOOL_ID));
+ setGrokToolRegistered(tools.some((t) => t.id === GROK_TOOL_ID));
})
.catch(() => toast.error('Failed to load image gen settings'))
.finally(() => setLoading(false));
@@ -253,6 +276,11 @@ export function ImageGenTab() {
|| codexModel !== saved.codexModel
|| codexEffort !== saved.codexEffort
|| codexParallelLimit !== saved.codexParallelLimit
+ || grokEnabled !== saved.grokEnabled
+ || grokPath !== saved.grokPath
+ || grokAspectRatio !== saved.grokAspectRatio
+ || cleanC2PAByMode.grok !== saved.cleanC2PAByMode.grok
+ || denoiseByMode.grok !== saved.denoiseByMode.grok
|| cleanC2PAByMode.codex !== saved.cleanC2PAByMode.codex
|| cleanC2PAByMode.local !== saved.cleanC2PAByMode.local
|| cleanC2PAByMode.external !== saved.cleanC2PAByMode.external
@@ -267,6 +295,8 @@ export function ImageGenTab() {
const cxModel = codexModel?.trim() || undefined;
const cxEffort = codexEffort?.trim() || undefined;
const cxParallel = clampParallel(codexParallelLimit, parallelBounds);
+ const gkPath = grokPath?.trim() || undefined;
+ const gkRatio = grokAspectRatio?.trim() || undefined;
const patch = {
imageGen: {
mode,
@@ -276,6 +306,10 @@ export function ImageGenTab() {
enabled: codexEnabled, codexPath: cxPath, model: cxModel, effort: cxEffort, parallelLimit: cxParallel,
cleanC2PA: cleanC2PAByMode.codex, denoise: denoiseByMode.codex,
},
+ grok: {
+ enabled: grokEnabled, grokPath: gkPath, aspectRatio: gkRatio,
+ cleanC2PA: cleanC2PAByMode.grok, denoise: denoiseByMode.grok,
+ },
expose: { a1111: exposeA1111 },
// Keep the legacy field populated so anything still reading
// `imageGen.sdapiUrl` directly stays working.
@@ -292,6 +326,7 @@ export function ImageGenTab() {
mode, sdapiUrl: url || '', pythonPath, exposeA1111,
codexEnabled, codexPath: cxPath || '', codexModel: cxModel || '', codexEffort: cxEffort || '',
codexParallelLimit: cxParallel,
+ grokEnabled, grokPath: gkPath || '', grokAspectRatio: gkRatio || '',
cleanC2PAByMode, denoiseByMode,
});
if (cxParallel !== codexParallelLimit) {
@@ -303,6 +338,8 @@ export function ImageGenTab() {
if (cxPath !== codexPath) setCodexPath(cxPath || '');
if (cxModel !== codexModel) setCodexModel(cxModel || '');
if (cxEffort !== codexEffort) setCodexEffort(cxEffort || '');
+ if (gkPath !== grokPath) setGrokPath(gkPath || '');
+ if (gkRatio !== grokAspectRatio) setGrokAspectRatio(gkRatio || '');
toast.success('Image gen settings saved');
} catch (err) {
toast.error(err.message || 'Failed to save settings');
@@ -321,6 +358,14 @@ export function ImageGenTab() {
config: { mode, sdapiUrl: url, pythonPath },
promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps }. Use POST /api/image-gen/avatar for character portraits.',
};
+ const grokToolData = {
+ name: 'Grok Imagegen',
+ category: 'image-generation',
+ description: 'Generate images via the Grok Build CLI built-in image_gen tool. Requires a Grok plan that includes image generation.',
+ enabled: grokEnabled,
+ config: { grokPath: gkPath, aspectRatio: gkRatio },
+ promptHints: 'Use POST /api/image-gen/generate with { prompt, mode: "grok" } — or call the image_generate voice tool with provider: "grok".',
+ };
const codexToolData = {
name: 'Codex Imagegen',
category: 'image-generation',
@@ -355,6 +400,11 @@ export function ImageGenTab() {
shouldCreate: codexEnabled, onCreated: () => setCodexToolRegistered(true),
errLabel: 'Codex Imagegen tool',
}),
+ syncTool({
+ id: GROK_TOOL_ID, registered: grokToolRegistered, data: grokToolData,
+ shouldCreate: grokEnabled, onCreated: () => setGrokToolRegistered(true),
+ errLabel: 'Grok Imagegen tool',
+ }),
]);
setSaving(false);
@@ -377,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);
+ const isAsync = (result?.mode === IMAGE_GEN_MODE.LOCAL || result?.mode === IMAGE_GEN_MODE.CODEX || result?.mode === IMAGE_GEN_MODE.GROK);
if (isAsync && result?.generationId) {
const jobResult = await attachRenderSse(result.generationId, {
onError: (msg) => new Error(msg.error || 'Generation failed'),
@@ -447,7 +497,7 @@ export function ImageGenTab() {
generation locally with mflux on this Mac. Pick whichever fits — you can also
expose this PortOS as an A1111-compatible endpoint for other tailnet boxes.
</p>
- <div className={`grid grid-cols-1 sm:grid-cols-2 ${codexEnabled ? 'lg:grid-cols-3' : ''} gap-3`}>
+ <div className={`grid grid-cols-1 sm:grid-cols-2 ${(codexEnabled || grokEnabled) ? 'lg:grid-cols-3' : ''} gap-3`}>
<button
type="button"
onClick={() => setMode(IMAGE_GEN_MODE.EXTERNAL)}
@@ -483,6 +533,19 @@ export function ImageGenTab() {
<p className="text-xs text-gray-500 mt-1">Route through the Codex CLI built-in image_gen tool. Counts against your Codex plan.</p>
</button>
)}
+ {grokEnabled && (
+ <button
+ type="button"
+ onClick={() => setMode(IMAGE_GEN_MODE.GROK)}
+ className={`text-left p-4 rounded-lg border transition-colors ${mode === IMAGE_GEN_MODE.GROK ? '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">
+ <Sparkles className="w-4 h-4" />
+ <span className="font-medium text-sm">Grok CLI</span>
+ </div>
+ <p className="text-xs text-gray-500 mt-1">Route through the Grok Build CLI built-in image_gen tool. Counts against your Grok plan.</p>
+ </button>
+ )}
</div>
</div>
)}
@@ -643,6 +706,85 @@ export function ImageGenTab() {
</div>
)}
+ {/* Grok Build CLI config — mirrors the Codex section's enable-gate
+ pattern. Grok appears as a backend tile only after the user flips
+ this on. Simpler than the Codex form: grok's image tools expose no
+ model/effort knobs, so it's just the binary path + a default aspect
+ ratio + the cleaner toggles. */}
+ {mediaTab === 'grok' && (
+ <div className="bg-port-card border border-port-border rounded-xl p-6 space-y-4">
+ <div className="flex items-center gap-2 text-white">
+ <Sparkles size={18} />
+ <h2 className="text-lg font-semibold">Grok CLI Imagegen</h2>
+ </div>
+ <p className="text-xs text-gray-500">
+ Route image generation through the Grok Build CLI's built-in
+ <code className="text-gray-400"> image_gen </code> tool (and
+ <code className="text-gray-400"> image_edit </code> for image-to-image) — invoked headlessly.
+ Uses your logged-in Grok session, no XAI_API_KEY required. Not every Grok plan includes
+ image generation; if yours doesn't, leave this off.
+ </p>
+ <label className="flex items-center gap-3 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={grokEnabled}
+ onChange={(e) => {
+ const v = e.target.checked;
+ setGrokEnabled(v);
+ // Disabling Grok while it's the active backend would leave the
+ // saved mode pointing at a disabled provider — same fallback
+ // order as the Codex toggle: local if configured, else external.
+ if (!v && mode === IMAGE_GEN_MODE.GROK) {
+ const hasLocal = !!pythonPath?.trim();
+ setMode(hasLocal ? IMAGE_GEN_MODE.LOCAL : IMAGE_GEN_MODE.EXTERNAL);
+ }
+ }}
+ className="rounded"
+ />
+ <span className="text-sm text-gray-300">Enable Grok Imagegen</span>
+ </label>
+ {grokEnabled && (
+ <div className="space-y-3 pl-6 border-l-2 border-port-border">
+ <div>
+ <label htmlFor={grokPathId} className="block text-xs font-medium text-gray-400 mb-1">Grok binary path (optional)</label>
+ <input
+ id={grokPathId}
+ type="text"
+ value={grokPath}
+ onChange={(e) => setGrokPath(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ placeholder="grok (uses $PATH)"
+ />
+ <p className="text-xs text-gray-500 mt-1">Leave empty to invoke <code>grok</code> from $PATH.</p>
+ </div>
+ <div>
+ <label htmlFor={grokRatioId} className="block text-xs font-medium text-gray-400 mb-1">Default aspect ratio (optional)</label>
+ <select
+ id={grokRatioId}
+ value={grokAspectRatio}
+ onChange={(e) => setGrokAspectRatio(e.target.value)}
+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:outline-none focus:border-port-accent"
+ >
+ <option value="">Auto (from requested size)</option>
+ {GROK_ASPECT_RATIOS.map((r) => (
+ <option key={r} value={r}>{r}</option>
+ ))}
+ </select>
+ <p className="text-xs text-gray-500 mt-1">
+ Applied when a render doesn't specify dimensions. A render's width/height maps to the nearest supported ratio automatically.
+ </p>
+ </div>
+ <CleanersToggles
+ cleanC2PA={cleanC2PAByMode.grok}
+ denoise={denoiseByMode.grok}
+ onCleanC2PAChange={setCleanC2PAFor(IMAGE_GEN_MODE.GROK)}
+ onDenoiseChange={setDenoiseFor(IMAGE_GEN_MODE.GROK)}
+ />
+ </div>
+ )}
+ </div>
+ )}
+
{/* HuggingFace token — used by local Flux models (FLUX.1-dev, FLUX.2-klein).
Independent of the mode picker because the token persists in settings
and applies whenever local image gen runs. */}
diff --git a/client/src/components/settings/ImageGenTab.test.jsx b/client/src/components/settings/ImageGenTab.test.jsx
index 5163f62324..f97470ed37 100644
--- a/client/src/components/settings/ImageGenTab.test.jsx
+++ b/client/src/components/settings/ImageGenTab.test.jsx
@@ -60,10 +60,10 @@ beforeEach(() => {
});
describe('ImageGenTab grouped tabs', () => {
- it('renders a pills sub-nav with all seven media-settings groups', async () => {
+ it('renders a pills sub-nav with all eight media-settings groups', async () => {
await renderTab();
const tabs = screen.getAllByRole('tab').map((t) => t.textContent);
- for (const label of ['Backend', 'External', 'Local', 'Codex CLI', 'Tokens', 'Expose', 'Test']) {
+ for (const label of ['Backend', 'External', 'Local', 'Codex CLI', 'Grok CLI', 'Tokens', 'Expose', 'Test']) {
expect(tabs.some((t) => t.includes(label))).toBe(true);
}
});
@@ -136,6 +136,62 @@ describe('ImageGenTab grouped tabs', () => {
expect(patch.imageGen.external.sdapiUrl).toBe('http://localhost:9999');
expect(patch.imageGen.mode).toBe('external');
expect(patch.imageGen).toHaveProperty('codex');
+ expect(patch.imageGen).toHaveProperty('grok');
expect(patch.imageGen).toHaveProperty('expose');
});
});
+
+describe('ImageGenTab — Grok CLI section (#2859)', () => {
+ it('shows the enable toggle and hides the config fields until enabled', async () => {
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
+ expect(screen.getByRole('heading', { name: 'Grok CLI Imagegen' })).toBeTruthy();
+ const toggle = screen.getByLabelText(/Enable Grok Imagegen/i);
+ expect(toggle.checked).toBe(false);
+ expect(screen.queryByPlaceholderText('grok (uses $PATH)')).toBeNull();
+ fireEvent.click(toggle);
+ expect(screen.getByPlaceholderText('grok (uses $PATH)')).toBeTruthy();
+ expect(screen.getByLabelText(/Default aspect ratio/i)).toBeTruthy();
+ });
+
+ it('adds a Grok backend tile only when enabled, and saves the grok slice', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: {
+ mode: 'external',
+ external: { sdapiUrl: 'http://localhost:7860' },
+ grok: { enabled: true, grokPath: '/opt/grok', aspectRatio: '16:9' },
+ },
+ });
+ await renderTab();
+ // Enabled grok surfaces a backend tile on the Backend tab (scope the
+ // query to the tile description — the tab bar also says "Grok CLI").
+ expect(screen.getByText(/Route through the Grok Build CLI/i)).toBeTruthy();
+ // Dirty the grok path and save — the patch carries the grok slice.
+ fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
+ fireEvent.change(screen.getByPlaceholderText('grok (uses $PATH)'), { target: { value: '/usr/local/bin/grok' } });
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ const patch = updateSettings.mock.calls[0][0];
+ expect(patch.imageGen.grok).toEqual(expect.objectContaining({
+ enabled: true, grokPath: '/usr/local/bin/grok', aspectRatio: '16:9',
+ }));
+ });
+
+ it('falls the mode back to local when grok is disabled while active', async () => {
+ getSettings.mockResolvedValue({
+ imageGen: {
+ mode: 'grok',
+ local: { pythonPath: '/usr/bin/python3' },
+ grok: { enabled: true },
+ },
+ });
+ await renderTab();
+ fireEvent.click(screen.getByRole('tab', { name: /Grok CLI/i }));
+ fireEvent.click(screen.getByLabelText(/Enable Grok Imagegen/i));
+ fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalled());
+ const patch = updateSettings.mock.calls[0][0];
+ expect(patch.imageGen.grok.enabled).toBe(false);
+ expect(patch.imageGen.mode).toBe('local');
+ });
+});
diff --git a/client/src/lib/imageGenBackends.js b/client/src/lib/imageGenBackends.js
index db45ac6c29..2394e5eacc 100644
--- a/client/src/lib/imageGenBackends.js
+++ b/client/src/lib/imageGenBackends.js
@@ -1,6 +1,6 @@
-import { Cpu, Terminal, Cloud } from 'lucide-react';
+import { Cpu, Terminal, Cloud, Sparkles } from 'lucide-react';
-export const IMAGE_GEN_MODE = Object.freeze({ LOCAL: 'local', CODEX: 'codex', EXTERNAL: 'external' });
+export const IMAGE_GEN_MODE = Object.freeze({ LOCAL: 'local', CODEX: 'codex', GROK: 'grok', EXTERNAL: 'external' });
// Shipped default Codex reasoning-effort level — the client mirror of the
// server's CODEX_IMAGEGEN_DEFAULT_EFFORT (server/services/imageGen/modes.js).
@@ -9,22 +9,28 @@ export const IMAGE_GEN_MODE = Object.freeze({ LOCAL: 'local', CODEX: 'codex', EX
// this default rather than showing a blank.
export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';
+// Client mirror of the server's GROK_ASPECT_RATIOS (imageGen/grok.js) — the
+// aspect ratios grok's image_gen/image_edit tools accept, offered as the
+// default-ratio picker in Settings → Image Gen → Grok.
+export const GROK_ASPECT_RATIOS = Object.freeze(['1:1', '16:9', '9:16', '4:3', '3:4', '3:2', '2:3']);
+
const META = {
[IMAGE_GEN_MODE.LOCAL]: { label: 'Local', icon: Cpu },
[IMAGE_GEN_MODE.CODEX]: { label: 'Codex', icon: Terminal },
+ [IMAGE_GEN_MODE.GROK]: { label: 'Grok', icon: Sparkles },
[IMAGE_GEN_MODE.EXTERNAL]: { label: 'External', icon: Cloud },
};
// 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]);
+export const I2I_CAPABLE_MODES = Object.freeze([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
// True when a mode can run image-to-image.
export const isI2iCapableMode = (mode) => I2I_CAPABLE_MODES.includes(mode);
// Pick the best available i2i backend from a list of `{ id }` backends,
-// preferring local (its form exposes strength + LoRAs), else codex. Returns
-// null when neither is installed.
+// preferring local (its form exposes strength + LoRAs), else codex, else grok.
+// Returns null when none is installed.
export function pickI2iMode(backends) {
for (const mode of I2I_CAPABLE_MODES) {
if (backends.some((b) => b.id === mode)) return mode;
@@ -39,6 +45,8 @@ export function deriveAvailableBackends(settings, { excludeExternal = false } =
out.push({ id: IMAGE_GEN_MODE.LOCAL, ...META[IMAGE_GEN_MODE.LOCAL] });
if (ig.codex?.enabled === true)
out.push({ id: IMAGE_GEN_MODE.CODEX, ...META[IMAGE_GEN_MODE.CODEX] });
+ if (ig.grok?.enabled === true)
+ out.push({ id: IMAGE_GEN_MODE.GROK, ...META[IMAGE_GEN_MODE.GROK] });
if (!excludeExternal && (ig.external?.sdapiUrl || ig.sdapiUrl || '').trim())
out.push({ id: IMAGE_GEN_MODE.EXTERNAL, ...META[IMAGE_GEN_MODE.EXTERNAL] });
return out;
diff --git a/client/src/lib/imageGenBackends.test.js b/client/src/lib/imageGenBackends.test.js
index 23a5b6e5ce..4631b4b9c8 100644
--- a/client/src/lib/imageGenBackends.test.js
+++ b/client/src/lib/imageGenBackends.test.js
@@ -8,10 +8,11 @@ import {
} from './imageGenBackends';
describe('I2I_CAPABLE_MODES / isI2iCapableMode', () => {
- it('treats local and codex as i2i-capable, external as not', () => {
- expect(I2I_CAPABLE_MODES).toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX]);
+ it('treats local, codex, and grok as i2i-capable, external as not', () => {
+ expect(I2I_CAPABLE_MODES).toEqual([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
expect(isI2iCapableMode(IMAGE_GEN_MODE.LOCAL)).toBe(true);
expect(isI2iCapableMode(IMAGE_GEN_MODE.CODEX)).toBe(true);
+ expect(isI2iCapableMode(IMAGE_GEN_MODE.GROK)).toBe(true);
expect(isI2iCapableMode(IMAGE_GEN_MODE.EXTERNAL)).toBe(false);
expect(isI2iCapableMode(undefined)).toBe(false);
});
diff --git a/client/src/lib/imageGenResolutions.js b/client/src/lib/imageGenResolutions.js
index 19fd54347b..8652c9c7ad 100644
--- a/client/src/lib/imageGenResolutions.js
+++ b/client/src/lib/imageGenResolutions.js
@@ -105,6 +105,10 @@ const NATIVE_RUNNER_KEYS = new Set([
export const compatibilityKey = (mode, runner) => {
if (mode === IMAGE_GEN_MODE.CODEX) return 'codex';
+ // Grok's image tools are prompt/aspect-ratio driven like codex — width and
+ // height are hints mapped to the nearest supported ratio, so it shares the
+ // codex preset list rather than getting its own compat key.
+ if (mode === IMAGE_GEN_MODE.GROK) return 'codex';
if (mode === IMAGE_GEN_MODE.EXTERNAL) return 'external';
if (NATIVE_RUNNER_KEYS.has(runner)) return runner;
return 'flux1';
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index d776d669a3..a701f581d5 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -224,7 +224,8 @@ export default function ImageGen() {
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;
+ const isGrokMode = effectiveMode === IMAGE_GEN_MODE.GROK;
+ const isAsyncMode = isLocalMode || isCodexMode || isGrokMode;
// 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);
@@ -292,9 +293,10 @@ export default function ImageGen() {
external: resolveCleanersFromConfig(s?.imageGen?.external, IMAGE_GEN_MODE.EXTERNAL),
local: resolveCleanersFromConfig(s?.imageGen?.local, IMAGE_GEN_MODE.LOCAL),
codex: resolveCleanersFromConfig(s?.imageGen?.codex, IMAGE_GEN_MODE.CODEX),
+ grok: resolveCleanersFromConfig(s?.imageGen?.grok, IMAGE_GEN_MODE.GROK),
};
- const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA };
- const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise };
+ const c2 = { external: perMode.external.cleanC2PA, local: perMode.local.cleanC2PA, codex: perMode.codex.cleanC2PA, grok: perMode.grok.cleanC2PA };
+ const dn = { external: perMode.external.denoise, local: perMode.local.denoise, codex: perMode.codex.denoise, grok: perMode.grok.denoise };
const saved = s?.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
// If the user just disabled the currently-selected backend, fall
// through to the first viable one — a just-toggled provider should
@@ -609,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 && initImage.source == null && !prompt.trim();
+ const codexNeedsPrompt = (isCodexMode || isGrokMode) && 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
@@ -721,11 +723,11 @@ export default function ImageGen() {
// payload hits imageEdgeSchema.
const w = clampImageEdge(width);
const h = clampImageEdge(height);
- const payload = isCodexMode ? {
+ const payload = (isCodexMode || isGrokMode) ? {
prompt: composed.prompt,
negativePrompt: composed.negativePrompt || undefined,
width: w, height: h,
- mode: IMAGE_GEN_MODE.CODEX,
+ mode: isGrokMode ? IMAGE_GEN_MODE.GROK : IMAGE_GEN_MODE.CODEX,
cleanC2PA, denoise,
} : {
prompt: composed.prompt,
@@ -784,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 ? {} : {
+ const localOnlyMeta = (isCodexMode || isGrokMode) ? {} : {
steps: payload.steps ?? currentModel?.steps,
guidance: payload.guidance ?? currentModel?.guidance,
};
@@ -1064,7 +1066,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 === IMAGE_GEN_MODE.LOCAL ? 'mflux/local' : status.mode === IMAGE_GEN_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' : status.mode === IMAGE_GEN_MODE.GROK ? 'grok CLI' : 'external SD API')}</>
) : (
<>
<AlertTriangle className="w-3 h-3" />
@@ -1232,7 +1234,7 @@ export default function ImageGen() {
<button
type="submit"
disabled={notConnected || editImageMissing || codexNeedsPrompt}
- title={editImageMissing ? 'This image-edit model needs a source image — upload one below first' : codexNeedsPrompt ? 'Codex text-to-image needs a prompt — add one, or attach a source image to edit' : undefined}
+ 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}
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'}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 5e64c1b45c..3d91fd8879 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -863,6 +863,21 @@ export const locationSettingsSchema = z.object({
{ message: 'Provide both lat and lon, or neither.' },
);
+// Grok Imagegen settings slice (`imageGen.grok`) — the Grok Build CLI backend
+// (#2859). No model/effort knobs: grok's image tools run on xAI's fixed image
+// backend, so only the enable gate, binary path, default aspect ratio, and
+// per-mode cleaner flags are stored. `''` sentinels from the UI preprocess to
+// undefined (same convention as other CLI provider slices); aspectRatio is
+// constrained to the `N:M` shape the grok tool accepts so a hand-edited
+// settings.json can't inject arbitrary prompt text.
+export const imageGenGrokSettingsSchema = z.object({
+ enabled: z.boolean().optional(),
+ grokPath: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().max(500).optional()),
+ aspectRatio: z.preprocess((v) => (v === '' ? undefined : v), z.string().trim().regex(/^\d{1,2}:\d{1,2}$/, 'aspect ratio must look like 16:9').optional()),
+ cleanC2PA: z.boolean().optional(),
+ denoise: z.boolean().optional(),
+});
+
// Provider-agnostic embeddings settings. `provider: 'none'` is the default and
// makes embedText() a no-op — rows persist without an embedding and a future
// admin "Re-embed missing" action backfills. Model is optional so the user can
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 73b6be7cf5..e148cb8087 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -418,6 +418,30 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
});
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 }));
+ }
if (mode === IMAGE_GEN_MODE.LOCAL) {
const py = settings.imageGen?.local?.pythonPath || null;
// Pre-validate config: mflux models need pythonPath, FLUX.2 doesn't
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index b365a51d81..a5cbb591c2 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -16,8 +16,9 @@ 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'],
+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok' },
+ IMAGE_GEN_MODES: ['external', 'local', 'codex', 'grok'],
+ CLOUD_IMAGE_GEN_MODES: ['codex', 'grok'],
// Mirror the real precedence by delegating to the same helper the prod
// resolver uses — keeps test mock and prod in lock-step automatically.
// Legacy `autoClean: true` no longer carries into denoise (lossy, opt-in only).
@@ -719,6 +720,62 @@ describe('Image Gen Routes', () => {
expect(response.body.error).toMatch(/disabled/i);
expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
});
+
+ it('grok mode enqueues through mediaJobQueue with the saved grok params', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'grok', grok: { enabled: true, grokPath: '/usr/local/bin/grok', aspectRatio: '16:9' } },
+ });
+ mediaJobQueue.enqueueJob.mockReturnValueOnce({ jobId: 'queued-grok-001', position: 1, status: 'queued' });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'a tavern at dusk' });
+
+ expect(response.status).toBe(200);
+ expect(response.body.status).toBe('queued');
+ expect(response.body.mode).toBe('grok');
+ expect(response.body.jobId).toBe('queued-grok-001');
+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'image',
+ params: expect.objectContaining({
+ mode: 'grok',
+ grokPath: '/usr/local/bin/grok',
+ aspectRatio: '16:9',
+ prompt: 'a tavern at dusk',
+ }),
+ }));
+ // Synchronous generateImage MUST NOT be called in grok mode either —
+ // the queue takes ownership.
+ expect(imageGen.generateImage).not.toHaveBeenCalled();
+ });
+
+ it('grok mode with disabled toggle returns 400 GROK_IMAGEGEN_DISABLED', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'grok', grok: { enabled: false } },
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: 'a fox' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toMatch(/disabled/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('rejects a Grok text-to-image request with no prompt and no init image (synchronous 400)', async () => {
+ getSettings.mockResolvedValueOnce({
+ imageGen: { mode: 'grok', grok: { enabled: true } },
+ });
+
+ const response = await request(app)
+ .post('/api/image-gen/generate')
+ .send({ prompt: '' });
+
+ expect(response.status).toBe(400);
+ expect(response.body.error).toMatch(/prompt is required/i);
+ expect(mediaJobQueue.enqueueJob).not.toHaveBeenCalled();
+ });
});
describe('POST /api/image-gen/avatar', () => {
diff --git a/server/routes/pipeline/covers.js b/server/routes/pipeline/covers.js
index b6400fc5a8..0b04166ab9 100644
--- a/server/routes/pipeline/covers.js
+++ b/server/routes/pipeline/covers.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]).optional(),
+ mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).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.js
index 8bf0388747..bcd2318a96 100644
--- a/server/routes/pipeline/issues.js
+++ b/server/routes/pipeline/issues.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]).optional(),
+ imageMode: z.enum(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).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]).optional(),
+ mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).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]).optional(),
+ mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).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]).optional(),
+ mode: z.enum([IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]).optional(),
modelId: z.string().trim().max(64).optional(),
width: imageEdgeSchema,
height: imageEdgeSchema,
diff --git a/server/routes/sdapi.js b/server/routes/sdapi.js
index 0847a2eaa4..783983aaa7 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, IMAGE_GEN_MODE } from '../services/imageGen/index.js';
+import { generateImage, getMode, getActiveJob, IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } 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';
@@ -168,14 +168,14 @@ router.post('/txt2img', asyncHandler(async (req, res) => {
modelId = sd_model_checkpoint.replace(/^portos-local-/, '').split(' ')[0];
}
- // In local + codex modes generateImage returns the moment the child is
+ // In local + cloud-CLI (codex/grok) modes generateImage returns the moment the child is
// spawned — the file isn't on disk yet. Subscribe to the completion event
// BEFORE calling generateImage so a fast job (cached weights, low steps)
// can't fire before we attach. External mode awaits internally and the
// file is on disk by the time generateImage resolves, so the wait is a
// no-op there.
const mode = await getMode();
- const isAsyncMode = mode === IMAGE_GEN_MODE.LOCAL || mode === IMAGE_GEN_MODE.CODEX;
+ const isAsyncMode = mode === IMAGE_GEN_MODE.LOCAL || CLOUD_IMAGE_GEN_MODES.includes(mode);
const localWait = isAsyncMode
? createCompletionWaiter()
: { register: () => {}, promise: Promise.resolve(), cleanup: () => {} };
diff --git a/server/routes/sdapi.test.js b/server/routes/sdapi.test.js
index b7277d5483..969d339431 100644
--- a/server/routes/sdapi.test.js
+++ b/server/routes/sdapi.test.js
@@ -10,7 +10,8 @@ vi.mock('../services/imageGen/index.js', () => ({
generateImage: vi.fn(),
getMode: vi.fn(),
getActiveJob: vi.fn(),
- IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },
+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok' },
+ CLOUD_IMAGE_GEN_MODES: ['codex', 'grok'],
local: { listImageModels: vi.fn(() => [{ id: 'dev', name: 'Flux 1 Dev' }]) },
}));
diff --git a/server/routes/settings.js b/server/routes/settings.js
index 67181da788..8a73d1d41b 100644
--- a/server/routes/settings.js
+++ b/server/routes/settings.js
@@ -10,7 +10,7 @@ import {
} from '../services/mediaJobQueue/index.js';
import { asyncHandler } from '../lib/errorHandler.js';
import { isPlainObject } from '../lib/objects.js';
-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, validateRequest } from '../lib/validation.js';
+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, validateRequest } from '../lib/validation.js';
const router = Router();
@@ -205,6 +205,13 @@ router.put('/', asyncHandler(async (req, res) => {
if (req.body?.seriesAutopilot !== undefined) {
validateRequest(seriesAutopilotSettingsSchema.partial(), req.body.seriesAutopilot);
}
+ // Grok Imagegen settings slice (#2859) — validate when present so a malformed
+ // save can't write a bad aspect ratio (which lands verbatim in the grok
+ // prompt) or a non-boolean enabled gate to disk. The imageGen parent stays
+ // polymorphic; only the grok sub-slice has a schema here.
+ if (req.body?.imageGen?.grok !== undefined) {
+ validateRequest(imageGenGrokSettingsSchema.partial(), req.body.imageGen.grok);
+ }
// Install-level Layered Intelligence settings (#2515) — validate the slice when
// present so a malformed `trustShellSources` can't persist and silently unlock
// full-shell custom `cmd` sources install-wide.
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index 963cd56916..35095d9b6a 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -81,3 +81,47 @@ describe('Settings routes — apiAccess slice', () => {
expect(res.body.apiAccess.sdapi.exposed).toBe(true);
});
});
+
+describe('Settings routes — imageGen.grok slice (#2859)', () => {
+ beforeEach(() => {
+ store = {};
+ vi.clearAllMocks();
+ });
+
+ it('accepts a valid grok slice and persists it', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { grok: { enabled: true, grokPath: '/usr/local/bin/grok', aspectRatio: '16:9' } } });
+ expect(res.status).toBe(200);
+ expect(res.body.imageGen.grok.enabled).toBe(true);
+ expect(res.body.imageGen.grok.aspectRatio).toBe('16:9');
+ });
+
+ it('accepts empty-string UI sentinels for path and ratio', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { grok: { enabled: false, grokPath: '', aspectRatio: '' } } });
+ expect(res.status).toBe(200);
+ });
+
+ it('rejects a malformed aspect ratio (would land verbatim in the grok prompt)', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { grok: { aspectRatio: '16:9; rm -rf /' } } });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a non-boolean enabled gate', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { grok: { enabled: 'yes' } } });
+ expect(res.status).toBe(400);
+ });
+
+ it('leaves an imageGen patch without a grok key unvalidated (polymorphic parent)', async () => {
+ const res = await request(buildApp())
+ .put('/api/settings')
+ .send({ imageGen: { mode: 'local' } });
+ expect(res.status).toBe(200);
+ });
+});
diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.js
index 44ea896d2f..578d7b2aa4 100644
--- a/server/services/creativeDirector/firstPassGen.js
+++ b/server/services/creativeDirector/firstPassGen.js
@@ -82,6 +82,16 @@ async function resolveQueueModeParams() {
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 },
+ };
+ }
if (mode === IMAGE_GEN_MODE.LOCAL) {
// We pass no modelId, so the worker renders with its default ('dev') model —
// an mflux model that REQUIRES a configured pythonPath (the imageGen route
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 9751e683aa..8c970a2c33 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -122,8 +122,10 @@ 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.
-const describeFidelity = (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';
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
new file mode 100644
index 0000000000..85536a52f0
--- /dev/null
+++ b/server/services/imageGen/grok.js
@@ -0,0 +1,373 @@
+/**
+ * Image Gen — xAI Grok Build CLI provider.
+ *
+ * Routes image generation through the user's locally-installed `grok` CLI
+ * (Grok Build). Grok ships built-in media tools — `image_gen` (text → image)
+ * and `image_edit` (source image + instruction → image) — guided by its
+ * bundled `imagine` skill, and runs them against the user's logged-in Grok
+ * session. No XAI_API_KEY required.
+ *
+ * Wire format: `grok --output-format plain --permission-mode bypassPermissions
+ * --prompt-file /dev/stdin` (built by `ensureGrokHeadlessArgs` in
+ * server/lib/grok.js; the /dev/stdin sentinel is rewritten to a temp file on
+ * Windows by `prepareGrokPromptFile`). Unlike Codex — which writes to a fixed
+ * `~/.codex/generated_images/<session-id>/` dir PortOS has to banner-scrape —
+ * grok is a general coding agent that can be *told where to write the file*:
+ * the prompt directs it to save the generated PNG to a staging path PortOS
+ * chose, and the post-exit handler just reads that file back.
+ *
+ * The user must explicitly enable this provider in Settings → Image Gen
+ * (mirrors the Codex gate — it spends the user's Grok quota). When disabled
+ * the dispatcher rejects up front; this module assumes it's enabled by the
+ * time generateImage() is called.
+ */
+
+import { spawn } from 'child_process';
+import { copyFile, stat, unlink } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { randomUUID } from 'crypto';
+import { atomicWrite, ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';
+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 { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
+import { IMAGE_GEN_MODE } from './modes.js';
+import { describeFidelity } from './codex.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
+// progress signal to short-circuit on, and a queued/over-subscribed session
+// can stall. Env-overridable for power users who want a tighter cap. Keep in
+// rough sync with the mediaJobQueue cloud-lane watchdog (WATCHDOG_CODEX_MS)
+// so the queue's watchdog and the child's wall-clock cap fire on a similar
+// budget.
+const GROK_TIMEOUT_MS = (() => {
+ const n = Number(process.env.GROK_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : 20 * 60 * 1000;
+})();
+
+const DEFAULT_BIN = 'grok';
+
+// Aspect ratios grok's image_gen/image_edit tools accept. Width/height from
+// 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']);
+
+// 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).
+export function deriveAspectRatio(width, height) {
+ const w = Number(width);
+ const h = Number(height);
+ if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return null;
+ 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);
+ if (delta < bestDelta) {
+ best = ratio;
+ bestDelta = delta;
+ }
+ }
+ return best;
+}
+
+// Per-job state — keyed by jobId so multiple grok renders can run in parallel
+// under the mediaJobQueue's cloud lane. Same client shape as imageGen/codex.js
+// so attachSseClient/broadcastSse just work.
+const jobs = new Map();
+const activeProcs = new Map();
+const activeJobs = new Map();
+
+// Returns the most-recently-started job — used by status surfaces and the
+// settings test-render; not safe for cancel routing under parallel use.
+export const getActiveJob = () => {
+ const entries = [...activeJobs.values()];
+ return entries.length ? entries[entries.length - 1] : null;
+};
+
+export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
+
+const sigtermWithEscalation = (id, proc) =>
+ killWithEscalation(proc, { label: 'grok child', delayMs: 5000, stillRunning: () => activeProcs.get(id) === proc });
+
+// Cancel one specific grok render. jobId is required — with parallel renders
+// an "anonymous cancel" would nuke every in-flight render. Use `cancelAll()`
+// for the dispatcher's "stop everything" path.
+export const cancel = (jobId) => {
+ if (!jobId) {
+ throw new Error("grok.cancel requires a jobId — use grok.cancelAll() to terminate every in-flight render");
+ }
+ const proc = activeProcs.get(jobId);
+ if (!proc) return false;
+ sigtermWithEscalation(jobId, proc);
+ return true;
+};
+
+// Bulk terminate every in-flight grok render. Only used by the imageGen
+// dispatcher's "cancel everything" route.
+export const cancelAll = () => {
+ const entries = [...activeProcs.entries()];
+ if (entries.length === 0) return false;
+ for (const [id, proc] of entries) sigtermWithEscalation(id, proc);
+ return true;
+};
+
+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".
+ 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' });
+ });
+ });
+}
+
+// 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 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}"`;
+}
+
+// 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 general
+// coding agent, so the prompt is explicit about the tool, the save path, and
+// staying out of everything else.
+export function buildGrokPrompt({ prompt, negativePrompt, aspectRatio, stagingPath, initImagePath, initImageStrength }) {
+ const avoid = negativePrompt?.trim() ? `\nAvoid: ${negativePrompt.trim()}` : '';
+ const ratio = aspectRatio ? `\nUse aspect_ratio "${aspectRatio}".` : '';
+ const task = initImagePath
+ ? `Use your built-in image_edit tool to transform the source image at ${initImagePath} — ${describeFidelity(initImageStrength)}.\nEdit instruction: ${prompt.trim()}${avoid}`
+ : `Use your built-in image_gen tool to generate exactly one image.\nImage prompt: ${prompt.trim()}${avoid}`;
+ return `${task}${ratio}\nSave the generated image as a PNG file at exactly this path: ${stagingPath}\nDo not create any other files, do not modify any code, and do not run any other tools beyond what is needed to generate the image and write it to that path. When the file is written, you are done.`;
+}
+
+// `initImageStrength` maps to a fidelity phrase (grok's image_edit has no
+// numeric denoise knob, same constraint as codex).
+export async function generateImage({
+ grokPath, aspectRatio, prompt = '', width, height, negativePrompt,
+ initImagePath, initImageStrength,
+ jobId: providedJobId = null,
+ cleanC2PA = false,
+ denoise = false,
+}) {
+ await ensureDir(PATHS.images);
+
+ // Defense-in-depth: re-anchor the init image to the allowed input roots so
+ // no caller can point grok's image_edit at an arbitrary local file. Mirrors
+ // imageGen/codex.js.
+ const validInitImagePath = (initImagePath && typeof initImagePath === 'string')
+ ? resolveImageInputPath(initImagePath)
+ : null;
+
+ // An empty prompt is fine when editing an init image; a pure text-to-image
+ // grok render still needs one.
+ if (!validInitImagePath && !prompt?.trim()) {
+ throw new ServerError('Prompt is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+
+ const jobId = providedJobId || randomUUID();
+ const filename = `${jobId}.png`;
+ const outputPath = join(PATHS.images, filename);
+ // Grok writes to a tmp staging path, not straight into the gallery — a
+ // failed/partial run must never leave junk where the gallery scanner or a
+ // concurrent client can see it. The success path copies it over.
+ const stagingPath = join(tmpdir(), `portos-grok-${jobId}.png`);
+
+ // Caller dimensions win (mapped to the closest supported ratio); the saved
+ // per-provider default applies when no dimensions were sent; otherwise the
+ // tool's own default. Validate the saved value against the known ratios so
+ // a hand-edited settings.json can't inject arbitrary prompt text.
+ const derived = deriveAspectRatio(width, height);
+ const configured = GROK_ASPECT_RATIOS.includes(aspectRatio) ? aspectRatio : null;
+ const effectiveRatio = derived || configured;
+
+ const fullPrompt = buildGrokPrompt({
+ prompt, negativePrompt, aspectRatio: effectiveRatio, stagingPath,
+ initImagePath: validInitImagePath, initImageStrength,
+ });
+
+ const bin = grokPath || DEFAULT_BIN;
+ // No model arg — grok's image tools run on xAI's fixed image backend and
+ // the agent model is whatever the local `grok` install defaults to (see
+ // server/lib/grok.js: PortOS does not pick a grok model).
+ const baseArgs = ensureGrokHeadlessArgs([], null);
+ const { args, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(baseArgs, fullPrompt);
+
+ const meta = {
+ id: jobId, prompt: prompt.trim(), negativePrompt: negativePrompt || '',
+ width: width ? Number(width) : null, height: height ? Number(height) : null,
+ filename, mode: IMAGE_GEN_MODE.GROK,
+ ...(effectiveRatio ? { aspectRatio: effectiveRatio } : {}),
+ createdAt: new Date().toISOString(),
+ };
+ const job = { ...meta, clients: [], status: 'running' };
+ jobs.set(jobId, job);
+
+ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] grok: ${prompt.slice(0, 60)}…`);
+ imageGenEvents.emit('started', { generationId: jobId, totalSteps: 1 });
+ activeJobs.set(jobId, { ...meta, generationId: jobId, totalSteps: 1, step: 0, progress: 0, currentImage: null });
+ broadcastSse(job, { type: 'status', message: 'Spawning grok…' });
+
+ // generateImage returns a job descriptor synchronously; the actual grok
+ // child runs out-of-band so the HTTP response can ship while the client
+ // attaches to the per-job SSE stream (mirrors codex.js/local.js).
+ runGrok(job, jobId, bin, args, {
+ useStdin, fullPrompt, cleanupPromptFile, stagingPath, outputPath, filename, meta, cleanC2PA, denoise,
+ }).catch((err) => {
+ console.log(`❌ grok run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
+ });
+
+ return {
+ jobId, filename, path: `/data/images/${filename}`, generationId: jobId,
+ mode: IMAGE_GEN_MODE.GROK,
+ // Async callers gate UI state on `status`; without 'running' they flip
+ // to 'done' before the PNG lands. SSE / socket 'completed' fires later.
+ status: 'running',
+ };
+}
+
+async function runGrok(job, jobId, bin, args, {
+ useStdin, fullPrompt, cleanupPromptFile, stagingPath, outputPath, filename, meta, cleanC2PA = false, denoise = false,
+}) {
+ const proc = spawn(bin, args, { shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ activeProcs.set(jobId, proc);
+
+ if (useStdin) {
+ // POSIX: grok reads the prompt via --prompt-file /dev/stdin. EPIPE fires
+ // when the child dies before consuming stdin — the close handler reports
+ // the real failure, so just swallow the write error.
+ proc.stdin.on('error', () => {});
+ proc.stdin.write(fullPrompt);
+ proc.stdin.end();
+ }
+
+ let stdoutTail = '';
+ const STDOUT_TAIL_BYTES = 8 * 1024;
+ let stderrTail = '';
+ const STDERR_TAIL_BYTES = 32 * 1024;
+ 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);
+ }
+ }, GROK_TIMEOUT_MS);
+
+ proc.on('error', (err) => {
+ clearTimeout(timeoutTimer);
+ cleanupPromptFile();
+ finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ });
+
+ proc.stdout.on('data', (chunk) => {
+ stdoutTail += chunk.toString();
+ if (stdoutTail.length > STDOUT_TAIL_BYTES) stdoutTail = stdoutTail.slice(-STDOUT_TAIL_BYTES);
+ broadcastSse(job, { type: 'status', message: 'Running…' });
+ });
+
+ proc.stderr.on('data', (chunk) => {
+ stderrTail += chunk.toString();
+ if (stderrTail.length > STDERR_TAIL_BYTES) stderrTail = stderrTail.slice(-STDERR_TAIL_BYTES);
+ });
+
+ proc.on('close', async (code, signal) => {
+ clearTimeout(timeoutTimer);
+ cleanupPromptFile();
+ // EventEmitter doesn't await async listeners — without this try/catch,
+ // a throw from the harvest/copy would surface as an unhandled rejection
+ // and the job would be stuck in 'running' forever with no SSE error.
+ try {
+ if (code !== 0) {
+ const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
+ const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
+ return finalizeError(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);
+ }
+ // Grok writes the file during the turn; empirically it's on disk by
+ // exit, but poll a few seconds in case of flush lag on slow disks.
+ const harvested = await harvestStagedImage(stagingPath, 5000);
+ if (!harvested) {
+ return finalizeError(job, jobId, proc, noImageReason(stdoutTail));
+ }
+ 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(() => {});
+ // Cleaners run BEFORE the SSE complete + completed events so
+ // subscribers see the cleaned bytes.
+ await autoCleanGeneratedImage({ cleanC2PA, denoise, pngPath: outputPath, sidecarPath: sidecar, mode: IMAGE_GEN_MODE.GROK });
+ job.status = 'complete';
+ if (activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ activeJobs.delete(jobId);
+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (grok)`);
+ const result = { filename, path: `/data/images/${filename}` };
+ broadcastSse(job, { type: 'complete', result });
+ imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename });
+ closeJobAfterDelay(jobs, jobId);
+ } catch (err) {
+ finalizeError(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`);
+ }
+ });
+}
+
+// `proc` is the child this finalize belongs to — only clear module-scoped
+// state when it still belongs to *this* job (a late finalize from a stale run
+// must not wipe a newer active job).
+const finalizeError = (job, jobId, proc, reason) => {
+ // Idempotent — spawn failures fire 'error' AND a follow-up 'close'.
+ if (job.status === 'error' || job.status === 'complete') return;
+ if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
+ job.status = 'error';
+ activeJobs.delete(jobId);
+ console.log(`❌ grok image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ imageGenEvents.emit('failed', { generationId: jobId, error: reason });
+ closeJobAfterDelay(jobs, jobId);
+};
+
+// Poll for the directed output file until it exists non-empty or timeoutMs
+// elapses. Returns true when the file is ready.
+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;
+ }
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return false;
+}
+
+// Test-only handles (mirrors codex.js's carve-out).
+export const _internals = {
+ harvestStagedImage,
+ deriveAspectRatio,
+ buildGrokPrompt,
+};
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
new file mode 100644
index 0000000000..04dd72bc5a
--- /dev/null
+++ b/server/services/imageGen/grok.test.js
@@ -0,0 +1,322 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { mkdir, writeFile, rm, readFile } from 'fs/promises';
+import { existsSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { EventEmitter } from 'events';
+
+// Spawn mock — capture every spawn call so tests can assert args, drive
+// stdout/stderr, capture the stdin-delivered prompt, and trigger the close
+// event whenever they want. Grok reads the prompt via `--prompt-file
+// /dev/stdin`, so unlike codex the prompt is captured from stdin writes,
+// not argv.
+const spawnCalls = [];
+const makeFakeChild = () => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.stdin = { written: '', on: vi.fn(), write: vi.fn(function (s) { child.stdin.written += s; }), end: vi.fn() };
+ child.kill = vi.fn();
+ child.exitCode = null;
+ child.signalCode = null;
+ return child;
+};
+vi.mock('child_process', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ spawn: vi.fn((bin, args) => {
+ const child = makeFakeChild();
+ spawnCalls.push({ bin, args, child });
+ return child;
+ }),
+ };
+});
+
+// Stable PATHS.images under a test dir so the success-path copyFile lands in
+// a predictable place we can read back (mirrors codex.test.js).
+const TEST_ROOT = join(tmpdir(), `portos-grok-test-${process.pid}-${Date.now()}`);
+const FAKE_IMAGES_DIR = join(TEST_ROOT, 'data-images');
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ actual.PATHS.images = FAKE_IMAGES_DIR;
+ return {
+ ...actual,
+ ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
+ };
+});
+
+const grok = await import('./grok.js');
+const { imageGenEvents } = await import('../imageGenEvents.js');
+
+const flush = () => new Promise((r) => setImmediate(r));
+const stagingPathFor = (jobId) => join(tmpdir(), `portos-grok-${jobId}.png`);
+const promptOf = (i = 0) => spawnCalls[i].child.stdin.written;
+const closeChild = async (i = 0, code = 1) => {
+ spawnCalls[i].child.exitCode = code;
+ spawnCalls[i].child.emit('close', code, null);
+ await flush();
+};
+
+beforeEach(async () => {
+ spawnCalls.length = 0;
+ imageGenEvents.removeAllListeners();
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+ await mkdir(TEST_ROOT, { recursive: true });
+});
+
+afterEach(async () => {
+ await rm(TEST_ROOT, { recursive: true, force: true }).catch(() => {});
+});
+
+describe('grok provider — deriveAspectRatio', () => {
+ it('maps common dimension pairs to the closest supported ratio', () => {
+ expect(grok.deriveAspectRatio(1024, 1024)).toBe('1:1');
+ expect(grok.deriveAspectRatio(1920, 1080)).toBe('16:9');
+ expect(grok.deriveAspectRatio(1080, 1920)).toBe('9:16');
+ expect(grok.deriveAspectRatio(1024, 1536)).toBe('2:3');
+ expect(grok.deriveAspectRatio(1536, 1024)).toBe('3:2');
+ });
+
+ it('returns null for absent or invalid dimensions', () => {
+ expect(grok.deriveAspectRatio(undefined, undefined)).toBe(null);
+ expect(grok.deriveAspectRatio(0, 512)).toBe(null);
+ expect(grok.deriveAspectRatio('nope', 512)).toBe(null);
+ });
+});
+
+describe('grok provider — generateImage', () => {
+ it('spawns grok with headless args and delivers the prompt over stdin', async () => {
+ const job = await grok.generateImage({ prompt: 'a small fox' });
+ expect(job.mode).toBe('grok');
+ expect(job.filename).toMatch(/^[0-9a-f-]{36}\.png$/);
+ expect(job.status).toBe('running');
+ expect(spawnCalls.length).toBe(1);
+ const { bin, args } = spawnCalls[0];
+ expect(bin).toBe('grok');
+ // ensureGrokHeadlessArgs contract: plain output, bypassed permissions,
+ // prompt via /dev/stdin (POSIX), no --model pin.
+ expect(args).toEqual(expect.arrayContaining(['--output-format', 'plain']));
+ expect(args).toEqual(expect.arrayContaining(['--permission-mode', 'bypassPermissions']));
+ expect(args).toEqual(expect.arrayContaining(['--prompt-file', '/dev/stdin']));
+ expect(args).not.toContain('--model');
+ // The agent prompt names the tool, the image prompt, and the directed path.
+ const prompt = promptOf();
+ expect(prompt).toContain('image_gen');
+ expect(prompt).toContain('a small fox');
+ expect(prompt).toContain(stagingPathFor(job.jobId));
+ await closeChild();
+ });
+
+ it('derives the aspect ratio from width/height and puts it in the prompt', async () => {
+ await grok.generateImage({ prompt: 'a fox', width: 1920, height: 1080 });
+ expect(promptOf()).toContain('aspect_ratio "16:9"');
+ await closeChild();
+ });
+
+ it('falls back to the configured default ratio when no dimensions are sent', async () => {
+ await grok.generateImage({ prompt: 'a fox', aspectRatio: '9:16' });
+ expect(promptOf()).toContain('aspect_ratio "9:16"');
+ await closeChild();
+ });
+
+ it('ignores an unsupported configured ratio (no injection into the prompt)', async () => {
+ await grok.generateImage({ prompt: 'a fox', aspectRatio: '99:1; rm -rf /' });
+ expect(promptOf()).not.toContain('99:1');
+ expect(promptOf()).not.toContain('aspect_ratio');
+ await closeChild();
+ });
+
+ it('honors grokPath override (custom binary)', async () => {
+ await grok.generateImage({ prompt: 'a fox', grokPath: '/opt/custom/grok' });
+ expect(spawnCalls[0].bin).toBe('/opt/custom/grok');
+ await closeChild();
+ });
+
+ it('appends the negative prompt as an Avoid line', async () => {
+ await grok.generateImage({ prompt: 'a fox', negativePrompt: 'watermark, text' });
+ expect(promptOf()).toContain('Avoid: watermark, text');
+ await closeChild();
+ });
+
+ it('rejects when prompt is empty and there is no init image', async () => {
+ await expect(grok.generateImage({ prompt: ' ' })).rejects.toThrow(/Prompt is required/);
+ });
+
+ it('switches to image_edit and the fidelity phrase for an init image', async () => {
+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });
+ await writeFile(join(FAKE_IMAGES_DIR, 'proof.png'), 'fake');
+ await grok.generateImage({ prompt: 'cover art', initImagePath: 'proof.png', initImageStrength: 0.2 });
+ const prompt = promptOf();
+ expect(prompt).toContain('image_edit');
+ expect(prompt).toContain(join(FAKE_IMAGES_DIR, 'proof.png'));
+ // Low strength → composition-preserving fidelity phrase (shared with codex).
+ expect(prompt).toMatch(/preserve composition/i);
+ expect(prompt).toContain('cover art');
+ await closeChild();
+ });
+
+ it('drops an initImagePath that escapes the gallery (defense-in-depth)', async () => {
+ await grok.generateImage({ prompt: 'cover art', initImagePath: '/etc/passwd', initImageStrength: 0.2 });
+ const prompt = promptOf();
+ expect(prompt).not.toContain('image_edit');
+ expect(prompt).not.toContain('/etc/passwd');
+ await closeChild();
+ });
+
+ it('allows an empty prompt when editing an init image', async () => {
+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });
+ await writeFile(join(FAKE_IMAGES_DIR, 'editme.png'), 'fake');
+ await grok.generateImage({ prompt: '', initImagePath: 'editme.png' });
+ expect(promptOf()).toContain('image_edit');
+ await closeChild();
+ });
+
+ it('allows concurrent generations (parallel cloud lane)', async () => {
+ const a = await grok.generateImage({ prompt: 'one' });
+ const b = await grok.generateImage({ prompt: 'two' });
+ expect(a.jobId).not.toBe(b.jobId);
+ expect(spawnCalls.length).toBe(2);
+ await closeChild(0);
+ await closeChild(1);
+ });
+});
+
+describe('grok provider — directed-path harvest', () => {
+ it('copies the staged file into PATHS.images and emits completed', async () => {
+ const completedListener = vi.fn();
+ imageGenEvents.on('completed', completedListener);
+
+ const job = await grok.generateImage({ prompt: 'a fox' });
+ // Grok "writes" the directed staging file before the child exits.
+ const fakePngBytes = Buffer.from('fakepngbytes');
+ await writeFile(stagingPathFor(job.jobId), fakePngBytes);
+ await closeChild(0, 0);
+
+ const deadline = Date.now() + 3000;
+ while (Date.now() < deadline && completedListener.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+
+ expect(completedListener).toHaveBeenCalledTimes(1);
+ const finalPath = join(FAKE_IMAGES_DIR, job.filename);
+ expect(existsSync(finalPath)).toBe(true);
+ const written = await readFile(finalPath);
+ expect(Buffer.compare(written, fakePngBytes)).toBe(0);
+ // Staging file is cleaned up after the copy.
+ expect(existsSync(stagingPathFor(job.jobId))).toBe(false);
+ // Sidecar metadata exists too.
+ const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
+ expect(existsSync(sidecar)).toBe(true);
+ });
+
+ it('fails with the stdout narration when grok exits 0 but wrote no file', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await grok.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ child.stdout.emit('data', Buffer.from('I cannot generate that image.\n'));
+ await closeChild(0, 0);
+
+ // Wait out the harvest poll window (5s) plus a buffer.
+ const deadline = Date.now() + 8000;
+ while (Date.now() < deadline && failedListener.mock.calls.length === 0) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/I cannot generate that image/);
+ }, 12000);
+
+ it('fails with the stderr tail on a non-zero exit', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await grok.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ child.stderr.emit('data', Buffer.from('boom: auth expired\n'));
+ await closeChild(0, 1);
+
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/Exit code 1/);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/auth expired/);
+ });
+
+ it('fails cleanly when the binary cannot be spawned', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ await grok.generateImage({ prompt: 'a fox' });
+ const child = spawnCalls[0].child;
+ child.emit('error', new Error('ENOENT'));
+ await flush();
+
+ expect(failedListener).toHaveBeenCalledTimes(1);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/Failed to spawn grok/);
+ });
+});
+
+describe('grok provider — noImageReason', () => {
+ it('falls back to the enablement hint when grok said nothing usable', () => {
+ expect(grok.noImageReason('')).toMatch(/Enable Grok Imagegen/);
+ expect(grok.noImageReason('----\n12,345\n')).toMatch(/Enable Grok Imagegen/);
+ });
+
+ it('surfaces the last narration lines', () => {
+ expect(grok.noImageReason('working…\nThat prompt violates policy.\n')).toMatch(/violates policy/);
+ });
+});
+
+describe('grok provider — cancel', () => {
+ it('cancel() requires a jobId', () => {
+ expect(() => grok.cancel()).toThrow(/requires a jobId/);
+ });
+
+ it('cancel(jobId) SIGTERMs the matching child; cancelAll() sweeps every one', async () => {
+ const a = await grok.generateImage({ prompt: 'one' });
+ const b = await grok.generateImage({ prompt: 'two' });
+ expect(grok.cancel(a.jobId)).toBe(true);
+ expect(spawnCalls[0].child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(spawnCalls[1].child.kill).not.toHaveBeenCalled();
+ expect(grok.cancelAll()).toBe(true);
+ expect(spawnCalls[1].child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(grok.cancel(b.jobId)).toBe(true);
+ await closeChild(0);
+ await closeChild(1);
+ // Everything finished — nothing left to cancel.
+ expect(grok.cancel(a.jobId)).toBe(false);
+ expect(grok.cancelAll()).toBe(false);
+ });
+});
+
+describe('grok provider — checkConnection', () => {
+ it('reports connected with the parsed version on exit 0', async () => {
+ const p = grok.checkConnection({});
+ await flush();
+ const probe = spawnCalls[0];
+ expect(probe.bin).toBe('grok');
+ expect(probe.args).toEqual(['--version']);
+ probe.child.stdout.emit('data', Buffer.from('grok 0.2.7\n'));
+ probe.child.emit('close', 0, null);
+ const status = await p;
+ expect(status).toEqual({ connected: true, mode: 'grok', model: 'grok-cli 0.2.7' });
+ });
+
+ it('reports not-found when the spawn errors', async () => {
+ const p = grok.checkConnection({ grokPath: '/nope/grok' });
+ await flush();
+ spawnCalls[0].child.emit('error', new Error('ENOENT'));
+ const status = await p;
+ expect(status.connected).toBe(false);
+ expect(status.reason).toMatch(/not found/);
+ });
+
+ it('reports the exit code on a non-zero probe', async () => {
+ const p = grok.checkConnection({});
+ await flush();
+ spawnCalls[0].child.emit('close', 3, null);
+ const status = await p;
+ expect(status.connected).toBe(false);
+ expect(status.reason).toMatch(/exited 3/);
+ });
+});
diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.js
index 20b096461a..390014d502 100644
--- a/server/services/imageGen/index.js
+++ b/server/services/imageGen/index.js
@@ -18,20 +18,22 @@ 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 { IMAGE_GEN_MODE, IMAGE_GEN_MODES } from './modes.js';
+import * as grok from './grok.js';
+import { IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_IMAGE_GEN_MODES } from './modes.js';
// 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 };
+export { IMAGE_GEN_MODE, IMAGE_GEN_MODES, CLOUD_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;
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
@@ -64,6 +66,11 @@ export async function checkConnection({ mode: modeOverride } = {}) {
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 status = await external.checkConnection(sdapiUrl(s));
return { ...status, mode };
}
@@ -81,10 +88,11 @@ export async function generateImage(params) {
}
// Strip the dispatcher-only `mode` field — providers don't expect it.
delete normalized.mode;
- // i2i is supported by local (mflux/diffusers --image-path) and codex
- // (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.
+ // i2i is supported by local (mflux/diffusers --image-path), codex
+ // (gpt-image-2 image-edit via codex CLI's -i flag), and grok (image_edit).
+ // 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 === IMAGE_GEN_MODE.EXTERNAL && (normalized.initImagePath || normalized.initImageStrength != null)) {
delete normalized.initImagePath;
delete normalized.initImageStrength;
@@ -109,6 +117,18 @@ export async function generateImage(params) {
// 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 });
+ }
if (mode === IMAGE_GEN_MODE.LOCAL) {
return local.generateImage({ pythonPath: pythonPath(s), cleanC2PA, denoise, ...normalized });
}
@@ -150,7 +170,7 @@ export async function generateAvatar({ name, characterClass, prompt }) {
// Callers wanting all of them can read individual providers via the
// re-exports below.
export async function getActiveJob() {
- const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob()].filter(Boolean);
+ const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob(), grok.getActiveJob()].filter(Boolean);
if (!jobs.length) return null;
return jobs.sort((a, b) => {
const ta = a.createdAt ? Date.parse(a.createdAt) : 0;
@@ -165,22 +185,24 @@ export async function getActiveJob() {
export const attachSseClient = (jobId, res) => {
if (local.attachSseClient(jobId, res)) return true;
if (codex.attachSseClient(jobId, res)) return true;
+ if (grok.attachSseClient(jobId, res)) return true;
return false;
};
export const cancel = () => {
// The "stop everything" dispatcher — invoked by routes/imageGen.js's
// `/cancel` fallback when no specific jobId or queue entry is targeted.
- // local has at most one in-flight, codex can have N (parallel lane), so
- // codex's bulk variant is the right one here. Return whether anything
- // was actually cancelled — short-circuiting on the first hit would
- // orphan a codex job whenever local is also active.
+ // local has at most one in-flight, codex/grok can have N (parallel cloud
+ // lane), so their bulk variants are the right ones here. Return whether
+ // anything was actually cancelled — short-circuiting on the first hit
+ // would orphan a cloud job whenever local is also active.
const localCancelled = local.cancel();
const codexCancelled = codex.cancelAll();
- return localCancelled || codexCancelled;
+ const grokCancelled = grok.cancelAll();
+ return localCancelled || codexCancelled || grokCancelled;
};
// Re-exports so routes can hit a specific backend directly when the request
// is shape-specific (gallery, LoRAs). The dispatcher is for the generic
// generate/status flow used by all modes.
-export { local, external, codex };
+export { local, external, codex, grok };
diff --git a/server/services/imageGen/modes.js b/server/services/imageGen/modes.js
index 55fb0914f7..1363ee7c98 100644
--- a/server/services/imageGen/modes.js
+++ b/server/services/imageGen/modes.js
@@ -14,10 +14,18 @@ export const IMAGE_GEN_MODE = Object.freeze({
EXTERNAL: 'external',
LOCAL: 'local',
CODEX: 'codex',
+ GROK: 'grok',
});
export const IMAGE_GEN_MODES = Object.freeze(Object.values(IMAGE_GEN_MODE));
+// Cloud-CLI backends (codex `$imagegen`, grok `image_gen`) — each render
+// shells out to an external child that spends remote quota, not local GPU.
+// The mediaJobQueue routes these through its parallel cloud lane (they don't
+// serialize on the MLX runtime) and async callers treat them like local:
+// 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]);
+
// 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 cheap
diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.js
index 14c07e6238..c23425545d 100644
--- a/server/services/imageGen/prepareParams.js
+++ b/server/services/imageGen/prepareParams.js
@@ -27,7 +27,7 @@ import { join } from 'node:path';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, ensureDir, resolveGalleryImage } from '../../lib/fileUtils.js';
import { getSettings } from '../settings.js';
-import { IMAGE_GEN_MODE, resolveImageCleaners } from './index.js';
+import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, resolveImageCleaners } from './index.js';
import { getImageModels, isFlux2 } from '../../lib/mediaModels.js';
// Only the formats mflux can decode — mirrors the route's MIME_TO_EXT map
@@ -162,12 +162,13 @@ export async function prepareGenerateParams({ data, files, referenceImageFields
data.referenceImageStrengths = referenceImageStrengths;
}
- // Empty prompt is allowed for i2i / local / external, but Codex text-to-image
- // (no init image) still needs one — reject synchronously here so direct API
- // callers get a 400 instead of a 200-then-async-job-failure. Mirrors the guard
- // in codex.js and the client's codexNeedsPrompt gate.
- if (mode === IMAGE_GEN_MODE.CODEX && !initImagePath && !data.prompt?.trim()) {
- throw new ServerError('Prompt is required for Codex text-to-image', { status: 400, code: 'VALIDATION_ERROR' });
+ // Empty prompt is allowed for i2i / local / external, but cloud-CLI
+ // text-to-image (codex/grok, no init image) still needs one — reject
+ // synchronously here so direct API callers get a 400 instead of a
+ // 200-then-async-job-failure. Mirrors the guards in codex.js/grok.js and
+ // the client's needs-prompt gate.
+ if (CLOUD_IMAGE_GEN_MODES.includes(mode) && !initImagePath && !data.prompt?.trim()) {
+ throw new ServerError(`Prompt is required for ${mode === IMAGE_GEN_MODE.CODEX ? 'Codex' : 'Grok'} text-to-image`, { status: 400, code: 'VALIDATION_ERROR' });
}
if (data.guidance == null && data.cfgScale != null) {
diff --git a/server/services/loraDatasetGenerate.js b/server/services/loraDatasetGenerate.js
index 2bbc900755..7da66a455b 100644
--- a/server/services/loraDatasetGenerate.js
+++ b/server/services/loraDatasetGenerate.js
@@ -354,6 +354,17 @@ async function resolveRenderParams({ modelId: modelOverride = null } = {}) {
}
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' };
+ }
if (activeMode === IMAGE_GEN_MODE.LOCAL) {
const allModels = getImageModels();
const modelId = resolveSheetModelId({ override: modelOverride, settings, allModels });
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 3af4e44f34..5165c6ce89 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -45,9 +45,15 @@ import { imageGenEvents } from '../imageGenEvents.js';
import { trainingEvents } from '../loraTraining/events.js';
import { audioGenEvents } from '../audioGen/events.js';
import { getSettings } from '../settings.js';
-import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
+import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
-const isCodexJob = (j) => j.kind === 'image' && j.params?.mode === IMAGE_GEN_MODE.CODEX;
+// Cloud-CLI image jobs (codex, grok) share one parallel lane — each render
+// shells out to its own external child spending remote quota, so they don't
+// serialize on the MLX runtime the way GPU jobs do. The lane's slot count is
+// `codexParallelLimit` (settings key `imageGen.codex.parallelLimit`, kept
+// under the codex name for backward compat — it now bounds codex + grok
+// renders combined).
+const isCloudImageJob = (j) => j.kind === 'image' && CLOUD_IMAGE_GEN_MODES.includes(j.params?.mode);
const JOBS_FILE = join(PATHS.data, 'media-jobs.json');
const COMPLETED_TTL_MS = 24 * 60 * 60 * 1000;
@@ -127,6 +133,7 @@ function getGenModuleForJob(job) {
if (job.kind === 'training') return import('../loraTraining/index.js');
if (job.kind === 'audio') return import('../audioGen/local.js');
if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');
+ if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');
if (job.kind === 'image') return import('../imageGen/local.js');
return Promise.resolve(null);
}
@@ -152,7 +159,7 @@ async function resolveLiveParams(job, safeParams) {
// live settings pythonPath wins there too. flux2 training resolves its
// own venv (resolveFlux2Python) inside runTraining — skip it here.
const usesLocalPython = job.kind === 'video'
- || (job.kind === 'image' && job.params?.mode !== IMAGE_GEN_MODE.CODEX)
+ || (job.kind === 'image' && !CLOUD_IMAGE_GEN_MODES.includes(job.params?.mode))
|| (job.kind === 'training' && job.params?.runtime === 'mflux');
if (!usesLocalPython) return;
const live = await getSettings().catch(() => null);
@@ -350,7 +357,7 @@ export async function initMediaJobQueue() {
let codexCounter = 0;
let gpuCounter = 0;
for (const q of queue) {
- if (isCodexJob(q)) {
+ if (isCloudImageJob(q)) {
q.position = ++codexCounter;
} else {
q.position = ++gpuCounter;
@@ -399,7 +406,7 @@ function startWorker() {
// running job. This lets a Codex job that arrives while a GPU render is in
// flight be picked up immediately on the next 150 ms tick instead of having
// to wait for the entire GPU job to finish first.
-function startLaneJob(job, { isCodex }) {
+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)
@@ -415,18 +422,17 @@ function startLaneJob(job, { isCodex }) {
job.position = 1;
job.progress = typeof job.progress === 'number' && Number.isFinite(job.progress) ? job.progress : 0;
job.statusMsg = job.statusMsg || 'Starting';
- if (isCodex) {
+ if (isCloud) {
codexRunning.push(job);
} else {
running = job;
}
recomputeQueuePositions();
- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${isCodex ? 'codex' : 'gpu'} start failed: ${e.message}`));
+ const label = isCloud ? (job.params?.mode || 'cloud') : job.kind;
+ persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${isCloud ? label : 'gpu'} 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)}] ${isCodex ? 'codex' : job.kind} started`);
-
- const label = isCodex ? 'codex' : job.kind;
+ console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${label} started`);
(async () => {
try {
await runJob(job);
@@ -443,7 +449,7 @@ function startLaneJob(job, { isCodex }) {
mediaJobEvents.emit('failed', job);
}
}
- if (isCodex) {
+ if (isCloud) {
const idx = codexRunning.indexOf(job);
if (idx >= 0) codexRunning.splice(idx, 1);
} else {
@@ -466,13 +472,13 @@ async function drainLoop() {
let codexSlots = codexParallelLimit - codexRunning.length;
if ((gpuOpen || codexSlots > 0) && queue.length > 0) {
for (const job of queue.slice()) {
- if (isCodexJob(job)) {
+ if (isCloudImageJob(job)) {
if (codexSlots > 0) {
- startLaneJob(job, { isCodex: true });
+ startLaneJob(job, { isCloud: true });
codexSlots -= 1;
}
} else if (gpuOpen) {
- startLaneJob(job, { isCodex: false });
+ startLaneJob(job, { isCloud: false });
gpuOpen = false;
}
if (!gpuOpen && codexSlots <= 0) break;
@@ -504,15 +510,16 @@ export function removeArchivedJob(jobId) {
return true;
}
-// "Run now" bypass — start a queued codex job immediately even if the lane is
-// at its limit. GPU jobs are rejected (single MLX runtime would OOM).
+// "Run now" bypass — start a queued cloud-CLI (codex/grok) job immediately
+// even if the lane is at its limit. GPU jobs are rejected (single MLX runtime
+// would OOM). The rejection code stays 'NOT_CODEX' for client back-compat.
export function runJobNow(jobId) {
const job = queue.find((j) => j.id === jobId);
if (!job) return { ok: false, code: 'NOT_FOUND', error: 'Job not found in queue' };
- if (!isCodexJob(job)) {
- return { ok: false, code: 'NOT_CODEX', error: 'Only Codex image jobs can be run-now; GPU jobs serialize on the MLX runtime' };
+ if (!isCloudImageJob(job)) {
+ return { ok: false, code: 'NOT_CODEX', error: 'Only cloud-CLI (Codex/Grok) image jobs can be run-now; GPU jobs serialize on the MLX runtime' };
}
- startLaneJob(job, { isCodex: true });
+ startLaneJob(job, { isCloud: true });
return { ok: true, status: 'running' };
}
@@ -522,8 +529,8 @@ 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(isCodexJob);
- const gpuJobs = queue.filter((j) => !isCodexJob(j));
+ const codexJobs = queue.filter(isCloudImageJob);
+ const gpuJobs = queue.filter((j) => !isCloudImageJob(j));
codexJobs.forEach((q, i) => {
const newPosition = i + 1 + codexRunning.length;
@@ -782,7 +789,7 @@ async function runJob(job) {
if (job.kind === 'video') return WATCHDOG_VIDEO_MS * Math.max(1, Number(safeParams.chunks) || 1);
if (job.kind === 'training') return WATCHDOG_TRAINING_MS;
if (job.kind === 'audio') return WATCHDOG_AUDIO_MS;
- if (isCodexJob(job)) return WATCHDOG_CODEX_MS;
+ if (isCloudImageJob(job)) return WATCHDOG_CODEX_MS;
return WATCHDOG_IMAGE_MS;
})();
let lastActivityAt = Date.now();
@@ -892,9 +899,9 @@ export function enqueueJob({ kind, params, owner = null }) {
// same lane occupies slot 1, then same-lane queued jobs follow. Codex
// jobs only count Codex ahead-of-them; GPU jobs only count GPU jobs.
position: (() => {
- const isCodex = isCodexJob({ kind, params });
- const laneQueue = queue.filter((j) => isCodexJob(j) === isCodex);
- return laneQueue.length + (isCodex ? codexRunning.length : (running ? 1 : 0)) + 1;
+ const isCloud = isCloudImageJob({ kind, params });
+ const laneQueue = queue.filter((j) => isCloudImageJob(j) === isCloud);
+ return laneQueue.length + (isCloud ? codexRunning.length : (running ? 1 : 0)) + 1;
})(),
};
queue.push(job);
diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.js
index 9b10435296..f0541f8b48 100644
--- a/server/services/pipeline/issuesShared.js
+++ b/server/services/pipeline/issuesShared.js
@@ -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]);
+const IMAGE_MODE_VALUES = new Set(['auto', IMAGE_GEN_MODE.LOCAL, IMAGE_GEN_MODE.CODEX, IMAGE_GEN_MODE.GROK]);
const GEN_CONFIG_STR_MAX = 200;
const sanitizeGenConfig = (raw) => {
if (!raw || typeof raw !== 'object') return null;
diff --git a/server/services/pipeline/visualStageHelpers.js b/server/services/pipeline/visualStageHelpers.js
index 4c0e9c1025..e72558f4f5 100644
--- a/server/services/pipeline/visualStageHelpers.js
+++ b/server/services/pipeline/visualStageHelpers.js
@@ -66,12 +66,16 @@ 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;
+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;
if (options.mode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (options.mode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
if (options.mode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
const settingsMode = settings?.imageGen?.mode;
if (settingsMode === IMAGE_GEN_MODE.CODEX && codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (settingsMode === IMAGE_GEN_MODE.GROK && grokEnabled) return IMAGE_GEN_MODE.GROK;
if (settingsMode === IMAGE_GEN_MODE.LOCAL) return IMAGE_GEN_MODE.LOCAL;
if (codexEnabled) return IMAGE_GEN_MODE.CODEX;
+ if (grokEnabled) return IMAGE_GEN_MODE.GROK;
return IMAGE_GEN_MODE.LOCAL;
};
@@ -256,7 +260,9 @@ const enqueueImageJob = ({ prompt, world, settings, options, mode, owner, logLin
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 }
- : { pythonPath: settings.imageGen?.local?.pythonPath || null, modelId: options.modelId, 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 { 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.js
index 79d5f8bf59..74bfcb6ee1 100644
--- a/server/services/universeBuilderRender.js
+++ b/server/services/universeBuilderRender.js
@@ -63,9 +63,9 @@ 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) {
+ if (mode !== IMAGE_GEN_MODE.LOCAL && mode !== IMAGE_GEN_MODE.CODEX && mode !== IMAGE_GEN_MODE.GROK) {
throw new ServerError(
- 'Batch render requires local or codex mode — switch image-gen mode in Settings → Image Gen',
+ 'Batch render requires local, codex, or grok mode — switch image-gen mode in Settings → Image Gen',
{ status: 400, code: 'WORLD_BUILDER_EXTERNAL_UNSUPPORTED' },
);
}
@@ -78,6 +78,12 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
{ 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' },
+ );
+ }
if (mode === IMAGE_GEN_MODE.LOCAL) {
const py = settings.imageGen?.local?.pythonPath || null;
const allModels = getImageModels();
@@ -186,6 +192,12 @@ export async function renderUniverseJobs(universeId, body, mapServiceError) {
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 || {};
+ queued = enqueueJob({
+ kind: 'image',
+ params: { mode: IMAGE_GEN_MODE.GROK, grokPath: g.grokPath, aspectRatio: g.aspectRatio, cleanC2PA, denoise, ...params },
+ });
} else {
// mode === IMAGE_GEN_MODE.LOCAL (validated upfront).
const py = settings.imageGen?.local?.pythonPath || null;
diff --git a/server/services/universeCharacterSheet.js b/server/services/universeCharacterSheet.js
index 56b3ddac24..c7fc940360 100644
--- a/server/services/universeCharacterSheet.js
+++ b/server/services/universeCharacterSheet.js
@@ -451,6 +451,16 @@ export async function renderCharacterReferenceSheet(universeId, entryId, options
}
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 };
} else if (activeMode === IMAGE_GEN_MODE.LOCAL) {
const allModels = getImageModels();
modelId = resolveSheetModelId({ override: options.modelId, settings, allModels });
diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.js
index 23052fa550..a324a28f74 100644
--- a/server/services/voice/tools.test.js
+++ b/server/services/voice/tools.test.js
@@ -105,8 +105,9 @@ const generateImageMock = vi.fn(async (params) => {
});
vi.mock('../imageGen/index.js', () => ({
generateImage: (...args) => generateImageMock(...args),
- IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex' },
- IMAGE_GEN_MODES: ['external', 'local', 'codex'],
+ IMAGE_GEN_MODE: { EXTERNAL: 'external', LOCAL: 'local', CODEX: 'codex', GROK: 'grok' },
+ CLOUD_IMAGE_GEN_MODES: ['codex', 'grok'],
+ IMAGE_GEN_MODES: ['external', 'local', 'codex', 'grok'],
}));
vi.mock('../settings.js', () => ({
getSettings: vi.fn(async () => ({
diff --git a/server/services/voice/tools/media.js b/server/services/voice/tools/media.js
index 7f94542142..22eba54638 100644
--- a/server/services/voice/tools/media.js
+++ b/server/services/voice/tools/media.js
@@ -16,7 +16,7 @@ export const MEDIA_TOOLS = [
{
name: 'image_generate',
description:
- 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend (Local mflux, External SD API, or Codex CLI). Pass `provider` to override per-call: "local" for fast Flux drafts, "external" for an A1111-compatible server, "codex" for the Codex CLI built-in image_gen tool (subject to the user enabling it in Settings). Returns the saved file path.',
+ 'Generate an image from a text prompt and save it to the user\'s gallery. Defaults to the user\'s saved Image Gen backend (Local mflux, External SD API, or Codex CLI). Pass `provider` to override per-call: "local" for fast Flux drafts, "external" for an A1111-compatible server, "codex" for the Codex CLI built-in image_gen tool, or "grok" for the Grok Build CLI built-in image_gen tool (both subject to the user enabling them in Settings). Returns the saved file path.',
parameters: {
type: 'object',
properties: {
@@ -61,6 +61,12 @@ export const MEDIA_TOOLS = [
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.' };
+ }
+ }
// LLMs/tool callers often hand back numeric args as strings ("512").
// Coerce + bounds-check before forwarding — the route's Zod schema
// also gates these, but voice tool calls bypass the route, so an
@@ -103,7 +109,7 @@ export const MEDIA_TOOLS = [
}
const usedMode = result?.mode || requestedMode || 'default';
- const isAsync = usedMode === imageGen.IMAGE_GEN_MODE.LOCAL || usedMode === imageGen.IMAGE_GEN_MODE.CODEX;
+ const isAsync = usedMode === imageGen.IMAGE_GEN_MODE.LOCAL || imageGen.CLOUD_IMAGE_GEN_MODES.includes(usedMode);
// External resolves with the file already on disk — short-circuit.
if (!isAsync) {
waiter.cleanup();