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
fix(images): settle completion when backup admission rejects
[._.]/ Adam Eivy9968500d8f3b
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.jsindex 7003b7b216..2b26707b1f 100644--- a/server/services/imageGen/agy.js+++ b/server/services/imageGen/agy.js@@ -480,6 +480,12 @@ async function runAgy(job, jobId, bin, args, {// createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });}+ }).catch(err => {+ // Admission can reject before the publication callback is entered.+ // EventEmitter does not await this listener, so settle the job here too.+ clearTimeout(timeoutTimer);+ removeScratch();+ finalizeJobFailure(job, jobId, proc, `Agy publication admission failed: ${err?.message || err}`);});});}diff --git a/server/services/imageGen/agy.test.js b/server/services/imageGen/agy.test.jsindex 7911b846e6..e9e888f3fc 100644--- a/server/services/imageGen/agy.test.js+++ b/server/services/imageGen/agy.test.js@@ -6,6 +6,15 @@ import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'events';+const admissionFault = vi.hoisted(() => ({ error: null }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: (...args) => {+ if (admissionFault.error) return Promise.reject(admissionFault.error);+ return actual.withBackupAssetPublication(...args);+ } };+});+const spawnCalls = [];const makeFakeChild = () => {const child = new EventEmitter();@@ -384,3 +393,20 @@ describe('agy image provider', () => {expect(existsSync(join(FAKE_IMAGES_DIR, job.filename))).toBe(false);});});+++it('settles admission rejection from the actual close event and clears the active slot', async () => {+ const job = await agy.generateImage({ prompt: 'admission failure' });+ const child = spawnCalls[0].child;+ const failed = new Promise(resolve => imageGenEvents.once('failed', resolve));+ admissionFault.error = new Error('injected publication admission refusal');+ try {+ child.emit('close', 0, null);+ expect((await failed).error).toContain('injected publication admission refusal');+ expect(agy.getActiveJob()).toBeNull();+ const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };+ expect(agy.attachSseClient(job.jobId, response)).toBe(true);+ expect(response.write.mock.calls[0][0]).toContain('injected publication admission refusal');+ response.req.emit('close');+ } finally { admissionFault.error = null; }+});diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 52b5d94e1c..80d0bf54be 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -467,6 +467,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle// createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`, { force: true });}+ }).catch(err => {+ // Admission can reject before the publication callback is entered.+ // 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}`);});});}diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 1a2ab7a1f4..1c0ade4cdc 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -5,6 +5,15 @@ import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'events';+const admissionFault = vi.hoisted(() => ({ error: null }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: (...args) => {+ if (admissionFault.error) return Promise.reject(admissionFault.error);+ return actual.withBackupAssetPublication(...args);+ } };+});+// Each test runs against a synthetic ~/.codex layout so it never touches// the user's real generated_images dir. We mock os.homedir() directly —// node's homedir() uses getpwuid() on macOS and ignores $HOME, so just@@ -738,3 +747,20 @@ describe('codex provider — noImageReason (no-image diagnostics)', () => {expect(msg).not.toMatch(/\[\d+m/);});});+++it('settles admission rejection from the actual close event and clears the active slot', async () => {+ const job = await codex.generateImage({ prompt: 'admission failure' });+ const child = spawnCalls[0].child;+ const failed = new Promise(resolve => imageGenEvents.once('failed', resolve));+ admissionFault.error = new Error('injected publication admission refusal');+ try {+ child.emit('close', 0, null);+ expect((await failed).error).toContain('injected publication admission refusal');+ expect(codex.getActiveJob()).toBeNull();+ 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');+ response.req.emit('close');+ } finally { admissionFault.error = null; }+});diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.jsindex 8f87ccf8d7..b2d24a0de8 100644--- a/server/services/imageGen/grok.js+++ b/server/services/imageGen/grok.js@@ -448,6 +448,13 @@ async function runGrok(job, jobId, bin, args, {// createJobFailureFinalizer's doc comment in sseUtils.js.finalizeJobFailure(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`, { force: true });}+ }).catch(err => {+ // Admission can reject before the publication callback is entered.+ // EventEmitter does not await this listener, so settle the job here too.+ clearTimeout(timeoutTimer);+ cleanupPromptFile();+ removeScratch();+ finalizeJobFailure(job, jobId, proc, `Grok publication admission failed: ${err?.message || err}`);});});}diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.jsindex d3a40777af..97499347fc 100644--- a/server/services/imageGen/grok.test.js+++ b/server/services/imageGen/grok.test.js@@ -2,6 +2,15 @@ import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { posixPath } from '../../lib/testHelper.js';+const admissionFault = vi.hoisted(() => ({ error: null }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: (...args) => {+ if (admissionFault.error) return Promise.reject(admissionFault.error);+ return actual.withBackupAssetPublication(...args);+ } };+});+import { mkdir, writeFile, rm, readFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';@@ -504,3 +513,20 @@ describe('grok provider — checkConnection', () => {expect(status.reason).toMatch(/exited 3/);});});+++it('settles admission rejection from the actual close event and clears the active slot', async () => {+ const job = await grok.generateImage({ prompt: 'admission failure' });+ const child = spawnCalls[0].child;+ const failed = new Promise(resolve => imageGenEvents.once('failed', resolve));+ admissionFault.error = new Error('injected publication admission refusal');+ try {+ child.emit('close', 0, null);+ expect((await failed).error).toContain('injected publication admission refusal');+ expect(grok.getActiveJob()).toBeNull();+ const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };+ expect(grok.attachSseClient(job.jobId, response)).toBe(true);+ expect(response.write.mock.calls[0][0]).toContain('injected publication admission refusal');+ response.req.emit('close');+ } finally { admissionFault.error = null; }+});diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.jsindex 3042962ee6..81bb5787ab 100644--- a/server/services/imageGen/local.js+++ b/server/services/imageGen/local.js@@ -1189,6 +1189,25 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =} finally {closeJobAfterDelay(jobs, jobId);}+ }).catch(async err => {+ // Admission failure happens before the inner finalizer can clear the+ // process slot or release its heavy-job claim. Settle without publishing+ // or deleting gallery bytes outside the refused boundary.+ if (finalized) return;+ finalized = true;+ activeProcess = null;+ activeJob = null;+ if (watcher) { try { watcher.close(); } catch { /* ignore */ } }+ await Promise.all([releaseHeavyClaim(), removeStepwise()]);+ const reason = err?.message || String(err);+ job.status = 'error';+ job.error = reason;+ dispatchTerminalEvent(+ jobId,+ () => broadcastSse(job, { type: 'error', error: reason }),+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason }),+ );+ closeJobAfterDelay(jobs, jobId);});});diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.jsindex 6741686173..4a0ab44782 100644--- a/server/services/imageGen/local.test.js+++ b/server/services/imageGen/local.test.js@@ -4,12 +4,22 @@ import { join } from 'path';import { tmpdir } from 'os';import { EventEmitter } from 'node:events';+const admissionFault = vi.hoisted(() => ({ error: null }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: (...args) => {+ if (admissionFault.error) return Promise.reject(admissionFault.error);+ return actual.withBackupAssetPublication(...args);+ } };+});+// These lifecycle tests drive the child directly; preview watchers are unrelated.vi.mock('fs', async original => ({ ...await original(), watch: vi.fn(() => ({ close() {} })) }));const mockSpawn = vi.fn();vi.mock('../../lib/childProcess.js', async (original) => ({ ...await original(), spawn: (...args) => mockSpawn(...args) }));-vi.mock('../../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: async () => ({ ok: true, release: async () => {} }) }));+const releaseClaim = vi.fn(async () => {});+vi.mock('../../lib/heavyJobClaim.js', () => ({ claimHeavyLocalJob: async () => ({ ok: true, release: releaseClaim }) }));vi.mock('../localMemory.js', () => ({ gpuBlockersMessage: vi.fn(), prepareLocalMemory: async () => ({ blockers: [], unloaded: [] }) }));vi.mock('../hfToken.js', () => ({ hfChildEnv: async () => ({}) }));vi.mock('../../lib/fileUtils.js', async (original) => ({ ...await original(), ensureDir: vi.fn() }));@@ -1240,3 +1250,32 @@ it('drains a snapshot through local upscale and the sidecar naming the delivered.toMatchObject({ width: 128, height: 128, renderWidth: 64, renderHeight: 64 });} finally { release(); }});+++it('settles a refused close-event publication and releases the process and heavy claim', async () => {+ mockResolveFlux2Python.mockReturnValue('/fake/venv-flux2/bin/python3');+ mockIsFlux2VenvHealthy.mockResolvedValue(true);+ const child = new EventEmitter();+ child.stdout = new EventEmitter(); child.stderr = new EventEmitter();+ mockSpawn.mockReturnValue(child);+ const { imageGenEvents } = await import('../imageGenEvents.js');+ const { attachSseClient, getActiveJob } = await import('./local.js');+ const { SSE_CLEANUP_DELAY_MS } = await import('../../lib/sseUtils.js');+ const { jobId } = await generateImage({ modelId: 'qwen-image-2.1', prompt: 'admission failure' });+ const releasedBefore = releaseClaim.mock.calls.length;+ const failed = new Promise(resolve => imageGenEvents.once('failed', resolve));+ admissionFault.error = new Error('injected publication admission refusal');+ vi.useFakeTimers();+ try {+ child.emit('close', 0);+ expect((await failed).error).toContain('injected publication admission refusal');+ expect(getActiveJob()).toBeNull();+ expect(releaseClaim.mock.calls.length).toBe(releasedBefore + 1);+ const response = { writeHead: vi.fn(), write: vi.fn(), end: vi.fn(), req: new EventEmitter() };+ expect(attachSseClient(jobId, response)).toBe(true);+ expect(response.write.mock.calls[0][0]).toContain('injected publication admission refusal');+ response.req.emit('close');+ vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS);+ expect(attachSseClient(jobId, response)).toBe(false);+ } finally { admissionFault.error = null; vi.useRealTimers(); }+});