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

address review (codex): harden the grok backend and fix integration gaps

[._.]/ Adam Eivy90d450808048
diff --git a/client/src/components/pipeline/stages/VisualGenSettings.jsx b/client/src/components/pipeline/stages/VisualGenSettings.jsx
index e52a7cb0b1..e00f858eaf 100644
--- a/client/src/components/pipeline/stages/VisualGenSettings.jsx
+++ b/client/src/components/pipeline/stages/VisualGenSettings.jsx
@@ -77,19 +77,23 @@ const loadLookups = () => {
// this panel must match what the server will actually dispatch — otherwise
// the modal tells the user "Auto is currently Codex" while the render flows
// to local diffusion (or vice versa). Priority:
-// 1. settings.imageGen.mode pinned to 'codex' AND codex.enabled → 'codex'
+// 1. settings.imageGen.mode pinned to 'codex'/'grok' AND enabled → that backend
// 2. settings.imageGen.mode pinned to 'local' → 'local'
-// 3. settings.imageGen.codex.enabled (auto-default) → 'codex'
+// 3. codex enabled, else grok enabled (auto-default) → that backend
// 4. local pythonPath configured → 'local'
// 5. otherwise → not configured
-// Codex is gated on the enabled flag at every step — a stale 'codex' pin
-// from before the toggle was turned off must resolve as local, not Codex.
+// Mirrors the server's resolveMode in pipeline/visualStageHelpers.js — a
+// cloud backend is gated on its enabled flag at every step, so a stale pin
+// from before a toggle was turned off resolves as local, not that backend.
const resolveAutoLabel = (s) => {
const codexEnabled = s?.imageGen?.codex?.enabled === true;
+ const grokEnabled = s?.imageGen?.grok?.enabled === true;
const pinned = s?.imageGen?.mode;
if (pinned === IMAGE_GEN_MODE.CODEX && codexEnabled) return 'Codex';
+ if (pinned === IMAGE_GEN_MODE.GROK && grokEnabled) return 'Grok';
if (pinned === IMAGE_GEN_MODE.LOCAL) return 'Local diffusion';
if (codexEnabled) return 'Codex';
+ if (grokEnabled) return 'Grok';
if (s?.imageGen?.local?.pythonPath) return 'Local diffusion';
return 'Local diffusion (not configured)';
};
diff --git a/client/src/lib/pipelineImageDefaults.js b/client/src/lib/pipelineImageDefaults.js
index d3938184e0..a0ac914aab 100644
--- a/client/src/lib/pipelineImageDefaults.js
+++ b/client/src/lib/pipelineImageDefaults.js
@@ -5,7 +5,7 @@
// models render multi-panel pages dramatically better than local diffusion,
// so Codex is the right default whenever the user has it wired up.
-import { IMAGE_GEN_MODE } from './imageGenBackends';
+import { isCloudCliMode, IMAGE_GEN_MODE } from './imageGenBackends';
// 1024×1536 = 2:3 portrait, the closest preset to a real comic-book trim
// (~0.65 ratio). The "hi-res portrait" entry in imageGenResolutions is
@@ -29,7 +29,13 @@ export const PIPELINE_IMAGE_DEFAULTS = Object.freeze({
export function readPipelineImageSettings(settings) {
const stored = settings?.pipeline?.imageGen || {};
const codexEnabled = settings?.imageGen?.codex?.enabled === true;
- const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX : PIPELINE_IMAGE_DEFAULTS.mode;
+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ // Prefer an enabled cloud backend (codex first, then grok — the same order
+ // as the server's visual-stage resolver) so a cloud-only install doesn't
+ // default pipeline renders to an unconfigured local diffusion.
+ const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX
+ : grokEnabled ? IMAGE_GEN_MODE.GROK
+ : PIPELINE_IMAGE_DEFAULTS.mode;
return {
mode: stored.mode || defaultMode,
modelId: stored.modelId || PIPELINE_IMAGE_DEFAULTS.modelId,
@@ -51,7 +57,7 @@ export function pipelineImageCfgToRenderOpts(cfg) {
if (cfg.mode === IMAGE_GEN_MODE.LOCAL && cfg.modelId) opts.modelId = cfg.modelId;
if (Number.isFinite(cfg.width)) opts.width = cfg.width;
if (Number.isFinite(cfg.height)) opts.height = cfg.height;
- if (cfg.mode !== IMAGE_GEN_MODE.CODEX) {
+ if (!isCloudCliMode(cfg.mode)) {
const steps = Number(cfg.steps);
if (Number.isFinite(steps) && steps > 0) opts.steps = steps;
const guidance = Number(cfg.guidance);
diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.js
index 934a0799e9..2a87479c11 100644
--- a/client/src/lib/wrImageDefaults.js
+++ b/client/src/lib/wrImageDefaults.js
@@ -60,7 +60,10 @@ export function buildSceneRenderPayload({ prompt, negativePrompt = '', imageCfg
export function readWrImageSettings(settings, availableBackends = null) {
const stored = settings?.writersRoom?.imageGen || {};
const codexEnabled = settings?.imageGen?.codex?.enabled === true;
- const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX : WR_IMAGE_DEFAULTS.mode;
+ const grokEnabled = settings?.imageGen?.grok?.enabled === true;
+ const defaultMode = codexEnabled ? IMAGE_GEN_MODE.CODEX
+ : grokEnabled ? IMAGE_GEN_MODE.GROK
+ : WR_IMAGE_DEFAULTS.mode;
let mode = stored.mode || defaultMode;
if (Array.isArray(availableBackends) && availableBackends.length > 0
&& !availableBackends.some((b) => b.id === mode)) {
diff --git a/server/routes/sdapi.js b/server/routes/sdapi.js
index 783983aaa7..d44ad2098e 100644
--- a/server/routes/sdapi.js
+++ b/server/routes/sdapi.js
@@ -34,7 +34,11 @@ const router = Router();
// status + code on the HTTP response.
function createCompletionWaiter() {
return createImageGenWaiter({
- timeoutMs: 5 * 60 * 1000,
+ // Cloud-CLI providers (codex/grok) allow 20 minutes wall-clock
+ // (CODEX_TIMEOUT_MS / GROK_TIMEOUT_MS) — wait slightly past that so a
+ // slow-but-valid render doesn't return a timeout while the job keeps
+ // running (which invites a duplicate billed render).
+ timeoutMs: 21 * 60 * 1000,
onTimeout: () => new ServerError('Generation timed out', { status: 504, code: 'GEN_TIMEOUT' }),
onFailed: (ev) => new ServerError(ev?.error || 'Generation failed', { status: 500, code: 'GEN_FAILED' }),
});
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 4ced0fec6f..8d54e21dfa 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -20,21 +20,29 @@
* (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.
+ *
+ * Containment: grok is a general coding agent and headless runs bypass its
+ * approval prompts, so a prompt-injected render could try to reach beyond
+ * image generation. Grok exposes no image-tool-only permission mode, so the
+ * child is confined the ways we can: it runs with cwd set to a throwaway
+ * per-job scratch directory (relative-path tool ops and default file writes
+ * land there, and the whole dir is removed on every terminal path), and the
+ * staged output is signature-sniffed before it is accepted into the gallery.
*/
import { spawn } from 'child_process';
-import { copyFile, rename, stat, unlink } from 'fs/promises';
+import { copyFile, mkdir, open, rename, rm, stat, unlink } from 'fs/promises';
import { join } from 'path';
import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
-import { atomicWrite, ensureDir, PATHS, resolveImageInputPath } from '../../lib/fileUtils.js';
+import { atomicWrite, detectImageFormat, 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 { stripAnsi } from '../../lib/ansiStrip.js';
-import { bufferedSpawn } from '../../lib/bufferedSpawn.js';
+import { bufferedSpawn, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
import { IMAGE_GEN_MODE, describeFidelity } from './modes.js';
@@ -196,10 +204,14 @@ export async function generateImage({
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`);
+ // Grok writes into a per-job tmp scratch dir, not straight into the
+ // gallery — a failed/partial run must never leave junk where the gallery
+ // scanner or a concurrent client can see it, and the dir doubles as the
+ // child's cwd (see the containment note in the module header). Every
+ // terminal path removes the whole dir.
+ const scratchDir = join(tmpdir(), `portos-grok-${jobId}`);
+ const stagingPath = join(scratchDir, 'output.png');
+ await mkdir(scratchDir, { recursive: true });
// Caller dimensions win (mapped to the closest supported ratio); the saved
// per-provider default applies when no dimensions were sent; otherwise the
@@ -240,7 +252,7 @@ export async function generateImage({
// 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,
+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA, denoise,
}).catch((err) => {
console.log(`❌ grok run failed [${jobId.slice(0, 8)}]: ${err?.message}`);
});
@@ -255,10 +267,14 @@ export async function generateImage({
}
async function runGrok(job, jobId, bin, args, {
- useStdin, fullPrompt, cleanupPromptFile, stagingPath, outputPath, filename, meta, cleanC2PA = false, denoise = false,
+ useStdin, fullPrompt, cleanupPromptFile, scratchDir, stagingPath, outputPath, filename, meta, cleanC2PA = false, denoise = false,
}) {
- const proc = spawn(bin, args, { shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
+ // prepareCliSpawn resolves the Windows .cmd shim of an npm-installed grok
+ // and wraps it for a safe shell:false spawn — a no-op on POSIX.
+ const { command: spawnBin, args: spawnArgs } = prepareCliSpawn(bin, args);
+ const proc = spawn(spawnBin, spawnArgs, { cwd: scratchDir, shell: false, stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] });
activeProcs.set(jobId, proc);
+ const removeScratch = () => rm(scratchDir, { recursive: true, force: true }).catch(() => {});
if (useStdin) {
// POSIX: grok reads the prompt via --prompt-file /dev/stdin. EPIPE fires
@@ -283,6 +299,7 @@ async function runGrok(job, jobId, bin, args, {
proc.on('error', (err) => {
clearTimeout(timeoutTimer);
cleanupPromptFile();
+ removeScratch();
finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
@@ -307,13 +324,18 @@ async function runGrok(job, jobId, bin, args, {
if (code !== 0) {
const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
+ removeScratch();
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.
+ // exit, but poll a few seconds in case of flush lag on slow disks. The
+ // harvest signature-sniffs the bytes so a text error, truncated file,
+ // or non-image payload is never accepted into the gallery as a PNG.
const harvested = await harvestStagedImage(stagingPath, 5000);
- if (!harvested) {
- return finalizeError(job, jobId, proc, noImageReason(stdoutTail));
+ if (!harvested.found) {
+ removeScratch();
+ const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';
+ return finalizeError(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
}
// Move, not copy — the staging file is PortOS-owned and disposable, so
// rename is a metadata-only op when tmpdir and the gallery share a
@@ -322,6 +344,7 @@ async function runGrok(job, jobId, bin, args, {
await copyFile(stagingPath, outputPath);
await unlink(stagingPath).catch(() => {});
});
+ removeScratch();
// Sidecar metadata so the gallery can recover prompt/ratio/etc.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
await atomicWrite(sidecar, meta).catch(() => {});
@@ -337,6 +360,7 @@ async function runGrok(job, jobId, bin, args, {
imageGenEvents.emit('completed', { generationId: jobId, path: `/data/images/${filename}`, filename });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
+ removeScratch();
finalizeError(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`);
}
});
@@ -357,17 +381,32 @@ const finalizeError = (job, jobId, proc, 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. A single stat() answers both
-// "exists" and "non-empty" per tick.
+// Poll for the directed output file until it exists non-empty AND carries a
+// real image signature (PNG/JPEG/WebP/GIF via the shared detectImageFormat
+// sniffer), or timeoutMs elapses. Returns { found, invalid } — `invalid`
+// means a non-empty file appeared whose bytes never matched an image
+// signature (grok wrote a text error or other junk), which the caller
+// surfaces distinctly from "no file at all".
async function harvestStagedImage(stagingPath, timeoutMs) {
const deadline = Date.now() + timeoutMs;
+ let sawInvalid = false;
while (Date.now() < deadline) {
const s = await stat(stagingPath).catch(() => null);
- if (s && s.size > 0) return true;
+ if (s && s.size > 0) {
+ const head = Buffer.alloc(16);
+ const fh = await open(stagingPath, 'r').catch(() => null);
+ if (fh) {
+ const { bytesRead } = await fh.read(head, 0, 16, 0).catch(() => ({ bytesRead: 0 }));
+ await fh.close().catch(() => {});
+ if (detectImageFormat(head.subarray(0, bytesRead))) return { found: true, invalid: false };
+ // Header may still be flushing — keep polling; only report invalid
+ // if it never resolves into a real signature before the deadline.
+ sawInvalid = true;
+ }
+ }
await new Promise((r) => setTimeout(r, 250));
}
- return false;
+ return { found: false, invalid: sawInvalid };
}
// Test-only handles (mirrors codex.js's carve-out).
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
index 04dd72bc5a..490a334d90 100644
--- a/server/services/imageGen/grok.test.js
+++ b/server/services/imageGen/grok.test.js
@@ -50,7 +50,7 @@ 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 stagingPathFor = (jobId) => join(tmpdir(), `portos-grok-${jobId}`, 'output.png');
const promptOf = (i = 0) => spawnCalls[i].child.stdin.written;
const closeChild = async (i = 0, code = 1) => {
spawnCalls[i].child.exitCode = code;
@@ -188,8 +188,14 @@ describe('grok provider — directed-path harvest', () => {
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');
+ // Grok "writes" the directed staging file before the child exits. The
+ // harvest signature-sniffs the bytes, so the fixture needs a real PNG
+ // magic header.
+ const fakePngBytes = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from('fakepngbody'),
+ ]);
+ await mkdir(join(tmpdir(), `portos-grok-${job.jobId}`), { recursive: true });
await writeFile(stagingPathFor(job.jobId), fakePngBytes);
await closeChild(0, 0);
@@ -203,13 +209,34 @@ describe('grok provider — directed-path harvest', () => {
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);
+ // The whole per-job scratch dir is cleaned up after the move.
+ expect(existsSync(join(tmpdir(), `portos-grok-${job.jobId}`))).toBe(false);
// Sidecar metadata exists too.
const sidecar = join(FAKE_IMAGES_DIR, `${job.generationId}.metadata.json`);
expect(existsSync(sidecar)).toBe(true);
});
+ it('rejects a staged file that is not a real image (signature sniff)', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ const job = await grok.generateImage({ prompt: 'a fox' });
+ // Grok wrote a text error where the PNG should be.
+ await mkdir(join(tmpdir(), `portos-grok-${job.jobId}`), { recursive: true });
+ await writeFile(stagingPathFor(job.jobId), 'Error: could not generate');
+ await closeChild(0, 0);
+
+ 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(/non-image file/);
+ // The rejected junk never reaches the gallery, and the scratch dir is gone.
+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);
+ expect(existsSync(join(tmpdir(), `portos-grok-${job.jobId}`))).toBe(false);
+ }, 12000);
+
it('fails with the stdout narration when grok exits 0 but wrote no file', async () => {
const failedListener = vi.fn();
imageGenEvents.on('failed', failedListener);
diff --git a/server/services/voice/tools/media.js b/server/services/voice/tools/media.js
index aa5b36c343..b93fb1f414 100644
--- a/server/services/voice/tools/media.js
+++ b/server/services/voice/tools/media.js
@@ -86,9 +86,11 @@ export const MEDIA_TOOLS = [
// emit 'completed' before we attach. External backends await the
// upstream HTTP call internally and the file is on disk by the time
// generateImage resolves — wait() is a no-op there.
- // 5-min cap mirrors the codex provider's own timeout — a stuck job
- // shouldn't leak listeners into the voice/palette dispatcher forever.
- const waiter = createImageGenWaiter({ timeoutMs: 5 * 60 * 1000 });
+ // 21-min cap sits just past the cloud providers' own 20-minute
+ // wall-clock timeouts (CODEX_TIMEOUT_MS / GROK_TIMEOUT_MS) so a slow
+ // but valid render isn't reported as a timeout while the job keeps
+ // running; a stuck job still can't leak listeners forever.
+ const waiter = createImageGenWaiter({ timeoutMs: 21 * 60 * 1000 });
let result;
try {