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 4: 4 Copilot findings on PR #181
Adam Eivy68b6c53e3993
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex eaaaa8c63a..97ab883e18 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -166,7 +166,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {proc.on('error', (err) => {clearTimeout(timeoutTimer);- finalizeError(job, jobId, `Failed to spawn ${bin}: ${err.message}`);+ finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);});proc.stdout.on('data', (chunk) => {@@ -184,7 +184,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {proc.on('close', async (code, signal) => {clearTimeout(timeoutTimer);- activeProcess = null;+ // Don't clear activeProcess yet — the post-exit handler still does+ // async work (harvest + copyFile + sidecar). Clearing the+ // module-scoped guard up front would let a new generation start+ // while we're still finalizing this one, then the in-flight+ // finalizer could clobber the new job's activeJob snapshot.// 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@@ -193,10 +197,10 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {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}`);+ return finalizeError(job, jobId, proc, `Codex generation failed: ${reason}\n${tail}`);}if (!sessionId) {- return finalizeError(job, jobId, 'Codex returned no session id — output format may have changed');+ return finalizeError(job, jobId, proc, '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@@ -204,7 +208,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {const harvested = await harvestLatestImage(sessionId, 5000);if (!harvested) {return finalizeError(- job, jobId,+ job, jobId, proc,'Codex returned no image — your Codex account may not allow image_gen, or the model declined. Check Settings → Image Gen → Enable Codex Imagegen.',);}@@ -213,30 +217,37 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta) {const sidecar = join(PATHS.images, `${jobId}.metadata.json`);await writeFile(sidecar, JSON.stringify(meta, null, 2)).catch(() => {});job.status = 'complete';- activeJob = null;+ // Only clear if still ours — a userland cancel that started a+ // newer job could have replaced these references while our+ // harvest was running.+ if (activeProcess === proc) activeProcess = null;+ if (activeJob && activeJob.generationId === jobId) 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}`);+ finalizeError(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`);}});}-const finalizeError = (job, jobId, reason) => {+// `proc` is the child this finalize belongs to — pass it through so we+// only clear module-scoped state when it still belongs to *this* job.+// A late finalize from a cancelled or stale run must not wipe a newer+// job that has already become active.+const finalizeError = (job, jobId, proc, reason) => {// Idempotent — spawn failures fire 'error' AND a follow-up 'close', so// both paths reach finalizeError. Without this guard, listeners would// see duplicate 'failed' events.if (job.status === 'error' || job.status === 'complete') return;- // Clear activeProcess too. The 'close' handler does this for normal exits,- // but a spawn failure (ENOENT, EACCES) routes through 'error' before any- // 'close' may fire — without this, a single bad codexPath would- // permanently lock the provider into 409 BUSY for every later request.- activeProcess = null;+ // Clear activeProcess only if it's still the proc we own. Without+ // this, a single bad codexPath would permanently lock the provider+ // into 409 BUSY (the 'close' handler also clears it on success path).+ if (proc == null || activeProcess === proc) activeProcess = null;job.status = 'error';- activeJob = null;+ if (activeJob && activeJob.generationId === jobId) activeJob = null;console.log(`❌ codex image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);broadcastSse(job, { type: 'error', error: reason });imageGenEvents.emit('failed', { generationId: jobId, error: reason });diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 21ed90a47f..c1b320a053 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -225,47 +225,54 @@ 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'.+ // 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 in the close handler, the async EventEmitter+ // listener would surface an unhandled rejection and leave the job stuck+ // in 'running'.+ // Skip on Windows: POSIX read-only chmod doesn't reliably block writes+ // there, and ESM `vi.spyOn(fs/promises, 'copyFile')` errors with+ // "Cannot redefine property: copyFile" because module namespaces aren't+ // configurable in ESM. macOS/Linux are the platforms PortOS actually+ // runs on; this regression-locks the fix where it matters.+ const itPosix = process.platform === 'win32' ? it.skip : it;+ itPosix('routes async errors in the close handler through finalizeError (no unhandled rejections)', async () => {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);+ const failedListener = vi.fn();+ imageGenEvents.on('failed', failedListener);+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));+ try {+ 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));+ }++ expect(failedListener).toHaveBeenCalledTimes(1);+ expect(failedListener.mock.calls[0][0].error).toMatch(/post-exit handler failed/i);+ expect(unhandled).toBeNull();+ } finally {+ // Restore write perms so afterEach cleanup can rm the tree.+ await chmod(FAKE_IMAGES_DIR, 0o755).catch(() => {});+ process.off('unhandledRejection', onUnhandled);}-- // 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 () => {diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex a5cfbca8db..1584218c8c 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -91,9 +91,20 @@ export async function generateAvatar({ name, characterClass, prompt }) {// Snapshot of any in-flight generation across all modes — lets the UI// rehydrate prompt + settings + progress + last frame after navigating away-// during a render.+// during a render. Each provider enforces its own single-job invariant+// (cancel() relies on this — see the note there), so up to three jobs can+// be in flight concurrently. Return the most-recently-started one based on+// `createdAt`, falling back to provider order if timestamps are missing.+// Callers wanting all of them can read individual providers via the+// re-exports below.export async function getActiveJob() {- return local.getActiveJob() || external.getActiveJob() || codex.getActiveJob() || null;+ const jobs = [local.getActiveJob(), external.getActiveJob(), codex.getActiveJob()].filter(Boolean);+ if (!jobs.length) return null;+ return jobs.sort((a, b) => {+ const ta = a.createdAt ? Date.parse(a.createdAt) : 0;+ const tb = b.createdAt ? Date.parse(b.createdAt) : 0;+ return tb - ta;+ })[0];}// Try-each-provider SSE attach + cancel — the route only knows the jobId,