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

refactor: share one job-failure finalizer across the six media backends (#6830)

[._.]/ Adam Eivya6fc6f1f9554
diff --git a/server/lib/README.md b/server/lib/README.md
index 861689e113..52f3f8351a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -584,7 +584,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `singleFlight.js` | `createSingleFlight()` → `run(key, fn)` — keyed in-flight coalescer: concurrent calls for the same key share one `fn()` execution and result; the slot auto-clears on settle. Minimal by design (no TTL/result cache layered on top, doesn't reject concurrent callers). Used by `services/promptRunner.js`'s fallback mark-and-pick. |
| `staleWhileRevalidate.js` | `createStaleWhileRevalidate({ ttlMs, failureBackoffMs?, isComplete?, partialTtlMs? })` → `read(key, produce, { wait })` / `clear(key?)` — TTL cache that serves a STALE value immediately and revalidates behind the caller, for readings too slow to block on (10-20s CLI/PTY spawns). `wait`: `'fresh'` bypasses and blocks, `'cached'` (default) blocks only on a cold cache, `'never'` returns the `PENDING` symbol on a cold cache for UIs that render "still reading" and poll. Failures keep the last good value and back off; a cold cache whose producer failed throws rather than promising a reading that isn't coming. Used by `providerUsage.js` (TUI scrapes) and `claudeCodeUsage.js`. |
| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `buildStaticImportGraph(rootDir)` → `Map<relPath, relPath[]>` of one directory's internal static edges (recurses into subdirectories, skips `.test.js`); `listModuleFiles(rootDir)` → every non-test `.js` under a directory, keyed by `/`-separated relative path (the same walk the graph builder uses, shared so a layering guard cannot drift from it); `findImportCycles(graph)` → each cycle rendered as `a.js -> b.js -> a.js` (depth-first, so WHICH rings it names depends on where the walk enters a component — fine for an "is this empty?" assertion, unusable as a baseline); `findImportCycleComponents(graph)` → the cyclic strongly-connected components as sorted member lists, traversal-order invariant and therefore baselineable (#5693); `specifierMatchesPackage(spec, pkg)` matches a package or any subpath; `toModuleKey(relPath)` is the one graph-key mint — always `/`-separated, because the keys are built two ways (entry-name concatenation vs `path.relative`) and Windows spells the second one with `\`, which silently dropped every edge into a subdirectory module and made the acyclicity guards pass vacuously there (#5909). Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `serviceImportCycles.test.js` (the tree-wide cycle ratchet), `agentImportCycles.test.js` and `twinImportCycles.test.js` (per-cluster acyclicity) and `spriteAnimationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
-| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
+| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. `createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? })` — the shared job-failure finalizer (idempotency guard w/ `force` escape hatch, slot-owner clear, SSE error frame, `failed` event, `closeJobAfterDelay`) behind all six media-generation backends (`imageGen/{agy,codex,grok}.js`, `videoGen/{grok,fal,reactor}.js`). |
| `streamAttachment.js` | `streamAttachment(res,stream,{filename,contentType,failure,label})` — pipe a readable to a response as a file download. Sets the attachment headers plus `X-Content-Type-Options:nosniff`, and owns the teardown every attachment route needs: a pre-stream failure drops the download headers and returns `failure` via `sendErrorResponse`, a mid-stream failure destroys the socket (the envelope no-ops once headers are sent), and a client disconnect calls `stream.abort?.()` so an upstream child process is torn down. Shared by `routes/imageTo3d.js` (GLB, full-mesh) and `routes/backup.js` (snapshot tarball). |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. |
diff --git a/server/lib/sseUtils.js b/server/lib/sseUtils.js
index f668612b09..284742bd04 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -85,6 +85,50 @@ export const closeJobAfterDelay = (jobs, jobId, delay = SSE_CLEANUP_DELAY_MS, ex
}, delay);
};
+// Shared "this job died" finalizer for the six media-generation backends
+// (imageGen/{agy,codex,grok}.js, videoGen/{grok,fal,reactor}.js). Each used to
+// carry a private ~10-line `finalizeError` doing the same eight things —
+// idempotency guard, clear the active-slot map, stamp `job.status = 'error'`,
+// drop from `activeJobs`, log, broadcast an SSE error frame, emit `failed`,
+// and `closeJobAfterDelay` — which had drifted (#6830): the video backends
+// picked up a `force` escape hatch (fa3796650) for a throw that lands AFTER
+// `job.status` is already stamped 'complete' (finalizeGeneratedVideo/the
+// image copy-and-clean tail failing during their own post-processing), and
+// the three image backends never did, so that same failure silently hit the
+// idempotency guard's no-op instead of ever reaching the client or the queue.
+//
+// `activeSlots` is the per-jobId "who owns this render" map — `activeProcs`
+// for the CLI-spawn backends (agy/codex/imageGen-grok/videoGen-grok, keyed by
+// the child process) or `activeRequests` for the REST-poll backends (fal,
+// reactor). The returned finalizer takes `slotOwner` per call: pass the
+// current owner (the `proc`/request entry) to clear the slot only when it
+// still belongs to THIS job — a late finalize from a cancelled/stale run must
+// not wipe a newer job's active slot — or pass `null` for a backend whose
+// slot map has no owner identity to compare, which deletes unconditionally
+// (fal/reactor's pre-factory behavior).
+//
+// `failedPayload(jobId, reason)` builds the `events.emit('failed', …)` body.
+// It defaults to the video shape (`{ generationId, error }`); the image
+// backends override it to add the `mode` field their event bus carries
+// (read by `imageGenQuota.js`'s per-provider outcome recorder).
+export const createJobFailureFinalizer = ({
+ jobs, activeJobs, activeSlots, label, events,
+ failedPayload = (jobId, reason) => ({ generationId: jobId, error: reason }),
+}) => (job, jobId, slotOwner, reason, { force = false } = {}) => {
+ // Idempotent except under `force` — spawn failures fire 'error' AND a
+ // follow-up 'close', so both paths reach this finalizer, and a caller
+ // whose success path can throw AFTER stamping 'complete' passes `force`
+ // to still deliver a terminal 'failed' for that window.
+ if (!force && (job.status === 'error' || job.status === 'complete')) return;
+ if (slotOwner == null || activeSlots.get(jobId) === slotOwner) activeSlots.delete(jobId);
+ job.status = 'error';
+ activeJobs.delete(jobId);
+ console.log(`❌ ${label} failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ events.emit('failed', failedPayload(jobId, reason));
+ closeJobAfterDelay(jobs, jobId);
+};
+
// ---------------------------------------------------------------------------
// createSseRunner — shared batch-runner lifecycle for the pipeline runners.
// ---------------------------------------------------------------------------
diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.js
index 14d12c31eb..0a7e4f92ed 100644
--- a/server/lib/sseUtils.test.js
+++ b/server/lib/sseUtils.test.js
@@ -5,6 +5,7 @@ import {
broadcastSse,
attachSseClient,
closeJobAfterDelay,
+ createJobFailureFinalizer,
createSseRunner
} from './sseUtils.js';
@@ -185,6 +186,108 @@ describe('closeJobAfterDelay', () => {
});
});
+describe('createJobFailureFinalizer', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ const setup = (overrides = {}) => {
+ const jobs = new Map();
+ const activeJobs = new Map();
+ const activeSlots = new Map();
+ const events = { emit: vi.fn() };
+ const finalize = createJobFailureFinalizer({
+ jobs, activeJobs, activeSlots, events, label: 'test backend', ...overrides,
+ });
+ return { jobs, activeJobs, activeSlots, events, finalize };
+ };
+
+ it('stamps error, clears the owned slot, emits failed (default payload), and schedules cleanup', () => {
+ const { jobs, activeJobs, activeSlots, events, finalize } = setup();
+ const proc = { pid: 1 };
+ const client = makeRes();
+ const job = { clients: [client], status: 'running' };
+ jobs.set('j1', job);
+ activeJobs.set('j1', { id: 'j1' });
+ activeSlots.set('j1', proc);
+
+ finalize(job, 'j1', proc, 'boom');
+
+ expect(job.status).toBe('error');
+ expect(activeSlots.has('j1')).toBe(false);
+ expect(activeJobs.has('j1')).toBe(false);
+ expect(events.emit).toHaveBeenCalledWith('failed', { generationId: 'j1', error: 'boom' });
+ expect(client.write).toHaveBeenCalledWith(`data: ${JSON.stringify({ type: 'error', error: 'boom' })}\n\n`);
+
+ // closeJobAfterDelay was scheduled as part of the same call.
+ vi.advanceTimersByTime(SSE_CLEANUP_DELAY_MS);
+ expect(client.end).toHaveBeenCalled();
+ expect(jobs.has('j1')).toBe(false);
+ });
+
+ it('is idempotent once the job is already terminal — a duplicate spawn-error/close pair does not double-emit', () => {
+ const { activeSlots, activeJobs, events, finalize } = setup();
+ const proc = { pid: 1 };
+ const job = { clients: [], status: 'complete' };
+ activeSlots.set('j1', proc);
+ activeJobs.set('j1', {});
+
+ finalize(job, 'j1', proc, 'boom');
+
+ expect(job.status).toBe('complete');
+ expect(activeSlots.has('j1')).toBe(true);
+ expect(activeJobs.has('j1')).toBe(true);
+ expect(events.emit).not.toHaveBeenCalled();
+ });
+
+ it('force overrides the idempotency guard for a throw that lands after complete is already stamped', () => {
+ const { activeJobs, events, finalize } = setup();
+ const job = { clients: [], status: 'complete' };
+ activeJobs.set('j1', {});
+
+ finalize(job, 'j1', { pid: 1 }, 'threw after complete', { force: true });
+
+ expect(job.status).toBe('error');
+ expect(activeJobs.has('j1')).toBe(false);
+ expect(events.emit).toHaveBeenCalledWith('failed', { generationId: 'j1', error: 'threw after complete' });
+ });
+
+ it('does not evict a slot a newer job already owns (stale finalize from a cancelled/superseded run)', () => {
+ const { activeSlots, finalize } = setup();
+ const staleProc = { pid: 1 };
+ const freshProc = { pid: 2 };
+ const job = { clients: [], status: 'running' };
+ activeSlots.set('j1', freshProc);
+
+ finalize(job, 'j1', staleProc, 'stale failure');
+
+ // The stale finalize still fails ITS OWN job record...
+ expect(job.status).toBe('error');
+ // ...but must not evict the newer run's slot ownership.
+ expect(activeSlots.get('j1')).toBe(freshProc);
+ });
+
+ it('clears the slot unconditionally when slotOwner is null (fal/reactor have no owner identity to compare)', () => {
+ const { activeSlots, finalize } = setup();
+ const job = { clients: [], status: 'running' };
+ activeSlots.set('j1', { some: 'request-entry' });
+
+ finalize(job, 'j1', null, 'boom');
+
+ expect(activeSlots.has('j1')).toBe(false);
+ });
+
+ it('builds the failed payload with a custom failedPayload (the image bus mode field)', () => {
+ const { events, finalize } = setup({
+ failedPayload: (jobId, reason) => ({ mode: 'grok', generationId: jobId, error: reason }),
+ });
+ const job = { clients: [], status: 'running' };
+
+ finalize(job, 'j1', null, 'boom');
+
+ expect(events.emit).toHaveBeenCalledWith('failed', { mode: 'grok', generationId: 'j1', error: 'boom' });
+ });
+});
+
describe('createSseRunner', () => {
// Flush the microtask queue enough times for the fire-and-forget IIFE
// (try → await work → finally) to settle. Real promises are not faked even
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index 8d0b1a4deb..f9f56b7dde 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -29,7 +29,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { buildNoImageReason } from './noImageReason.js';
import { rejectDegenerateFrame } from './frameGuard.js';
@@ -340,7 +340,7 @@ async function runAgy(job, jobId, bin, args, {
proc.on('error', (err) => {
clearTimeout(timeoutTimer);
removeScratch();
- finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
proc.on('close', async (code, signal) => {
clearTimeout(timeoutTimer);
@@ -348,13 +348,13 @@ async function runAgy(job, jobId, bin, args, {
if (code !== 0) {
removeScratch();
const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
- return finalizeError(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);
+ return finalizeJobFailure(job, jobId, proc, `Agy generation failed: ${reason}\n${stderrTail.trim().split('\n').slice(-6).join('\n')}`);
}
const harvested = await harvestStagedImage(stagingPath, harvestTimeoutMs);
if (!harvested.found) {
removeScratch();
const prefix = harvested.invalid ? 'Agy wrote a non-image file at the directed path. ' : '';
- return finalizeError(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
+ return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
}
// A PNG landed — but the harvest gate only proves it is image bytes, not
// that generate_image made them. Reject a file the agent drew itself.
@@ -364,7 +364,7 @@ async function runAgy(job, jobId, bin, args, {
const fabricated = await checkFabrication(scratchDir, AGY_TOOL);
if (fabricated) {
removeScratch();
- return finalizeError(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
+ return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
}
if (harvested.format === 'png') {
await copyFileGuarded(stagingPath, outputPath);
@@ -378,7 +378,7 @@ async function runAgy(job, jobId, bin, args, {
// contentless canvas never becomes a gallery record.
const emptyFrame = await rejectDegenerateFrame(outputPath);
if (emptyFrame) {
- return finalizeError(job, jobId, proc, emptyFrame);
+ return finalizeJobFailure(job, jobId, proc, emptyFrame);
}
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
// `job.renderStartedAtMs` is the queue-ingestion instant generateImage
@@ -402,21 +402,24 @@ async function runAgy(job, jobId, bin, args, {
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
- finalizeError(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`);
+ // finalizeJobFailure is a no-op once job.status === 'complete' — but the
+ // success path above stamps 'complete' BEFORE its own broadcastSse/
+ // event-emit tail, so a throw from there still needs a terminal
+ // 'failed' delivered. Force past the idempotency guard (matches
+ // videoGen/grok.js's post-exit catch, fa3796650).
+ finalizeJobFailure(job, jobId, proc, `Agy post-exit handler failed: ${err?.message || err}`, { force: true });
}
});
}
-const finalizeError = (job, jobId, proc, reason) => {
- if (job.status === 'error' || job.status === 'complete') return;
- if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
- job.status = 'error';
- activeJobs.delete(jobId);
- console.log(`❌ agy image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeProcs,
+ label: 'agy image generation',
+ events: imageGenEvents,
+ failedPayload: (jobId, reason) => ({ mode: IMAGE_GEN_MODE.AGY, generationId: jobId, error: reason }),
+});
async function harvestStagedImage(stagingPath, timeoutMs) {
const deadline = Date.now() + timeoutMs;
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index b3229de4c5..fb02d34860 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -39,7 +39,7 @@ import { atomicWrite, copyFileGuarded, ensureDir, PATHS } from '../../lib/fileUt
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { buildCodexStartupArgs, buildEffortArgs, resolveCliEffort } from '../../lib/providerModels.js';
@@ -366,7 +366,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
proc.on('error', (err) => {
clearTimeout(timeoutTimer);
- finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
proc.stdout.on('data', (chunk) => {
@@ -404,17 +404,17 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
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, proc, `Codex generation failed: ${reason}\n${tail}`);
+ return finalizeJobFailure(job, jobId, proc, `Codex generation failed: ${reason}\n${tail}`);
}
if (!sessionId) {
- return finalizeError(job, jobId, proc, 'Codex returned no session id — output format may have changed');
+ return finalizeJobFailure(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
// poll for a few seconds in case there's a flush lag on slow disks.
const harvested = await harvestGeneratedImage(sessionId, harvestTimeoutMs);
if (!harvested) {
- return finalizeError(job, jobId, proc, noImageReason(stdoutTail));
+ return finalizeJobFailure(job, jobId, proc, noImageReason(stdoutTail));
}
if (harvested.path) {
await copyFileGuarded(harvested.path, outputPath);
@@ -425,7 +425,7 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
// contentless canvas never becomes a gallery record.
const emptyFrame = await rejectDegenerateFrame(outputPath);
if (emptyFrame) {
- return finalizeError(job, jobId, proc, emptyFrame);
+ return finalizeJobFailure(job, jobId, proc, emptyFrame);
}
// Sidecar metadata so the gallery can recover prompt/seed/etc. The
// codex sessionId is the closest analogue to a seed for gpt-image-2
@@ -450,28 +450,24 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
- finalizeError(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`);
+ // finalizeJobFailure is a no-op once job.status === 'complete' — but the
+ // success path above stamps 'complete' BEFORE its own broadcastSse/
+ // event-emit tail, so a throw from there still needs a terminal
+ // 'failed' delivered. Force past the idempotency guard (matches
+ // videoGen/grok.js's post-exit catch, fa3796650).
+ finalizeJobFailure(job, jobId, proc, `Codex post-exit handler failed: ${err?.message || err}`, { force: true });
}
});
}
-// `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;
- if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
- job.status = 'error';
- activeJobs.delete(jobId);
- console.log(`❌ codex image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeProcs,
+ label: 'codex image generation',
+ events: imageGenEvents,
+ failedPayload: (jobId, reason) => ({ mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, error: reason }),
+});
// Returns the absolute path to the newest PNG in the session dir. Codex has
// used both `ig_*.png` and `exec-*.png`; the per-session directory is already
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index 88cca9f963..d199b05997 100644
--- a/server/services/imageGen/grok.js
+++ b/server/services/imageGen/grok.js
@@ -41,7 +41,7 @@ import { atomicWrite, copyFileGuarded, detectImageFormat, ensureDir, PATHS, rmGu
import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { imageGenEvents } from '../imageGenEvents.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { buildNoImageReason } from './noImageReason.js';
@@ -349,7 +349,7 @@ async function runGrok(job, jobId, bin, args, {
clearTimeout(timeoutTimer);
cleanupPromptFile();
removeScratch();
- finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
proc.stdout.on('data', (chunk) => {
@@ -374,7 +374,7 @@ async function runGrok(job, jobId, bin, args, {
const reason = signal ? `Killed by signal ${signal}` : `Exit code ${code}`;
const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
removeScratch();
- return finalizeError(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);
+ return finalizeJobFailure(job, jobId, proc, `Grok generation failed: ${reason}\n${tail}`);
}
// Grok writes the file during the turn; empirically it's on disk by
// exit, but poll a few seconds in case of flush lag on slow disks. The
@@ -384,7 +384,7 @@ async function runGrok(job, jobId, bin, args, {
if (!harvested.found) {
removeScratch();
const prefix = harvested.invalid ? 'Grok wrote a non-image file at the directed path. ' : '';
- return finalizeError(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
+ return finalizeJobFailure(job, jobId, proc, `${prefix}${noImageReason(stdoutTail)}`);
}
// Image bytes are not proof the image tool made them — reject a picture
// the agent drew with code (see fabricationGuard.js). The narration tail
@@ -393,7 +393,7 @@ async function runGrok(job, jobId, bin, args, {
const fabricated = await checkFabrication(scratchDir, toolName);
if (fabricated) {
removeScratch();
- return finalizeError(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
+ return finalizeJobFailure(job, jobId, proc, `${fabricated} ${noImageReason(stdoutTail)}`);
}
if (harvested.format === 'png') {
await copyFileGuarded(stagingPath, outputPath);
@@ -410,7 +410,7 @@ async function runGrok(job, jobId, bin, args, {
// canvas must fail here, not become a gallery record.
const emptyFrame = await rejectDegenerateFrame(outputPath);
if (emptyFrame) {
- return finalizeError(job, jobId, proc, emptyFrame);
+ return finalizeJobFailure(job, jobId, proc, emptyFrame);
}
// Sidecar metadata so the gallery can recover prompt/ratio/etc.
const sidecar = join(PATHS.images, `${jobId}.metadata.json`);
@@ -431,25 +431,24 @@ async function runGrok(job, jobId, bin, args, {
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
- finalizeError(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`);
+ // finalizeJobFailure is a no-op once job.status === 'complete' — but the
+ // success path above stamps 'complete' BEFORE its own broadcastSse/
+ // event-emit tail, so a throw from there still needs a terminal
+ // 'failed' delivered. Force past the idempotency guard (matches
+ // videoGen/grok.js's post-exit catch, fa3796650).
+ finalizeJobFailure(job, jobId, proc, `Grok post-exit handler failed: ${err?.message || err}`, { force: true });
}
});
}
-// `proc` is the child this finalize belongs to — only clear module-scoped
-// state when it still belongs to *this* job (a late finalize from a stale run
-// must not wipe a newer active job).
-const finalizeError = (job, jobId, proc, reason) => {
- // Idempotent — spawn failures fire 'error' AND a follow-up 'close'.
- if (job.status === 'error' || job.status === 'complete') return;
- if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
- job.status = 'error';
- activeJobs.delete(jobId);
- console.log(`❌ grok image generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeProcs,
+ label: 'grok image generation',
+ events: imageGenEvents,
+ failedPayload: (jobId, reason) => ({ mode: IMAGE_GEN_MODE.GROK, generationId: jobId, error: reason }),
+});
// Poll for the directed output file until it exists non-empty AND carries a
// real image signature (PNG/JPEG/WebP/GIF via the shared detectImageFormat
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
index 50f61fc96d..555eefdb8a 100644
--- a/server/services/imageGen/grok.test.js
+++ b/server/services/imageGen/grok.test.js
@@ -374,6 +374,45 @@ describe('grok provider — directed-path harvest', () => {
expect(failedListener).toHaveBeenCalledTimes(1);
expect(failedListener.mock.calls[0][0].error).toMatch(/Failed to spawn grok/);
});
+
+ // Regression (#6830): the success path stamps job.status = 'complete'
+ // BEFORE its own broadcastSse('complete') + imageGenEvents 'completed'
+ // tail, so a throw from that tail — a subscriber's res.write failing
+ // inside broadcastSse, same as any throw the surrounding catch was written
+ // to contain — used to hit the idempotency guard as a silent no-op: no
+ // 'failed' event, job stuck reading 'complete' with no terminal frame ever
+ // delivered. videoGen/grok.js already forces past this window (fa3796650);
+ // the three image backends never did until the shared finalizer's `force`
+ // option was threaded through their post-exit catches.
+ it('still emits failed when the post-exit handler throws after job.status is already complete', async () => {
+ const failedListener = vi.fn();
+ imageGenEvents.on('failed', failedListener);
+
+ const job = await grok.generateImage({ prompt: 'a fox' });
+ const fakePngBytes = Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ Buffer.from('fakepngbody'),
+ ]);
+ await mkdir(join(tmpdir(), `portos-grok-${job.jobId}`), { recursive: true });
+ await writeFile(stagingPathFor(job.jobId), fakePngBytes);
+
+ // A subscriber whose res.write throws ONLY on the terminal 'complete'
+ // frame — the exact window this regression covers. The earlier 'status'
+ // replay-on-attach write must succeed so the render reaches that frame.
+ const throwingClient = {
+ writeHead: vi.fn(),
+ write: vi.fn((msg) => {
+ if (msg.includes('"type":"complete"')) throw new Error('subscriber write failed');
+ }),
+ req: { on: vi.fn() },
+ };
+ grok.attachSseClient(job.jobId, throwingClient);
+
+ await closeChild(0, 0);
+
+ await vi.waitFor(() => expect(failedListener).toHaveBeenCalledTimes(1), { timeout: 5000, interval: 50 });
+ expect(failedListener.mock.calls[0][0].error).toMatch(/post-exit handler failed/i);
+ }, 10000);
});
describe('grok provider — noImageReason', () => {
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 41bdfc32c0..ca6f225c2b 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -23,7 +23,7 @@ import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
import { detectImageFormat } from '../../lib/mimeTypes.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
@@ -236,7 +236,7 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt
const status = await pollFalStatus({ statusUrl, apiKey });
if (status.status === 'COMPLETED') break;
if (status.status === 'ERROR') {
- return finalizeError(job, jobId, `fal.ai render failed: ${status.error || 'unknown error'}`);
+ return finalizeJobFailure(job, jobId, null, `fal.ai render failed: ${status.error || 'unknown error'}`);
}
// fal's own queue maps to SUBMIT rather than to the queued step: the
// ladder's `queued` is PortOS's local queue, and stepping back to it
@@ -247,19 +247,19 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt
}
if (entry.aborted) return finalizeCanceled(job, jobId);
if (Date.now() >= deadline) {
- return finalizeError(job, jobId, `fal.ai did not finish within ${Math.round(FAL_RENDER_TIMEOUT_MS / 1000)}s`);
+ return finalizeJobFailure(job, jobId, null, `fal.ai did not finish within ${Math.round(FAL_RENDER_TIMEOUT_MS / 1000)}s`);
}
const result = await fetchFalResult({ responseUrl, apiKey });
const videoUrl = result?.video?.url || result?.video_url || result?.output?.video?.url;
if (!videoUrl) {
- return finalizeError(job, jobId, 'fal.ai completed but returned no video URL');
+ return finalizeJobFailure(job, jobId, null, 'fal.ai completed but returned no video URL');
}
emitCloudRenderStatus(job, jobId, CLOUD_RENDER_PHASE.FETCH, 'Downloading video…');
const videoRes = await fetchWithTimeout(videoUrl, {}, FAL_DOWNLOAD_TIMEOUT_MS);
if (!videoRes.ok) {
- return finalizeError(job, jobId, `fal.ai video download failed: HTTP ${videoRes.status}`);
+ return finalizeJobFailure(job, jobId, null, `fal.ai video download failed: HTTP ${videoRes.status}`);
}
const buffer = Buffer.from(await videoRes.arrayBuffer());
await writeFile(outputPath, buffer);
@@ -269,22 +269,23 @@ async function runFalVideo(job, jobId, { apiKey, modelId, prompt, negativePrompt
await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed: null, mutateHistory: mutateVideoHistory });
closeJobAfterDelay(jobs, jobId);
} catch (err) {
- finalizeError(job, jobId, `fal.ai video generation failed: ${err?.message || err}`);
+ // NOTE: not forced, unlike videoGen/grok.js's post-exit catch — see #6831.
+ // finalizeGeneratedVideo stamps job.status = 'complete' before its own
+ // async tail (same as here), so a throw from that tail after the request
+ // slot is already cleared above lands here as a silent no-op today.
+ finalizeJobFailure(job, jobId, null, `fal.ai video generation failed: ${err?.message || err}`);
}
}
-const finalizeCanceled = (job, jobId) => finalizeError(job, jobId, 'Canceled', { force: true });
+const finalizeCanceled = (job, jobId) => finalizeJobFailure(job, jobId, null, 'Canceled', { force: true });
-const finalizeError = (job, jobId, reason, { force = false } = {}) => {
- if (!force && (job.status === 'error' || job.status === 'complete')) return;
- activeRequests.delete(jobId);
- activeJobs.delete(jobId);
- job.status = 'error';
- console.log(`❌ fal video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeRequests,
+ label: 'fal video generation',
+ events: videoGenEvents,
+});
// Test-only handles.
export const _internals = {
diff --git a/server/services/videoGen/grok.js b/server/services/videoGen/grok.js
index dc6c125b87..2a3ddd2a7d 100644
--- a/server/services/videoGen/grok.js
+++ b/server/services/videoGen/grok.js
@@ -28,7 +28,7 @@ import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
import { ensureDir, PATHS, copyFileGuarded, unlinkGuarded, rmGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { killProcessTree, prepareCliSpawn } from '../../lib/bufferedSpawn.js';
import { ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../../lib/grok.js';
@@ -238,7 +238,7 @@ async function runGrokVideo(job, jobId, bin, args, {
cleanupPromptFile();
removeScratch();
removeUpload();
- finalizeError(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
+ finalizeJobFailure(job, jobId, proc, `Failed to spawn ${bin}: ${err.message}`);
});
proc.stdout.on('data', (chunk) => {
@@ -267,14 +267,14 @@ async function runGrokVideo(job, jobId, bin, args, {
const tail = stderrTail.trim().split('\n').slice(-6).join('\n');
removeScratch();
removeUpload();
- return finalizeError(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);
+ return finalizeJobFailure(job, jobId, proc, `Grok video generation failed: ${reason}\n${tail}`);
}
const harvested = await harvestStagedVideo(stagingPath, harvestTimeoutMs);
if (!harvested.found) {
removeScratch();
removeUpload();
const prefix = harvested.invalid ? 'Grok wrote a non-MP4 file at the directed path. ' : '';
- return finalizeError(job, jobId, proc, `${prefix}${noVideoReason(stdoutTail)}`);
+ return finalizeJobFailure(job, jobId, proc, `${prefix}${noVideoReason(stdoutTail)}`);
}
await copyFileGuarded(stagingPath, outputPath);
await unlinkGuarded(stagingPath).catch(() => {});
@@ -295,7 +295,7 @@ async function runGrokVideo(job, jobId, bin, args, {
// post-processing (faststart/thumbnail/history) — a throw there must
// still surface as a terminal failure or the queue's job stays
// 'running' until the watchdog. Force past the idempotence guard.
- finalizeError(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`, { force: true });
+ finalizeJobFailure(job, jobId, proc, `Grok video post-exit handler failed: ${err?.message || err}`, { force: true });
}
});
}
@@ -309,19 +309,13 @@ function noVideoReason(stdoutTail = '') {
.replace('the image_gen tool may be unavailable', 'the image_to_video tool may be unavailable');
}
-const finalizeError = (job, jobId, proc, reason, { force = false } = {}) => {
- // Idempotent except under `force` — used when finalizeGeneratedVideo threw
- // AFTER stamping 'complete' but BEFORE emitting the completed event, so a
- // terminal 'failed' must still go out.
- if (!force && (job.status === 'error' || job.status === 'complete')) return;
- if (proc == null || activeProcs.get(jobId) === proc) activeProcs.delete(jobId);
- job.status = 'error';
- activeJobs.delete(jobId);
- console.log(`❌ grok video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeProcs,
+ label: 'grok video generation',
+ events: videoGenEvents,
+});
// Poll for the directed MP4 until it exists non-empty with an `ftyp` header,
// or timeoutMs elapses. { found, invalid } mirrors the image harvest —
diff --git a/server/services/videoGen/reactor.js b/server/services/videoGen/reactor.js
index 7937a92044..b397af6a1e 100644
--- a/server/services/videoGen/reactor.js
+++ b/server/services/videoGen/reactor.js
@@ -6,7 +6,7 @@ import { join } from 'path';
import { ensureDir, PATHS } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer } from '../../lib/sseUtils.js';
import { videoGenEvents } from './events.js';
import { finalizeGeneratedVideo, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';
import { mutateVideoHistory } from './history.js';
@@ -319,7 +319,7 @@ async function runReactorVideo(job, jobId, {
const continuationHint = continueFromClipId
? ' — reactor may no longer hold that clip; clear "Continue from clip" and render fresh, or start from an image'
: '';
- finalizeError(job, jobId, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}${continuationHint}`, { force: true });
+ finalizeJobFailure(job, jobId, null, entry.aborted ? 'Canceled' : `Reactor video generation failed: ${err?.message || 'unknown error'}${continuationHint}`, { force: true });
} finally {
await rm(`${outputPath}.capture`, { recursive: true, force: true }).catch(() => {});
if (frame.fittedPath) await rm(frame.fittedPath, { force: true }).catch(() => {});
@@ -329,18 +329,15 @@ async function runReactorVideo(job, jobId, {
}
}
-const finalizeCanceled = (job, jobId) => finalizeError(job, jobId, 'Canceled', { force: true });
+const finalizeCanceled = (job, jobId) => finalizeJobFailure(job, jobId, null, 'Canceled', { force: true });
-const finalizeError = (job, jobId, reason, { force = false } = {}) => {
- if (!force && (job.status === 'error' || job.status === 'complete')) return;
- activeRequests.delete(jobId);
- activeJobs.delete(jobId);
- job.status = 'error';
- console.log(`❌ reactor video generation failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- closeJobAfterDelay(jobs, jobId);
-};
+const finalizeJobFailure = createJobFailureFinalizer({
+ jobs,
+ activeJobs,
+ activeSlots: activeRequests,
+ label: 'reactor video generation',
+ events: videoGenEvents,
+});
// Test-only handles.
export const _internals = { validateRequest: validateReactorRequest };