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

Fix Codex image model defaults and isolate render workspaces (#11770)

[._.]/254ecfc0cd1a
diff --git a/server/lib/imageGenCapabilities.js b/server/lib/imageGenCapabilities.js
index 239938fc65..83bcff754b 100644
--- a/server/lib/imageGenCapabilities.js
+++ b/server/lib/imageGenCapabilities.js
@@ -89,10 +89,9 @@ export const CODEX_IMAGEGEN_DEFAULT_EFFORT = 'low';
// (`imageGen/agy.js#resolveAgyDriverModel`), because an install can outrun
// its PortOS version: the catalog refreshes from the live CLI on its own
// schedule. That covers only this PortOS-chosen pin — a model the user typed
-// is theirs. Codex has no such heal: its pin is passed through verbatim by
-// `imageGen/codex.js` with no model/effort pairing to validate, so a retired
-// id surfaces as codex's own error rather than a confusing one, and the CI
-// guard above is the defense. Give it one if that ever stops being true.
+// is theirs. Codex similarly checks its local model cache at render time
+// and uses a known listed lightweight fallback only for the shipped default.
+// Missing cache evidence leaves the default unchanged; explicit pins win.
//
// So this constant is a shipped STARTING POINT — but keep it current: it is
// what the Settings/ImageGen pickers display as "the default", and what an
diff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.js
index 8b99f0487d..72661835e9 100644
--- a/server/services/imageGen/cloudProviderConfig.js
+++ b/server/services/imageGen/cloudProviderConfig.js
@@ -87,8 +87,9 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({
label: 'Codex Imagegen',
errorCode: 'CODEX_IMAGEGEN_DISABLED',
modelId: (c, override) => override || c.model || CODEX_IMAGEGEN_DEFAULT_MODEL,
- params: (c, override) => ({
+ params: (c, override, overrideIsShippedDefault = false) => ({
codexPath: c.codexPath,
+ modelIsShippedDefault: overrideIsShippedDefault || (!override && !c.model),
model: override || c.model || CODEX_IMAGEGEN_DEFAULT_MODEL,
effort: c.effort,
}),
@@ -197,7 +198,7 @@ export function resolveCloudProviderConfig(settings, mode, overrides = {}) {
modelOverride,
// Re-surfaced at the top level so a caller threading this bundle's model
// onward can thread its provenance with it, without reaching into the
- // per-provider `providerParams` bag (only agy carries the field there).
+ // per-provider `providerParams` bag (the CLI drivers carry the field there).
modelIsShippedDefault: providerParams.modelIsShippedDefault === true,
modelId: spec.modelId(config, modelOverride),
providerParams,
diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.js
index 8633b9455e..535e67f340 100644
--- a/server/services/imageGen/cloudProviderConfig.test.js
+++ b/server/services/imageGen/cloudProviderConfig.test.js
@@ -35,6 +35,7 @@ describe('resolveCloudProviderConfig', () => {
expect(cloud.providerParams).toEqual({
codexPath: '/bin/codex',
model: CODEX_IMAGEGEN_DEFAULT_MODEL,
+ modelIsShippedDefault: true,
effort: 'high',
});
expect(cloud.jobParams).toEqual({ mode: IMAGE_GEN_MODE.CODEX, ...cloud.providerParams });
@@ -49,6 +50,21 @@ describe('resolveCloudProviderConfig', () => {
expect(cloud.providerParams.model).toBe('gpt-5.4');
});
+ it('preserves Codex default provenance across render-target dispatch', () => {
+ const settings = settingsWith({ codex: { enabled: true } });
+ const resolved = resolveRenderTargetConfig(settings, 'universe-bible', { mode: IMAGE_GEN_MODE.CODEX });
+ const dispatched = resolveCloudProviderConfig(settings, resolved.mode, {
+ model: resolved.cloud.modelId,
+ modelIsShippedDefault: resolved.cloud.modelIsShippedDefault,
+ });
+ expect(dispatched.providerParams.modelIsShippedDefault).toBe(true);
+ expect(resolveCloudProviderConfig(settings, IMAGE_GEN_MODE.CODEX, {
+ model: CODEX_IMAGEGEN_DEFAULT_MODEL,
+ }).providerParams.modelIsShippedDefault).toBe(false);
+ expect(resolveCloudProviderConfig(settingsWith({ codex: { enabled: true, model: CODEX_IMAGEGEN_DEFAULT_MODEL } }),
+ IMAGE_GEN_MODE.CODEX, { modelIsShippedDefault: true }).providerParams.modelIsShippedDefault).toBe(false);
+ });
+
it('bundles grok job params (no model knob — fixed backend id)', () => {
const cloud = resolveCloudProviderConfig(
settingsWith({ grok: { enabled: true, grokPath: '/bin/grok', aspectRatio: '16:9' } }),
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index bb80857c2e..fe4306a6d4 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -20,24 +20,23 @@ import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js'
* disabled the dispatcher rejects up front; this module assumes it's enabled
* by the time generateImage() is called.
*
- * No fabrication guard here, unlike agy/grok (see imageGen/fabricationGuard.js):
- * those direct the agent to write a PNG at a path PortOS chose, which is a goal
- * a coding agent can satisfy by drawing one when the image tool is unavailable.
- * Codex is never told a destination — we harvest from its own
- * `~/.codex/generated_images/<session-id>/` dir and the session JSONL, and it
- * has no scratch cwd — so there is no "a file exists at path X" criterion for a
- * fabricated image to meet. If Codex ever gains a directed staging path, it
- * needs the guard too.
+ * Each child runs in an owned temporary workspace. Only the Codex generated
+ * image directory and image-generation session events are harvested; scratch
+ * drawings are never accepted. Missing tool events do not prove an account
+ * lacks image generation, so diagnostics distinguish observation from capability.
*/
import { spawn } from '../../lib/childProcess.js';
import { bufferedSpawn, prepareCliSpawn, killProcessTree } from '../../lib/bufferedSpawn.js';
-import { readFile, readdir, stat } from 'fs/promises';
+import { readFile, readdir, stat, mkdtemp } from 'fs/promises';
import { existsSync } from 'fs';
-import { join } from 'path';
-import { homedir } from 'os';
+import { join, isAbsolute, resolve, sep } from 'path';
+import { codexHomeDir } from '../../lib/codexUserConfig.js';
+import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';
+import { maintenance } from '../../lib/maintenanceAdmission.js';
+import { noFabricationClause } from './fabricationGuard.js';
import { randomUUID } from 'crypto';
-import { atomicWrite, copyFileGuarded, ensureDir, PATHS, sleep, unlinkGuarded } from '../../lib/fileUtils.js';
+import { atomicWrite, copyFileGuarded, ensureDir, PATHS, sleep, unlinkGuarded, rmGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
@@ -75,8 +74,30 @@ const DEFAULT_HARVEST_TIMEOUT_MS = 5000;
let harvestTimeoutMs = DEFAULT_HARVEST_TIMEOUT_MS;
const codexImagesDir = (sessionId) =>
- join(homedir(), '.codex', 'generated_images', sessionId);
-const codexSessionsDir = () => join(homedir(), '.codex', 'sessions');
+ join(codexHomeDir(), 'generated_images', sessionId);
+const codexSessionsDir = () => join(codexHomeDir(), 'sessions');
+
+// Cache evidence only changes PortOS's default, never an explicit selection.
+async function resolveCodexDriverModel(model, modelIsShippedDefault) {
+ const explicit = typeof model === 'string' && model.trim();
+ if (explicit && !modelIsShippedDefault) return explicit;
+ const preferred = CODEX_IMAGEGEN_DEFAULT_MODEL;
+ let listed;
+ try {
+ const path = join(codexHomeDir(), 'models_cache.json');
+ if ((await stat(path)).size > 2 * 1024 * 1024) return preferred;
+ const cache = JSON.parse(await readFile(path, 'utf8'));
+ if (!Array.isArray(cache.models)) return preferred;
+ listed = new Set(cache.models.filter(item => item?.visibility === 'list' && typeof item.slug === 'string').map(item => item.slug));
+ } catch { /* Missing or unreadable cache provides no model availability evidence. */ }
+ if (!listed?.size || listed.has(preferred)) return preferred;
+ const fallback = ['gpt-5.6-luna', 'gpt-5.6-terra'].find(id => listed.has(id));
+ if (fallback) {
+ console.log(`🔀 Codex image default ${preferred} is not listed in the local model cache; using ${fallback}`);
+ return fallback;
+ }
+ throw new ServerError('The local Codex model cache lists no supported low-cost image-generation driver default. Select an available model explicitly in Settings → Image Gen.', { status: 400 });
+}
// Per-job state — keyed by jobId so multiple codex renders can run in
// parallel under the mediaJobQueue's configurable lane limit. Same client
@@ -204,11 +225,11 @@ export function codexSentPrompt({ prompt = '', negativePrompt, width, height, in
initImageStrength,
});
const buildWith = (text) => `$imagegen ${editPrefix}${text.trim()}${sizeHint}${qualityHint}${avoidHint}`;
- const fullPrompt = buildWith(prompt);
+ const fullPrompt = buildWith(prompt) + '\n' + noFabricationClause('image_gen');
return {
fullPrompt,
record: sentPromptRecord({ sentPrompt: fullPrompt, carried: carriedPromptAdditions({ promptAdditions }),
- added: [agentInstructionsAddition('Codex image tool instructions', buildWith)] }),
+ added: [agentInstructionsAddition('Codex image tool instructions', text => buildWith(text) + '\n' + noFabricationClause('image_gen'))] }),
};
}
@@ -217,7 +238,7 @@ export function codexSentPrompt({ prompt = '', negativePrompt, width, height, in
// feeds the attachments to `image_gen` as references.
export async function generateImage({
promptAdditions = [],
- codexPath, model, effort, prompt = '', width, height, negativePrompt,
+ codexPath, model, modelIsShippedDefault = false, effort, prompt = '', width, height, negativePrompt,
initImagePath, initImageStrength, referenceImagePaths = [],
visualConditioning = null,
jobId: providedJobId = null,
@@ -233,7 +254,7 @@ export async function generateImage({
// A caller-supplied model/effort (an explicit Settings → Image Gen override,
// threaded through the dispatcher) wins; `null`/`''`/absent falls back to the
// shipped default so a bare install never runs Codex's heaviest tier.
- const effectiveModel = (typeof model === 'string' && model.trim()) ? model.trim() : CODEX_IMAGEGEN_DEFAULT_MODEL;
+ const effectiveModel = await resolveCodexDriverModel(model, modelIsShippedDefault);
// Validate the effort against the known codex levels before use: an
// unrecognized non-empty value (a hand-edited settings.json / the unvalidated
// settings PUT) would otherwise pass through, buildEffortArgs would emit no
@@ -306,19 +327,28 @@ export async function generateImage({
...sentRecord,
createdAt: new Date().toISOString(),
};
+ await ensureDir(PATHS.tmp);
+ const scratchDir = await mkdtemp(join(PATHS.tmp, 'codex-image-'));
const job = { ...meta, clients: [], status: 'running', renderStartedAtMs };
- jobs.set(jobId, job);
+ try {
+ jobs.set(jobId, job);
- console.log(`🎨 Generating image [${jobId.slice(0, 8)}] codex: ${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 codex…' });
+ console.log(`🎨 Generating image [${jobId.slice(0, 8)}] codex: ${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 codex…' });
+ } catch (err) {
+ jobs.delete(jobId);
+ activeJobs.delete(jobId);
+ await removeScratchDirectory(scratchDir);
+ throw err;
+ }
// generateImage returns a job descriptor synchronously; the actual codex
// child runs out-of-band so the HTTP response can ship while the client
// attaches to the per-job SSE stream (mirrors local.js). runCodex settles
// every launch failure through the job's own failure finalizer.
- runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA, denoise });
+ runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA, denoise, scratchDir });
return {
jobId, filename, path: `/data/images/${filename}`, generationId: jobId,
@@ -329,39 +359,45 @@ export async function generateImage({
};
}
-// Codex exited 0 with a session id but wrote no PNG. Turn its stdout narration
-// into the most useful error we can — surfacing the model's own words (#imagegen
-// declines, content refusals, "generated" claims with no file) instead of a
-// fixed guess. The legacy account/enablement hint is kept as a fallback when
-// codex said nothing usable. The line walk itself lives in the shared
-// `buildNoImageReason` so the codex and grok narrations cannot drift.
+// Preserve the model's reported reason without inferring account capability
+// from a missing output file or a narrated success claim.
const CODEX_NO_IMAGE_HINT =
- 'Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.';
+ 'Codex returned no generated image. Check the Codex session and Settings → Image Gen.';
export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail, {
hint: CODEX_NO_IMAGE_HINT,
// Codex's own structural labels, on top of the shared dashed-rule /
// bare-token-count filter.
dropLine: (l) => /^(codex|user)$/i.test(l) || /^tokens used\b/i.test(l),
describe: (said) => (
- // Codex claims success but no file landed → the image tool wasn't actually
- // run (image-gen unavailable / rate-limited on the account), even though the
- // turn narrated a generation. Call that out specifically.
/\b(generated|created|here(?:'|’)s|i(?:'|’)ve (?:made|generated))\b/i.test(said)
- ? `Codex reported success but wrote no image file — the built-in image tool likely didn't run (image generation may be unavailable or rate-limited on your account, even though the feature is enabled). Codex said: "${said}"`
+ ? `Codex reported success but no generated image file was found. Codex said: "${said}"`
: `Codex did not produce an image. Codex said: "${said}"`
),
});
+function removeScratchDirectory(scratchDir) {
+ return maintenance.continueSettlement(
+ () => rmGuarded(scratchDir, { recursive: true, force: true }),
+ ).catch(err => {
+ maintenance.markCurrentUnsettled();
+ console.error(`❌ Codex scratch cleanup failed: ${err.message}`);
+ });
+}
+
// Launch is synchronous so every failure has one owner: a refusal before a
// child exists (Node rejects an invalid argv/bin synchronously) settles the job
// here, and a setup failure after spawn terminates the child and leaves the
// close handler to settle once it has physically exited.
-function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false } = {}) {
+function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false, scratchDir } = {}) {
+ const removeScratch = () => removeScratchDirectory(scratchDir);
let proc;
try {
- const prepared = prepareCliSpawn(bin, args);
- proc = spawn(prepared.command, prepared.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ const resolvedBin = !isAbsolute(bin) && (bin.includes('/') || bin.includes(sep)) ? resolve(bin) : bin;
+ const prepared = prepareCliSpawn(resolvedBin, args);
+ const env = process.env.CODEX_HOME ? { ...process.env, CODEX_HOME: resolve(process.env.CODEX_HOME) } : process.env;
+ proc = spawn(prepared.command, prepared.args, { cwd: scratchDir, env: withSpawnCwdEnv(env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
} catch (err) {
+ void removeScratch();
return finalizeJobFailure(job, jobId, null, `Failed to spawn ${bin}: ${err?.message || err}`);
}
activeProcs.set(jobId, proc);
@@ -409,6 +445,7 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA
// A failed kill/send on a live child is not physical exit.
if (proc.pid) return;
clearTimeout(timeoutTimer);
+ void removeScratch();
finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
@@ -441,7 +478,7 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA
// poll for a few seconds in case there's a flush lag on slow disks.
const harvested = await harvestGeneratedImage(sessionId, harvestTimeoutMs);
if (!harvested) {
- return finalizeJobFailure(job, jobId, proc, noImageReason(stdoutTail));
+ return finalizeJobFailure(job, jobId, proc, await noImageSessionReason(sessionId, stdoutTail));
}
if (harvested.path) {
await copyFileGuarded(harvested.path, outputPath);
@@ -494,7 +531,7 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA
// EventEmitter does not await this listener, so settle the job here too.
clearTimeout(timeoutTimer);
finalizeJobFailure(job, jobId, proc, `Codex publication admission failed: ${err?.message || err}`);
- });
+ }).finally(removeScratch);
});
// Post-spawn setup. The error/close owners above are already installed, so a
@@ -515,7 +552,7 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA
// text and break the regex match.
// We DO retain stdout here (the model's turn narration) so a no-image
// finish can report why — a content decline, or a "generated" claim with
- // no file (tool unavailable / image-gen rate-limited on the account).
+ // no file.
stdoutTail += chunk.toString();
if (stdoutTail.length > STDOUT_TAIL_BYTES) stdoutTail = stdoutTail.slice(-STDOUT_TAIL_BYTES);
broadcastSse(job, { type: 'status', message: 'Running…' });
@@ -598,6 +635,24 @@ async function findSessionLogFile(sessionId) {
return null;
}
+async function noImageSessionReason(sessionId, stdoutTail) {
+ const path = await findSessionLogFile(sessionId);
+ if (!path) return noImageReason(stdoutTail);
+ const text = await readFile(path, 'utf8').catch(() => '');
+ let imageToolObserved = false;
+ let shellObserved = false;
+ for (const line of text.split('\n')) {
+ try {
+ const payload = JSON.parse(line)?.payload;
+ const name = payload?.name || '';
+ if (['image_gen', 'image_gen.text2im', 'image_gen.imagegen'].includes(name) || ['image_generation_call', 'image_generation_end'].includes(payload?.type)) imageToolObserved = true;
+ if (['function_call', 'custom_tool_call'].includes(payload?.type) && /^(exec|exec_command|shell|shell_command)$/.test(name)) shellObserved = true;
+ } catch { /* Incomplete transcript lines do not establish tool usage. */ }
+ }
+ if (imageToolObserved) return noImageReason(stdoutTail);
+ return `No image_gen call was observed in the Codex session${shellObserved ? '; shell activity was recorded' : ''}. No generated image was found. This does not establish whether the tool is available to this account. Check Settings → Image Gen and the Codex session. ${noImageReason(stdoutTail)}`;
+}
+
async function harvestSessionLogImage(sessionId) {
const logPath = await findSessionLogFile(sessionId);
if (!logPath) return null;
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index 8667ced974..8df99febe2 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -1,7 +1,7 @@
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 { join, relative, resolve } from 'path';
import { tmpdir } from 'os';
import { EventEmitter } from 'events';
import sharp from 'sharp';
@@ -80,6 +80,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
// a spread-only override would leave the original PATHS.images intact
// for any function closing over the actual module's binding.
actual.PATHS.images = FAKE_IMAGES_DIR;
+ actual.PATHS.tmp = join(TEST_HOME, 'tmp');
return {
...actual,
ensureDir: vi.fn(async (dir) => mkdir(dir, { recursive: true })),
@@ -99,6 +100,7 @@ const flush = () => new Promise((r) => setImmediate(r));
beforeEach(async () => {
setPlatform('linux');
+ vi.stubEnv('CODEX_HOME', join(TEST_HOME, '.codex'));
spawnCalls.length = 0;
imageGenEvents.removeAllListeners();
codex._internals.setHarvestTimeoutForTests(10);
@@ -445,6 +447,7 @@ describe('codex provider — image harvest', () => {
}
expect(completedListener).toHaveBeenCalledTimes(1);
+ await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
const finalPath = join(FAKE_IMAGES_DIR, job.filename);
expect(existsSync(finalPath)).toBe(true);
const written = await readFile(finalPath);
@@ -565,7 +568,7 @@ describe('codex provider — image harvest', () => {
child.emit('close', 0, null);
await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1));
- expect(failedListener.mock.calls[0][0].error).toMatch(/no image|account may not allow/i);
+ expect(failedListener.mock.calls[0][0].error).toMatch(/no generated image/i);
});
it('captures the session id even when banner + long prompt echo arrive in a single >4KB stderr chunk', async () => {
@@ -772,10 +775,10 @@ something else`;
});
describe('codex provider — noImageReason (no-image diagnostics)', () => {
- it('flags a "generated" claim with no file as tool-unavailable / rate-limited', () => {
+ it('reports a success claim without guessing tool availability', () => {
const msg = codex.noImageReason('codex\nGenerated with the built-in image tool using the imagegen skill.\ntokens used\n11484');
- expect(msg).toMatch(/wrote no image file/i);
- expect(msg).toMatch(/unavailable or rate-limited/i);
+ expect(msg).toMatch(/no generated image file was found/i);
+ expect(msg).not.toMatch(/unavailable|rate-limited|didn.t run/i);
// the model's own words are surfaced…
expect(msg).toContain('Generated with the built-in image tool');
// …but codex's structural labels + token count are stripped out
@@ -790,9 +793,9 @@ describe('codex provider — noImageReason (no-image diagnostics)', () => {
expect(msg).not.toMatch(/rate-limited/i);
});
- it('falls back to the account/enablement hint when codex said nothing usable', () => {
- expect(codex.noImageReason('')).toMatch(/may not allow image_gen/i);
- expect(codex.noImageReason('codex\nuser\n----\ntokens used\n42')).toMatch(/may not allow image_gen/i);
+ it('falls back to session/settings guidance when codex said nothing usable', () => {
+ expect(codex.noImageReason('')).toMatch(/Check the Codex session and Settings/i);
+ expect(codex.noImageReason('codex\nuser\n----\ntokens used\n42')).toMatch(/Check the Codex session and Settings/i);
});
it('strips ANSI escape codes from the surfaced narration', () => {
@@ -817,6 +820,7 @@ it('settles admission rejection from the actual close event and clears the activ
const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };
expect(codex.attachSseClient(job.jobId, response)).toBe(true);
expect(response.write.mock.calls[0][0]).toContain('injected publication admission refusal');
+ await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
response.req.emit('close');
} finally { admissionFault.error = null; }
});
@@ -866,6 +870,7 @@ describe('codex provider — launch refusal settlement', () => {
child.pid = 4242;
expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(existsSync(spawnCalls[0].options.cwd)).toBe(true);
expect(failed).not.toHaveBeenCalled();
expect(codex.getActiveJob()).toMatchObject({ generationId: job.jobId });
@@ -880,6 +885,7 @@ describe('codex provider — launch refusal settlement', () => {
await flush();
expect(failed).toHaveBeenCalledTimes(1);
expect(failed.mock.calls[0][0].error).toMatch(/launch setup failed: synthetic stream setup failure/);
+ await vi.waitFor(() => expect(existsSync(spawnCalls[0].options.cwd)).toBe(false));
expect(codex.getActiveJob()).toBeNull();
expect(codex.cancel(job.jobId)).toBe(false);
});
@@ -985,3 +991,91 @@ describe('codex provider — Windows shim lifecycle', () => {
vi.clearAllTimers();
});
});
+
+describe('Codex cached defaults and isolated workspace', () => {
+ const cacheModels = async slugs => {
+ await mkdir(join(TEST_HOME, '.codex'), { recursive: true });
+ await writeFile(join(TEST_HOME, '.codex', 'models_cache.json'), JSON.stringify({
+ models: slugs.map(slug => ({ slug, visibility: 'list' })),
+ }));
+ };
+ const finish = async call => {
+ call.child.exitCode = 1;
+ call.child.emit('close', 1, null);
+ await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
+ };
+
+ it.each([
+ [['gpt-6-luna', 'gpt-5.6-luna'], {}, 'gpt-6-luna'],
+ [['gpt-5.6-terra', 'gpt-5.6-luna'], {}, 'gpt-5.6-luna'],
+ [['gpt-5.6-terra'], { model: 'gpt-6-luna', modelIsShippedDefault: true }, 'gpt-5.6-terra'],
+ [['gpt-5.6-luna'], { model: 'gpt-6-luna' }, 'gpt-6-luna'],
+ [['gpt-5.6-luna'], { model: 'custom-explicit' }, 'custom-explicit'],
+ ])('uses cached defaults without replacing explicit selection (%j, %j)', async (models, options, expected) => {
+ await cacheModels(models);
+ const job = await codex.generateImage({ prompt: 'synthetic', ...options });
+ const call = spawnCalls[0];
+ expect(job.model).toBe(expected);
+ expect(call.args[call.args.indexOf('-m') + 1]).toBe(expected);
+ await finish(call);
+ });
+
+ it('rejects a known-absent default without silently buying a more expensive tier', async () => {
+ await cacheModels(['gpt-6.1-sol']);
+ await expect(codex.generateImage({ prompt: 'synthetic' })).rejects.toThrow(/Select an available model explicitly/);
+ expect(spawnCalls).toHaveLength(0);
+ });
+
+ it.each(['{broken', '{"models":[]}', '{"other":true}'])('treats an unusable cache as unknown: %s', async content => {
+ await mkdir(join(TEST_HOME, '.codex'), { recursive: true });
+ await writeFile(join(TEST_HOME, '.codex', 'models_cache.json'), content);
+ expect((await codex.generateImage({ prompt: 'synthetic' })).model).toBe('gpt-6-luna');
+ await finish(spawnCalls[0]);
+ });
+
+ it('preserves relative CLI and CODEX_HOME resolution when changing cwd', async () => {
+ vi.stubEnv('CODEX_HOME', relative(process.cwd(), join(TEST_HOME, '.codex')));
+ await codex.generateImage({ prompt: 'synthetic', codexPath: './bin/codex' });
+ const call = spawnCalls[0];
+ expect(call.bin).toBe(resolve('./bin/codex'));
+ expect(call.options.env.CODEX_HOME).toBe(join(TEST_HOME, '.codex'));
+ await finish(call);
+ });
+
+ it('cleans scratch after a spawn error with no physical child', async () => {
+ await codex.generateImage({ prompt: 'synthetic' });
+ const call = spawnCalls[0];
+ call.child.emit('error', new Error('spawn ENOENT'));
+ await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
+ expect(codex.getActiveJob()).toBeNull();
+ });
+
+ it('keeps scratch files until physical exit and never harvests shell drawings', async () => {
+ const sessionId = '019e2513-c506-7de1-815e-c1f589229242';
+ const sessions = join(TEST_HOME, '.codex', 'sessions');
+ await mkdir(sessions, { recursive: true });
+ await writeFile(join(sessions, `rollout-${sessionId}.jsonl`), JSON.stringify({
+ type: 'response_item', payload: { type: 'function_call', name: 'exec_command', arguments: 'draw a picture' },
+ }));
+ const failed = vi.fn();
+ imageGenEvents.on('failed', failed);
+ const job = await codex.generateImage({ prompt: 'synthetic' });
+ const call = spawnCalls[0];
+ expect(call.options.cwd.startsWith(join(TEST_HOME, 'tmp', 'codex-image-'))).toBe(true);
+ expect(call.options.env.PWD).toBe(call.options.cwd);
+ expect(call.args.at(-1)).toContain('Only the image_gen tool may produce this image');
+ await writeFile(join(call.options.cwd, 'drawing.svg'), '<svg/>');
+ await writeFile(join(call.options.cwd, 'drawing.png'), 'not a generated image');
+ codex.cancel(job.jobId);
+ expect(existsSync(call.options.cwd)).toBe(true);
+ call.child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));
+ call.child.exitCode = 0;
+ call.child.emit('close', 0, null);
+ await vi.waitFor(() => expect(existsSync(call.options.cwd)).toBe(false));
+ expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);
+ expect(failed).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify(failed.mock.calls)).toContain('No image_gen call was observed');
+ expect(JSON.stringify(failed.mock.calls)).toContain('shell activity was recorded');
+ expect(JSON.stringify(failed.mock.calls)).toContain('does not establish whether the tool is available');
+ });
+});
diff --git a/server/services/sprites/reference.test.js b/server/services/sprites/reference.test.js
index ad10b6d224..6722662b83 100644
--- a/server/services/sprites/reference.test.js
+++ b/server/services/sprites/reference.test.js
@@ -201,6 +201,9 @@ describe('startReferenceGeneration', () => {
mode, designPrompt, correctionPrompt: ' repair the hem ',
});
const job = enqueueJob.mock.calls[0][0];
+ if (mode === 'codex') {
+ expect(job.params.modelIsShippedDefault).toBe(false);
+ }
// Normalize native paths BEFORE JSON escapes Windows backslashes.
// Only fixture-rooted paths change; prompts and other payload bytes
// retain their exact snapshot contract.
@@ -244,23 +247,23 @@ describe('startReferenceGeneration', () => {
},
"codex/ambient-main": {
"manifestWrites": 1,
- "payloadSHA256": "1a3056e9172577fb5fc052d701753a657682a40c33106841fe720a18acd6ab16",
+ "payloadSHA256": "eb5a0e7f9cb43a944944ec4bad178b9fa0b503829cb3466b02bf9b1346ff079a",
},
"codex/east": {
"manifestWrites": 0,
- "payloadSHA256": "1c4b040e9ef9687cfbbf3e879addd15e0a71a905a3b5cc8ae68f10f1a1e145da",
+ "payloadSHA256": "9e27f6c9f891a54c48966b603319a3f762efab7ef2dab26106015f4f6bc796c4",
},
"codex/main": {
"manifestWrites": 1,
- "payloadSHA256": "a7836b97b8c12d00cbc57abd1934d0d31b0009f1c662c06d99603a5d27f30a6e",
+ "payloadSHA256": "831738c9a5253ac4cb70d51bf48abaf93e4a1d4c60104182c4cd82c54387b744",
},
"codex/main-reroll": {
"manifestWrites": 0,
- "payloadSHA256": "c852aac43df1f7cb288081e1c3df3e74a56226ffd64f669149dd92bf499e2633",
+ "payloadSHA256": "80c1772f7fdabe48107d938a60875b91f5d90b74e42de68bac462d6dcd619a7e",
},
"codex/turnaround": {
"manifestWrites": 1,
- "payloadSHA256": "2191d6e8863245b323ba4ba3bc88b22f7d902449e37f77a1f4906e9ff1f5ac47",
+ "payloadSHA256": "cf90b056abeae15d14a0cd9da60c654b1d4b4810b75989c6c0183232e038f840",
},
"grok/ambient-main": {
"manifestWrites": 1,