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: decouple SSE and lifecycle-event dispatch in media-gen terminal handling (#8915)

[._.]/ Adam Eivy6b5c4d692844
diff --git a/server/lib/README.md b/server/lib/README.md
index 2cda3f37d9..f23f173007 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -684,7 +684,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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). |
| `progressChannels.js` | `createProgressChannels({ label, describeKey })` — shared GET/POST progress channel lifecycle with late subscriber replay, idle reservation reaping, and one active stream owner per key. |
-| `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`, plus a `.canceled(job, jobId, slotOwner?)` convenience) behind all six media-generation backends (`imageGen/{agy,codex,grok}.js`, `videoGen/{grok,fal,reactor}.js`). |
+| `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. `dispatchTerminalEvent(jobId, sseSend, emitEvent)` — dispatches a job's terminal SSE frame and its lifecycle event independently, each in its own try/catch, so a throw in one (a dead client's `res.write`, a throwing listener) can't suppress the other. `createJobFailureFinalizer({ jobs, activeJobs, activeSlots, label, events, failedPayload? })` — the shared job-failure finalizer (idempotency guard w/ `force` escape hatch, slot-owner clear, `dispatchTerminalEvent`-backed SSE error frame + `failed` event, `closeJobAfterDelay`, plus a `.canceled(job, jobId, slotOwner?)` convenience) 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 48750b2a1d..0f4f079244 100644
--- a/server/lib/sseUtils.js
+++ b/server/lib/sseUtils.js
@@ -42,6 +42,29 @@ export const broadcastSse = (job, payload, { retain = true } = {}) => {
for (const c of job.clients) c.write(msg);
};
+// Dispatches a job's terminal SSE frame and its companion lifecycle event
+// (`imageGenEvents`/`videoGenEvents` 'completed'/'failed') INDEPENDENTLY: each
+// call gets its own try/catch, so a throw from one — a dead client's
+// `res.write` throwing inside `sseSend`, or a throwing listener inside
+// `emitEvent` — cannot suppress the other. Terminal dispatch is otherwise a
+// bare `broadcastSse(...)` followed by `events.emit(...)`, and the lifecycle
+// event drives durable side effects (gallery index, peer sync, job-queue
+// settlement) that must fire regardless of whether the best-effort SSE write
+// to a possibly-dead client succeeds (#8915). `jobId` is only for the error
+// log line.
+export const dispatchTerminalEvent = (jobId, sseSend, emitEvent) => {
+ try {
+ sseSend();
+ } catch (err) {
+ console.error(`❌ SSE terminal broadcast failed [${String(jobId).slice(0, 8)}]: ${err?.message || err}`);
+ }
+ try {
+ emitEvent();
+ } catch (err) {
+ console.error(`❌ Lifecycle event dispatch failed [${String(jobId).slice(0, 8)}]: ${err?.message || err}`);
+ }
+};
+
export const attachSseClient = (jobs, jobId, res) => {
const job = jobs.get(jobId);
if (!job) return false;
@@ -130,8 +153,11 @@ export const createJobFailureFinalizer = ({
job.status = 'error';
activeJobs.delete(jobId);
console.error(`❌ ${label} failed [${jobId.slice(0, 8)}]: ${reason.split('\n')[0]}`);
- broadcastSse(job, { type: 'error', error: reason });
- events.emit('failed', failedPayload(jobId, reason));
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'error', error: reason }),
+ () => events.emit('failed', failedPayload(jobId, reason)),
+ );
closeJobAfterDelay(jobs, jobId);
};
finalize.canceled = (job, jobId, slotOwner = null) => finalize(job, jobId, slotOwner, 'Canceled', { force: true });
diff --git a/server/lib/sseUtils.test.js b/server/lib/sseUtils.test.js
index 4512b56c64..16bc1a292c 100644
--- a/server/lib/sseUtils.test.js
+++ b/server/lib/sseUtils.test.js
@@ -6,6 +6,7 @@ import {
attachSseClient,
closeJobAfterDelay,
createJobFailureFinalizer,
+ dispatchTerminalEvent,
createSseRunner
} from './sseUtils.js';
@@ -186,6 +187,50 @@ describe('closeJobAfterDelay', () => {
});
});
+describe('dispatchTerminalEvent', () => {
+ // Regression (#8915): the terminal dispatch used to be a bare
+ // `sseSend(); emitEvent();` pair — a throw from sseSend (e.g. a dead
+ // client's res.write) skipped emitEvent entirely, silently dropping the
+ // durable side effects (gallery index, peer sync, job-queue settlement)
+ // the lifecycle event drives, even though the SSE write failure was purely
+ // best-effort and unrelated to whether the job actually settled.
+ it('still calls emitEvent when sseSend throws', () => {
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const sseSend = vi.fn(() => { throw new Error('dead client'); });
+ const emitEvent = vi.fn();
+
+ dispatchTerminalEvent('job-123', sseSend, emitEvent);
+
+ expect(sseSend).toHaveBeenCalled();
+ expect(emitEvent).toHaveBeenCalled();
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('SSE terminal broadcast failed [job-123]'));
+ errSpy.mockRestore();
+ });
+
+ it('still calls sseSend, and does not re-throw, when emitEvent throws', () => {
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const sseSend = vi.fn();
+ const emitEvent = vi.fn(() => { throw new Error('listener exploded'); });
+
+ expect(() => dispatchTerminalEvent('job-123', sseSend, emitEvent)).not.toThrow();
+
+ expect(sseSend).toHaveBeenCalled();
+ expect(emitEvent).toHaveBeenCalled();
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('Lifecycle event dispatch failed [job-123]'));
+ errSpy.mockRestore();
+ });
+
+ it('calls both dispatches once each on the normal (non-throwing) path', () => {
+ const sseSend = vi.fn();
+ const emitEvent = vi.fn();
+
+ dispatchTerminalEvent('job-123', sseSend, emitEvent);
+
+ expect(sseSend).toHaveBeenCalledTimes(1);
+ expect(emitEvent).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('createJobFailureFinalizer', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
@@ -299,6 +344,26 @@ describe('createJobFailureFinalizer', () => {
expect(events.emit).toHaveBeenCalledWith('failed', { generationId: 'j1', error: 'Canceled' });
});
+ // Regression (#8915): createJobFailureFinalizer used to call
+ // `broadcastSse(...)` then `events.emit('failed', ...)` back to back — a
+ // throwing SSE client's res.write (dead pipe) aborted before the events.emit
+ // ran, so the six media-generation backends behind this finalizer
+ // (imageGen/{agy,codex,grok}.js, videoGen/{grok,fal,reactor}.js) would
+ // silently skip the queue-settlement/peer-sync bookkeeping `failed` drives.
+ it('still emits failed to the caller when a connected SSE client throws on write', () => {
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const { events, finalize } = setup();
+ const throwingClient = { write: vi.fn(() => { throw new Error('write after end'); }) };
+ const job = { clients: [throwingClient], status: 'running' };
+
+ finalize(job, 'j1', { pid: 1 }, 'boom');
+
+ expect(job.status).toBe('error');
+ expect(events.emit).toHaveBeenCalledWith('failed', { generationId: 'j1', error: 'boom' });
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('SSE terminal broadcast failed'));
+ errSpy.mockRestore();
+ });
+
it('.canceled accepts an optional slotOwner for a backend that does track one', () => {
const { activeSlots, finalize } = setup();
const owner = { pid: 1 };
diff --git a/server/services/imageGen/agy.js b/server/services/imageGen/agy.js
index 478140b6fc..685f3beade 100644
--- a/server/services/imageGen/agy.js
+++ b/server/services/imageGen/agy.js
@@ -35,7 +35,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, createJobFailureFinalizer } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer, dispatchTerminalEvent } from '../../lib/sseUtils.js';
import { imageGenEvents } from '../imageGenEvents.js';
import { buildNoImageReason } from './noImageReason.js';
import { rejectDegenerateFrame } from './frameGuard.js';
@@ -455,8 +455,11 @@ async function runAgy(job, jobId, bin, args, {
activeJobs.delete(jobId);
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (agy)`);
const result = { filename, path: `/data/images/${filename}` };
- broadcastSse(job, { type: 'complete', result });
- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'complete', result }),
+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.AGY, generationId: jobId, path: result.path, filename }),
+ );
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 41704c9e20..d5160ecc76 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -40,7 +40,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, createJobFailureFinalizer } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer, dispatchTerminalEvent } from '../../lib/sseUtils.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { buildCodexStartupArgs, buildEffortArgs, resolveCliEffort } from '../../lib/providerModels.js';
@@ -449,8 +449,11 @@ async function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cle
activeJobs.delete(jobId);
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', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'complete', result }),
+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.CODEX, generationId: jobId, path: `/data/images/${filename}`, filename }),
+ );
closeJobAfterDelay(jobs, jobId);
} catch (err) {
// force: true — 'complete' is already stamped above; see
diff --git a/server/services/imageGen/grok.js b/server/services/imageGen/grok.js
index ed9bbc55d2..3a0e9a1dea 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, createJobFailureFinalizer } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, createJobFailureFinalizer, dispatchTerminalEvent } from '../../lib/sseUtils.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { renderTimingFields } from '../../lib/renderTiming.js';
import { buildNoImageReason } from './noImageReason.js';
@@ -426,8 +426,11 @@ async function runGrok(job, jobId, bin, args, {
activeJobs.delete(jobId);
console.log(`✅ Image generated [${jobId.slice(0, 8)}]: ${filename} (grok)`);
const result = { filename, path: `/data/images/${filename}` };
- broadcastSse(job, { type: 'complete', result });
- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, path: `/data/images/${filename}`, filename });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'complete', result }),
+ () => imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.GROK, generationId: jobId, path: `/data/images/${filename}`, filename }),
+ );
closeJobAfterDelay(jobs, jobId);
} catch (err) {
removeScratch();
diff --git a/server/services/imageGen/grok.test.js b/server/services/imageGen/grok.test.js
index 555eefdb8a..8c07c63a5b 100644
--- a/server/services/imageGen/grok.test.js
+++ b/server/services/imageGen/grok.test.js
@@ -375,17 +375,19 @@ describe('grok provider — directed-path harvest', () => {
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 () => {
+ // Regression (#8915): the success-path tail dispatches its terminal SSE
+ // frame and its `imageGenEvents.emit('completed', ...)` INDEPENDENTLY via
+ // `dispatchTerminalEvent` — a throwing subscriber's res.write (a dead SSE
+ // client) must not suppress the 'completed' event, which is what drives the
+ // gallery index / peer-sync / job-queue settlement. (This used to instead
+ // hit the shared finalizer's `force` escape hatch and flip a successful
+ // render into a spurious 'failed' — see #6830 history — which was itself
+ // only correct for a REAL post-processing throw, not a merely-best-effort
+ // SSE write failing on an already-successful render.)
+ it('still emits completed when a connected SSE client throws on the terminal complete frame', async () => {
+ const completedListener = vi.fn();
const failedListener = vi.fn();
+ imageGenEvents.on('completed', completedListener);
imageGenEvents.on('failed', failedListener);
const job = await grok.generateImage({ prompt: 'a fox' });
@@ -404,14 +406,18 @@ describe('grok provider — directed-path harvest', () => {
write: vi.fn((msg) => {
if (msg.includes('"type":"complete"')) throw new Error('subscriber write failed');
}),
+ end: vi.fn(),
req: { on: vi.fn() },
};
grok.attachSseClient(job.jobId, throwingClient);
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
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);
+ await vi.waitFor(() => expect(completedListener).toHaveBeenCalledTimes(1), { timeout: 5000, interval: 50 });
+ expect(failedListener).not.toHaveBeenCalled();
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('SSE terminal broadcast failed'));
+ errSpy.mockRestore();
}, 10000);
});
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index a38b7de419..3d27066b5c 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -25,7 +25,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { autoCleanGeneratedImage } from '../../lib/imageClean.js';
import { rejectDegenerateFrame } from './frameGuard.js';
import { imageGenEvents } from '../imageGenEvents.js';
-import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
+import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, dispatchTerminalEvent, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
import { resolveFlux2Python, FLUX2_VENV_DEFAULT, isFlux2VenvHealthy, invalidateFlux2Health } from '../../lib/pythonSetup.js';
import { usesTorchVenv } from '../../lib/imageRuntimeRemedies.js';
import { hfChildEnv } from '../hfToken.js';
@@ -743,8 +743,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
job.status = 'error';
const reason = `Failed to spawn ${bin}: ${err.message}`;
console.error(`❌ Image generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);
- broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'error', error: reason }),
+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason }),
+ );
activeProcess = null;
activeJob = null;
void releaseHeavyClaim();
@@ -963,8 +966,11 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
job.error = emptyFrame;
console.error(`❌ Image generation failed [${jobId.slice(0, 8)}]: ${emptyFrame}`);
terminalEmitted = true;
- broadcastSse(job, { type: 'error', error: emptyFrame });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: emptyFrame });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'error', error: emptyFrame }),
+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: emptyFrame }),
+ );
return;
}
if (code !== 0) {
@@ -1043,10 +1049,13 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
job.errorKind = userKind;
job.errorRepo = userRepo;
terminalEmitted = true;
- broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo });
// Propagate the friendly message (not the raw "Exit code 1") to the
// job queue so its `failed` log line and future SSE replays carry it.
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: job.error });
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'error', error: errorText, kind: userKind, repo: userRepo }),
+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: job.error }),
+ );
} else {
job.status = 'complete';
// Large-source regen (issue #912): the render ran at a clamped FLUX-sane
@@ -1113,20 +1122,26 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
// stays null so nothing treats it as a gallery URL.
const result = { filename, seed: actualSeed, path: publicPath, outputPath, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) };
terminalEmitted = true;
- broadcastSse(job, { type: 'complete', result });
// Include `seed` so /sdapi/v1/txt2img can surface the actual seed used
// (mflux generates a random one if the client didn't pass one). Emit the
// gallery `completed` (which drives the media-asset index + peer-sync
// hooks) ONLY for a gallery target — a temp render must not be indexed or
// federated. The queue's own `completed` handler still fires off the
// return value below, so the job settles either way.
- if (!skipSidecar) {
- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });
- } else {
- // `temp: true` tells the media-asset-index + peer-sync hooks to ignore
- // this render — there's no gallery file or sidecar to index/federate.
- imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });
- }
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'complete', result }),
+ () => {
+ if (!skipSidecar) {
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: publicPath, filename, seed: actualSeed, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });
+ } else {
+ // `temp: true` tells the media-asset-index + peer-sync hooks to
+ // ignore this render — there's no gallery file or sidecar to
+ // index/federate.
+ imageGenEvents.emit('completed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, path: null, filename, seed: actualSeed, outputPath, temp: true, ...(meta.executionProvenance ? { executionProvenance: meta.executionProvenance } : {}) });
+ }
+ },
+ );
}
} catch (err) {
const reason = err?.message || String(err);
@@ -1140,18 +1155,18 @@ export async function generateImage({ pythonPath, prompt = '', negativePrompt =
if (!terminalEmitted) {
job.status = 'error';
job.error = reason;
- // Guard the dispatch itself: a throwing SSE writer (a dead client's
- // res.write) or a throwing imageGenEvents listener must not re-throw
- // out of this catch — that would escape the close handler as an
- // unhandled rejection, defeating the whole point of this try/catch.
- // job.status/job.error above are already correct even if delivery
- // fails partway, and `finally` below still runs the job cleanup.
- try {
- broadcastSse(job, { type: 'error', error: reason });
- imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason });
- } catch (dispatchErr) {
- console.error(`❌ Image generation terminal-event dispatch failed [${jobId.slice(0, 8)}]: ${dispatchErr?.message || dispatchErr}`);
- }
+ // `dispatchTerminalEvent` guards each call independently — a throwing
+ // SSE writer (a dead client's `res.write`) can't suppress the
+ // `imageGenEvents.emit` (or vice versa), and neither can re-throw out
+ // of this catch, which would escape the close handler as an
+ // unhandled rejection. job.status/job.error above are already correct
+ // even if delivery fails partway, and `finally` below still runs the
+ // job cleanup.
+ dispatchTerminalEvent(
+ jobId,
+ () => broadcastSse(job, { type: 'error', error: reason }),
+ () => imageGenEvents.emit('failed', { mode: IMAGE_GEN_MODE.LOCAL, generationId: jobId, error: reason }),
+ );
}
} finally {
closeJobAfterDelay(jobs, jobId);
diff --git a/server/services/imageGen/local.test.js b/server/services/imageGen/local.test.js
index 8746744b85..a48f6f7a63 100644
--- a/server/services/imageGen/local.test.js
+++ b/server/services/imageGen/local.test.js
@@ -1106,3 +1106,94 @@ describe('local render failure delivery — post-render throw safety net', () =>
}
});
});
+
+// Regression (#8915): the terminal dispatch was a bare
+// `broadcastSse(...); imageGenEvents.emit(...)` pair — a throwing SSE client
+// (e.g. a dead connection's res.write) that fires from inside broadcastSse
+// would abort BEFORE the lifecycle emit ran, silently skipping the gallery
+// index / peer-sync / job-queue bookkeeping the emit drives even though the
+// job's own status/error fields were already correct. Both dispatch paths
+// (the `code !== 0` failure branch and the success branch) now go through
+// `dispatchTerminalEvent`, which isolates each call in its own try/catch.
+describe('local render terminal dispatch — SSE/lifecycle decoupling (#8915)', () => {
+ beforeEach(() => {
+ mockRejectDegenerateFrame.mockReset();
+ mockRejectDegenerateFrame.mockResolvedValue(null);
+ });
+
+ it('still emits the failed lifecycle event when a connected SSE client throws on write', 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 } = await import('./local.js');
+ const { jobId } = await generateImage({ modelId: 'qwen-image-2.1', prompt: 'a fox' });
+
+ // Feed the stderr diagnosis BEFORE attaching the throwing client — the
+ // intermediate status broadcasts this line triggers are unrelated to the
+ // terminal-dispatch decoupling under test.
+ child.stderr.emit('data', Buffer.from('runner.py: error: invalid value for --steps\n'));
+
+ // A connected client whose write() throws — the dead-client hazard the
+ // issue names (a broken pipe surfacing as a synchronous throw) — attached
+ // just before the terminal close so only the terminal SSE frame hits it.
+ // (attachSseClient's own replay of the cached lastPayload is a first,
+ // separate write call — let that one through so it doesn't mask the
+ // terminal-dispatch assertion below.)
+ let writeCalls = 0;
+ const throwingClient = {
+ writeHead: vi.fn(),
+ write: vi.fn(() => {
+ writeCalls += 1;
+ if (writeCalls > 1) throw new Error('write after end');
+ }),
+ end: vi.fn(),
+ req: new EventEmitter(),
+ };
+ expect(attachSseClient(jobId, throwingClient)).toBe(true);
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const failed = new Promise((resolve) => imageGenEvents.once('failed', resolve));
+ child.emit('close', 2);
+
+ // The lifecycle event still fires — and still carries the real
+ // diagnosis — even though the SSE broadcast to this client threw.
+ const failure = await failed;
+ expect(failure.error).toContain('invalid value for --steps');
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('SSE terminal broadcast failed'));
+ errSpy.mockRestore();
+ });
+
+ it('still emits the completed lifecycle event when a connected SSE client throws on write', 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 } = await import('./local.js');
+ const { jobId } = await generateImage({ modelId: 'qwen-image-2.1', prompt: 'a fox' });
+
+ const throwingClient = {
+ writeHead: vi.fn(),
+ write: vi.fn(() => { throw new Error('write after end'); }),
+ end: vi.fn(),
+ req: new EventEmitter(),
+ };
+ expect(attachSseClient(jobId, throwingClient)).toBe(true);
+
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const completed = new Promise((resolve) => imageGenEvents.once('completed', resolve));
+ child.emit('close', 0);
+
+ // Gallery indexing / peer-sync (driven by 'completed') still fires even
+ // though the SSE 'complete' frame threw delivering to this client.
+ await expect(completed).resolves.toMatchObject({ mode: 'local' });
+ expect(errSpy).toHaveBeenCalledWith(expect.stringContaining('SSE terminal broadcast failed'));
+ errSpy.mockRestore();
+ });
+});