Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
address review round 3: route async close-handler errors through finalizeError
Adam Eivyc1f0896ce4e0
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 468708a936..eaaaa8c63a 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -185,35 +185,43 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {proc.on('close', async (code, signal) => {clearTimeout(timeoutTimer);activeProcess = null;- 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, `Codex generation failed: ${reason}\n${tail}`);- }- if (!sessionId) {- return finalizeError(job, jobId, 'Codex returned no session id — output format may have changed');- }- // Codex writes the PNG asynchronously while it's wrapping up the turn.- // Empirically the file is on disk by the time `codex exec` exits, but- // poll for a few seconds in case there's a flush lag on slow disks.- const harvested = await harvestLatestImage(sessionId, 5000);- if (!harvested) {- return finalizeError(- job, jobId,- 'Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.',- );+ // EventEmitter doesn't await async listeners — without this try/catch,+ // a throw from harvestLatestImage / copyFile would surface as an+ // unhandled rejection (process-killing on Node ≥15) and the job would+ // be stuck in 'running' forever with no SSE error to the client.+ 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, `Codex generation failed: ${reason}\n${tail}`);+ }+ if (!sessionId) {+ return finalizeError(job, jobId, 'Codex returned no session id — output format may have changed');+ }+ // Codex writes the PNG asynchronously while it's wrapping up the turn.+ // Empirically the file is on disk by the time `codex exec` exits, but+ // poll for a few seconds in case there's a flush lag on slow disks.+ const harvested = await harvestLatestImage(sessionId, 5000);+ if (!harvested) {+ return finalizeError(+ job, jobId,+ 'Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.',+ );+ }+ await copyFile(harvested, outputPath);+ // Sidecar metadata so the gallery can recover prompt/seed/etc.+ const sidecar = join(PATHS.images, `${jobId}.metadata.json`);+ await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});+ job.status = 'complete';+ activeJob = null;+ console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);+ 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, `Codex post-exit handler failed: ${err?.message || err}`);}- await copyFile(harvested, outputPath);- // Sidecar metadata so the gallery can recover prompt/seed/etc.- const sidecar = join(PATHS.images, `${jobId}.metadata.json`);- await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});- job.status = 'complete';- activeJob = null;- console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (codex)`);- 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);});}diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex a73aa3dfa4..21ed90a47f 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -225,6 +225,49 @@ describe('codex provider — image harvest', () => {await flush();});+ it('routes async errors in the close handler through finalizeError (no unhandled rejections)', async () => {+ // Simulate copyFile throwing — happens in the wild when data/images is+ // read-only, the disk is full, or the harvested PNG is unreadable.+ // Without the try/catch the async EventEmitter listener would surface+ // an unhandled rejection and leave the job stuck in 'running'.+ const sessionId = '11111111-1111-4111-8111-111111111111';+ const codexDir = join(TEST_HOME, '.codex', 'generated_images', sessionId);+ await mkdir(codexDir, { recursive: true });+ await writeFile(join(codexDir, 'ig_a.png'), Buffer.from('x'));++ const failedListener = vi.fn();+ imageGenEvents.on('failed', failedListener);++ // Force copyFile to throw by removing write access on FAKE_IMAGES_DIR+ // — easier than mocking fs/promises which is already partially mocked.+ await mkdir(FAKE_IMAGES_DIR, { recursive: true });+ const { chmod } = await import('fs/promises');+ await chmod(FAKE_IMAGES_DIR, 0o555);++ let unhandled = null;+ const onUnhandled = (reason) => { unhandled = reason; };+ process.on('unhandledRejection', onUnhandled);++ await codex.generateImage({ prompt: 'a fox' });+ const child = spawnCalls[0].child;+ child.stderr.emit('data', Buffer.from(`session id: ${sessionId}\n`));+ child.exitCode = 0;+ child.emit('close', 0, null);++ const deadline = Date.now() + 4000;+ while (Date.now() < deadline && failedListener.mock.calls.length === 0) {+ await new Promise((r) => setTimeout(r, 50));+ }++ // Restore write perms so afterEach cleanup can rm the tree.+ await chmod(FAKE_IMAGES_DIR, 0o755);+ process.off('unhandledRejection', onUnhandled);++ expect(failedListener).toHaveBeenCalledTimes(1);+ expect(failedListener.mock.calls[0][0].error).toMatch(/post-exit handler failed/i);+ expect(unhandled).toBeNull();+ }, 8000);+it('emits a failed event when codex exits non-zero', async () => {const failedListener = vi.fn();imageGenEvents.on('failed', failedListener);