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(media): prepare Windows Codex image CLI launches (#10748)

[._.]/ Adam Eivyb62940ba9e18
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.js
index 0b64a76514..60b18d9445 100644
--- a/scripts/ci-test-plan.js
+++ b/scripts/ci-test-plan.js
@@ -163,6 +163,7 @@ export const WINDOWS_RISK_RULES = [
// with an interpreter-startup budget mistaken for a state-machine defect
// (#6268).
/^server\/services\/voice\/fineTuning(?:\.test)?\.js$/,
+ /^server\/services\/imageGen\/codex(?:\.test)?\.js$/,
/^server\/routes\/apps\//,
/^server\/routes\/scaffoldVite\.js$/,
];
diff --git a/scripts/ci-test-plan.test.js b/scripts/ci-test-plan.test.js
index c71ff4fb4f..be4b5ef2cb 100644
--- a/scripts/ci-test-plan.test.js
+++ b/scripts/ci-test-plan.test.js
@@ -1356,6 +1356,8 @@ describe('Windows escalation on a full plan (#7440)', () => {
'server/services/agentTuiSpawning.js',
'server/services/autonomousJobs/execution.shellSpawn.js',
'server/services/voice/fineTuning.js',
+ 'server/services/imageGen/codex.js',
+ 'server/services/imageGen/codex.test.js',
'server/routes/apps/index.js',
'server/routes/scaffoldVite.js',
];
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 8407dcc879..e9a85a261b 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -31,7 +31,7 @@ import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js'
*/
import { spawn } from '../../lib/childProcess.js';
-import { bufferedSpawn, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
+import { bufferedSpawn, prepareCliSpawn, killProcessTree } from '../../lib/bufferedSpawn.js';
import { readFile, readdir, stat } from 'fs/promises';
import { existsSync } from 'fs';
import { join } from 'path';
@@ -91,8 +91,14 @@ export const getActiveJob = () => {
export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
-const sigtermWithEscalation = (id, proc) =>
+const sigtermWithEscalation = (id, proc) => {
+ if (process.platform === 'win32') {
+ // The cmd.exe wrapper owns a Codex descendant: terminate the whole tree.
+ killProcessTree(proc);
+ return;
+ }
killWithEscalation(proc, { label: 'codex child', delayMs: 5000, stillRunning: () => activeProcs.get(id) === proc });
+};
// Cancel one specific codex render. jobId is required — with parallel codex
// renders an "anonymous cancel" is genuinely destructive (would nuke every
@@ -328,7 +334,8 @@ export const noImageReason = (stdoutTail = '') => buildNoImageReason(stdoutTail,
function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA = false, denoise = false } = {}) {
let proc;
try {
- proc = spawn(bin, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
+ const prepared = prepareCliSpawn(bin, args);
+ proc = spawn(prepared.command, prepared.args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
} catch (err) {
return finalizeJobFailure(job, jobId, null, `Failed to spawn ${bin}: ${err?.message || err}`);
}
@@ -468,8 +475,7 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PA
timeoutTimer = setTimeout(() => {
if (activeProcs.get(jobId) === proc) {
console.log(`⏱️ codex timed out after ${CODEX_TIMEOUT_MS}ms [${jobId.slice(0, 8)}]`);
- proc.kill('SIGTERM');
- setTimeout(() => { if (proc.exitCode === null) proc.kill('SIGKILL'); }, 5000);
+ sigtermWithEscalation(jobId, proc);
}
}, CODEX_TIMEOUT_MS);
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index c0474fc1af..8b3084f756 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -4,6 +4,8 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { EventEmitter } from 'events';
+import { ChildProcess } from 'child_process';
+import { pinPlatform } from '../../lib/testHelper.js';
const admissionFault = vi.hoisted(() => ({ error: null }));
vi.mock('../../lib/backupSnapshotBoundary.js', async original => {
@@ -28,7 +30,8 @@ vi.mock('os', async () => {
// stdout/stderr lines, and trigger the close event whenever they want.
const spawnCalls = [];
const makeFakeChild = () => {
- const child = new EventEmitter();
+ const child = new ChildProcess();
+ child.unref = vi.fn();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.kill = vi.fn();
@@ -50,6 +53,22 @@ vi.mock('../../lib/childProcess.js', async (importOriginal) => {
};
});
+// Exercise the real launch/tree-kill helpers with injectable platform facts.
+vi.mock('../../lib/bufferedSpawn.js', async original => {
+ const actual = await original();
+ return {
+ ...actual,
+ prepareCliSpawn: (bin, args) => actual.prepareCliSpawn(bin, args, process.env, process.platform === 'win32'),
+ killProcessTree: child => actual.killProcessTree(child, 'SIGTERM', {}, process.platform === 'win32'),
+ };
+});
+
+let restorePlatform;
+const setPlatform = value => {
+ restorePlatform?.();
+ restorePlatform = pinPlatform(value);
+};
+
// Stable PATHS.images under the fake HOME so the harvest's copyFile lands
// in a predictable place we can read back.
const FAKE_IMAGES_DIR = join(TEST_HOME, 'data-images');
@@ -78,6 +97,7 @@ const { SSE_CLEANUP_DELAY_MS } = await import('../../lib/sseUtils.js');
const flush = () => new Promise((r) => setImmediate(r));
beforeEach(async () => {
+ setPlatform('linux');
spawnCalls.length = 0;
imageGenEvents.removeAllListeners();
codex._internals.setHarvestTimeoutForTests(10);
@@ -86,6 +106,8 @@ beforeEach(async () => {
});
afterEach(async () => {
+ restorePlatform?.();
+ vi.unstubAllEnvs();
vi.useRealTimers();
codex._internals.setHarvestTimeoutForTests();
await rm(TEST_HOME, { recursive: true, force: true }).catch(() => {});
@@ -831,3 +853,104 @@ describe('codex provider — launch refusal settlement', () => {
expect(codex.cancel(job.jobId)).toBe(false);
});
});
+
+describe('codex provider — Windows shim lifecycle', () => {
+ it.each(['bare', 'explicit'])('prepares the %s shim for both probes and image launches without losing arguments', async kind => {
+ setPlatform('win32');
+ const cliDir = join(TEST_HOME, 'CLI shims');
+ const shim = join(cliDir, 'codex.cmd');
+ await mkdir(cliDir, { recursive: true });
+ await writeFile(shim, '@echo off');
+ vi.stubEnv('PATH', cliDir);
+ const codexPath = kind === 'explicit' ? shim : undefined;
+
+ const probe = codex.checkConnection({ codexPath });
+ const probeCall = spawnCalls[0];
+ expect(probeCall).toMatchObject({ bin: 'cmd.exe', args: ['/c', shim, '--version'], options: { shell: false } });
+ probeCall.child.stdout.emit('data', Buffer.from('codex-cli 1.2.3'));
+ probeCall.child.emit('close', 0);
+ await expect(probe).resolves.toMatchObject({ connected: true });
+
+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });
+ const image = join(FAKE_IMAGES_DIR, 'reference & sketch.png');
+ await writeFile(image, 'synthetic image');
+ const job = await codex.generateImage({
+ codexPath, model: 'gpt-6.1-sol&example', effort: 'high',
+ prompt: 'a fox & tree | sky > clouds', initImagePath: image,
+ });
+ const call = spawnCalls[1];
+ expect(call.bin).toBe('cmd.exe');
+ expect(call.options.shell).toBe(false);
+ expect(call.args.slice(0, 3)).toEqual(['/c', shim, 'exec']);
+ expect(call.args).toEqual(expect.arrayContaining([
+ 'model_reasoning_effort=high', '-i', image, '-m', 'gpt-6.1-sol^&example', '--',
+ ]));
+ expect(call.args.at(-1)).toContain('a fox & tree | sky > clouds');
+ expect(call.args.at(-1)).toMatch(/^\$imagegen /);
+ call.child.exitCode = 1;
+ call.child.emit('close', 1);
+ await flush();
+ expect(codex.cancel(job.jobId)).toBe(false);
+ });
+
+ it.each(['win32', 'linux'])('terminates only the selected %s job, then cancel-all terminates the remaining job', async platform => {
+ setPlatform(platform);
+ const first = await codex.generateImage({ prompt: 'first', codexPath: '/example/codex.cmd' });
+ const second = await codex.generateImage({ prompt: 'second', codexPath: '/example/codex.cmd' });
+ const firstChild = spawnCalls[0].child;
+ const secondChild = spawnCalls[1].child;
+ firstChild.pid = 4242;
+ secondChild.pid = 4243;
+
+ expect(codex.cancel(first.jobId)).toBe(true);
+ if (platform === 'win32') {
+ expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4242'] });
+ expect(firstChild.kill).not.toHaveBeenCalled();
+ } else {
+ expect(firstChild.kill).toHaveBeenCalledWith('SIGTERM');
+ }
+ expect(secondChild.killed).toBe(false);
+ firstChild.exitCode = 1;
+ firstChild.emit('close', 1);
+ await flush();
+ expect(codex.getActiveJob()).toMatchObject({ generationId: second.jobId });
+ expect(codex.cancelAll()).toBe(true);
+ if (platform === 'win32') {
+ expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4243'] });
+ expect(secondChild.kill).not.toHaveBeenCalled();
+ } else {
+ expect(secondChild.kill).toHaveBeenCalledWith('SIGTERM');
+ }
+ secondChild.exitCode = 1;
+ secondChild.emit('close', 1);
+ await flush();
+ expect(codex.cancelAll()).toBe(false);
+ });
+
+ it.each(['win32', 'linux'])('uses the same platform termination path for the %s wall-clock limit', async platform => {
+ setPlatform(platform);
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const job = await codex.generateImage({ prompt: 'stalled synthetic render', codexPath: '/example/codex.cmd' });
+ const child = spawnCalls[0].child;
+ child.pid = 4242;
+ await vi.advanceTimersByTimeAsync(20 * 60 * 1000);
+ if (platform === 'win32') {
+ expect(spawnCalls.at(-1)).toMatchObject({ bin: 'taskkill', args: ['/T', '/F', '/PID', '4242'] });
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(child.kill).not.toHaveBeenCalled();
+ expect(spawnCalls.filter(call => call.bin === 'taskkill')).toHaveLength(1);
+ } else {
+ expect(spawnCalls[0].bin).toBe('/example/codex.cmd');
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ await vi.advanceTimersByTimeAsync(4999);
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(child.kill).toHaveBeenLastCalledWith('SIGKILL');
+ }
+ child.exitCode = 1;
+ child.emit('close', 1);
+ await flush();
+ expect(codex.cancel(job.jobId)).toBe(false);
+ vi.clearAllTimers();
+ });
+});