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

unify media-job scene-image completion hooks behind a tag-dispatch factory (#1791)

[._.]/ Adam Eivya3a92a84cbd0
diff --git a/client/src/components/writers-room/LiveRenderPanel.jsx b/client/src/components/writers-room/LiveRenderPanel.jsx
index f9c45fadc0..304d98dbd3 100644
--- a/client/src/components/writers-room/LiveRenderPanel.jsx
+++ b/client/src/components/writers-room/LiveRenderPanel.jsx
@@ -117,6 +117,15 @@ export default function LiveRenderPanel({
pendingJobRef.current = null;
if (mountedRef.current) setGenStatus('idle');
};
+ // A canceled render (e.g. dropped from the Media Jobs queue) emits no
+ // *:failed when it was still queued — clear the in-flight state on the
+ // bridged `image-gen:canceled` so "Rendering…" doesn't stick (#1791).
+ const onCanceled = (data) => {
+ const job = pendingJobRef.current;
+ if (!job || data.generationId !== job.jobId) return;
+ pendingJobRef.current = null;
+ if (mountedRef.current) setGenStatus('idle');
+ };
// The hook fires `writers-room:scene-image` once an async render lands on the
// analysis snapshot — fold that entry up so the boards update reactively.
// Gate on workId (the event is broadcast to every client); the downstream
@@ -129,10 +138,12 @@ export default function LiveRenderPanel({
};
socket.on('image-gen:completed', onCompleted);
socket.on('image-gen:failed', onFailed);
+ socket.on('image-gen:canceled', onCanceled);
socket.on('writers-room:scene-image', onSceneImage);
return () => {
socket.off('image-gen:completed', onCompleted);
socket.off('image-gen:failed', onFailed);
+ socket.off('image-gen:canceled', onCanceled);
socket.off('writers-room:scene-image', onSceneImage);
};
// The job snapshot is read from pendingJobRef (set at kickoff); the attach
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index 7dcd4c50b9..b73005f150 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -125,17 +125,33 @@ const SceneCard = forwardRef(function SceneCard({
setProgress(null);
jobIdRef.current = null;
};
+ // A canceled render (e.g. dropped from the Media Jobs queue) is not an
+ // error — roll back to idle / the prior image so the spinner clears instead
+ // of sticking until remount (#1791). The `*-gen:canceled` event is bridged
+ // from mediaJobEvents, keyed by the same generationId as completed/failed.
+ const onCanceled = (data) => {
+ if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
+ jobIdRef.current = null;
+ setProgress(null);
+ setError(null);
+ setGenerated(initialImage
+ ? { path: `/data/images/${initialImage.filename}`, jobId: initialImage.jobId, prompt: initialImage.prompt }
+ : null);
+ setGenStatus(initialImage ? 'done' : 'idle');
+ };
socket.on('image-gen:started', onStarted);
socket.on('image-gen:progress', onProgress);
socket.on('image-gen:completed', onCompleted);
socket.on('image-gen:failed', onFailed);
+ socket.on('image-gen:canceled', onCanceled);
return () => {
socket.off('image-gen:started', onStarted);
socket.off('image-gen:progress', onProgress);
socket.off('image-gen:completed', onCompleted);
socket.off('image-gen:failed', onFailed);
+ socket.off('image-gen:canceled', onCanceled);
};
- }, [workId, analysisId, scene.id]);
+ }, [workId, analysisId, scene.id, initialImage]);
const generate = async () => {
if (genStatus === 'running') return;
diff --git a/client/src/hooks/useMediaJobProgress.js b/client/src/hooks/useMediaJobProgress.js
index 87516bd058..93f0c4849e 100644
--- a/client/src/hooks/useMediaJobProgress.js
+++ b/client/src/hooks/useMediaJobProgress.js
@@ -131,7 +131,7 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
};
const onFailed = (data) => {
if (data.generationId !== jobId) return;
- // The mediaJobQueue collapses user-canceled jobs into a *:failed
+ // The mediaJobQueue collapses a RUNNING job's cancellation into a *:failed
// socket event (SIGTERM looks like a failure to the underlying gen
// module) while the persisted job.status is actually 'canceled'.
// Re-fetch the authoritative state so MediaJobThumb's canceled UI
@@ -144,17 +144,28 @@ export default function useMediaJobProgress(jobId, { kind = 'image' } = {}) {
}
}).catch(() => {});
};
+ // A job canceled while still QUEUED never starts a gen run, so it emits no
+ // *:failed — only `*-gen:canceled` (bridged from mediaJobEvents, #1791).
+ // Settle straight to 'canceled' so the spinner clears live without the
+ // re-fetch the *:failed path needs. Also fires (harmlessly, idempotently)
+ // alongside *:failed when a running job is canceled.
+ const onCanceled = (data) => {
+ if (data.generationId !== jobId) return;
+ setState((prev) => (prev.status === 'canceled' ? prev : { ...prev, status: 'canceled' }));
+ };
socket.on(`${evtPrefix}:started`, onStarted);
socket.on(`${evtPrefix}:progress`, onProgress);
socket.on(`${evtPrefix}:completed`, onCompleted);
socket.on(`${evtPrefix}:failed`, onFailed);
+ socket.on(`${evtPrefix}:canceled`, onCanceled);
return () => {
canceled = true;
socket.off(`${evtPrefix}:started`, onStarted);
socket.off(`${evtPrefix}:progress`, onProgress);
socket.off(`${evtPrefix}:completed`, onCompleted);
socket.off(`${evtPrefix}:failed`, onFailed);
+ socket.off(`${evtPrefix}:canceled`, onCanceled);
};
}, [jobId, kind]);
diff --git a/client/src/hooks/useMediaJobProgress.test.jsx b/client/src/hooks/useMediaJobProgress.test.jsx
new file mode 100644
index 0000000000..82658bc6ff
--- /dev/null
+++ b/client/src/hooks/useMediaJobProgress.test.jsx
@@ -0,0 +1,60 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act, cleanup, waitFor } from '@testing-library/react';
+
+// Mock the socket module so the test can drive the `image-gen:*` handlers the
+// hook registers with `on()`.
+const handlers = new Map();
+vi.mock('../services/socket', () => ({
+ default: {
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ emit: () => {},
+ },
+}));
+
+// Mock the hydrate fetch so mount doesn't hit the network. Default: an
+// in-flight (running) job so the spinner state is the starting point.
+const getMediaJob = vi.fn(async () => ({ status: 'running' }));
+vi.mock('../services/apiMediaJobs', () => ({ getMediaJob: (...a) => getMediaJob(...a) }));
+
+const useMediaJobProgress = (await import('./useMediaJobProgress.js')).default;
+
+const fire = (event, payload) => act(() => { handlers.get(event)?.(payload); });
+
+describe('useMediaJobProgress — canceled handling (#1791)', () => {
+ beforeEach(() => { handlers.clear(); getMediaJob.mockClear(); getMediaJob.mockResolvedValue({ status: 'running' }); });
+ afterEach(cleanup);
+
+ it('settles to canceled on a matching image-gen:canceled without re-fetching', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1'));
+ await waitFor(() => expect(result.current.status).toBe('running'));
+ getMediaJob.mockClear();
+ fire('image-gen:canceled', { generationId: 'job-1' });
+ expect(result.current.status).toBe('canceled');
+ // The canceled event is authoritative — no re-fetch needed (unlike :failed).
+ expect(getMediaJob).not.toHaveBeenCalled();
+ });
+
+ it('ignores a canceled event for a different job', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1'));
+ await waitFor(() => expect(result.current.status).toBe('running'));
+ fire('image-gen:canceled', { generationId: 'other-job' });
+ expect(result.current.status).toBe('running');
+ });
+
+ it('subscribes to the video-gen:canceled event when kind=video', () => {
+ renderHook(() => useMediaJobProgress('job-1', { kind: 'video' }));
+ expect(handlers.has('video-gen:canceled')).toBe(true);
+ expect(handlers.has('image-gen:canceled')).toBe(false);
+ });
+
+ it('a :failed for a user-canceled running job still corrects to canceled via re-fetch', async () => {
+ const { result } = renderHook(() => useMediaJobProgress('job-1'));
+ await waitFor(() => expect(result.current.status).toBe('running'));
+ // The gen module reports a SIGTERM cancel as a failure; the persisted state
+ // is 'canceled', so onFailed re-fetches and corrects.
+ getMediaJob.mockResolvedValueOnce({ status: 'canceled', error: 'Canceled while running' });
+ fire('image-gen:failed', { generationId: 'job-1', error: 'killed' });
+ await waitFor(() => expect(result.current.status).toBe('canceled'));
+ });
+});
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index e68ae6302d..3cef092d21 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -100,13 +100,20 @@ export default function MusicVideo() {
};
const onCompleted = (data) => settle(data, false);
const onFailed = (data) => settle(data, true);
+ // A canceled render (e.g. dropped from the Media Jobs queue) clears the
+ // scene spinner with no failure toast — settle as a non-failure (#1791).
+ // A queued-then-canceled job emits no *:failed, so without this the
+ // "Rendering…" button sticks until the page remounts.
+ const onCanceled = (data) => settle(data, false);
socket.on('music-video:scene-image', onSceneImage);
socket.on('image-gen:completed', onCompleted);
socket.on('image-gen:failed', onFailed);
+ socket.on('image-gen:canceled', onCanceled);
return () => {
socket.off('music-video:scene-image', onSceneImage);
socket.off('image-gen:completed', onCompleted);
socket.off('image-gen:failed', onFailed);
+ socket.off('image-gen:canceled', onCanceled);
};
}, []);
diff --git a/server/lib/README.md b/server/lib/README.md
index 04c807f67e..7cc877e2c9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -110,6 +110,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. |
| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. |
+| `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
diff --git a/server/lib/createNewestWinsGuard.js b/server/lib/createNewestWinsGuard.js
new file mode 100644
index 0000000000..eb55277266
--- /dev/null
+++ b/server/lib/createNewestWinsGuard.js
@@ -0,0 +1,45 @@
+/**
+ * createNewestWinsGuard — newest-render-wins ordering guard for out-of-order
+ * async completions.
+ *
+ * The media-job completion hooks (writers-room / catalog / music-video scene-
+ * image attach) all share a last-write-wins race: an OLDER render that completes
+ * AFTER a newer regenerate would otherwise overwrite the newer frame. The GPU
+ * lane is FIFO, but the Codex lane and renders kicked off from another client
+ * (or after a refresh cleared the local spinner) can complete out of order — so
+ * "last write wins by completion order" can show the new frame and then revert
+ * to the stale one.
+ *
+ * This guard tracks, per slot `key`, the newest `queuedAt` whose render has been
+ * applied. `isStale(key, at)` reports whether `at` is strictly older than that
+ * recorded newest — i.e. this render should be dropped — and `mark(key, at)`
+ * records a render as the newest after it applies. Callers read+write inside
+ * their per-key serialize section so the check/record pair never races.
+ *
+ * Fixed-width UTC ISO timestamps (`new Date().toISOString()`) compare
+ * chronologically as plain strings, so `at < prev` is a correct ordering test
+ * without parsing. A null/absent `at` is never stale and never recorded (the job
+ * carries no ordering info — fall through to last-write-wins for it).
+ *
+ * In-memory and best-effort: lost on restart, which is fine for the bookkeeping
+ * it guards. Carries `.clear()` for test reset.
+ */
+export function createNewestWinsGuard() {
+ const latest = new Map();
+
+ return {
+ // True when `at` is strictly older than the newest already applied for
+ // `key` — the caller should drop this render. Absent `at` is never stale.
+ isStale: (key, at) => {
+ if (!at) return false;
+ const prev = latest.get(key);
+ return !!prev && at < prev;
+ },
+ // Record `at` as the newest applied for `key`. No-op for an absent `at` so
+ // an untimed render can't poison the slot against future timed ones.
+ mark: (key, at) => {
+ if (at) latest.set(key, at);
+ },
+ clear: () => latest.clear(),
+ };
+}
diff --git a/server/lib/createNewestWinsGuard.test.js b/server/lib/createNewestWinsGuard.test.js
new file mode 100644
index 0000000000..a91547b96c
--- /dev/null
+++ b/server/lib/createNewestWinsGuard.test.js
@@ -0,0 +1,42 @@
+import { describe, it, expect } from 'vitest';
+import { createNewestWinsGuard } from './createNewestWinsGuard.js';
+
+describe('createNewestWinsGuard', () => {
+ it('reports an older queuedAt as stale once a newer one is marked', () => {
+ const guard = createNewestWinsGuard();
+ guard.mark('scene', '2026-06-29T00:00:02.000Z');
+ expect(guard.isStale('scene', '2026-06-29T00:00:01.000Z')).toBe(true);
+ expect(guard.isStale('scene', '2026-06-29T00:00:03.000Z')).toBe(false);
+ // Equal timestamps are not stale — a re-applied render at the same instant wins.
+ expect(guard.isStale('scene', '2026-06-29T00:00:02.000Z')).toBe(false);
+ });
+
+ it('treats an empty slot (nothing marked) as not stale', () => {
+ const guard = createNewestWinsGuard();
+ expect(guard.isStale('scene', '2026-06-29T00:00:01.000Z')).toBe(false);
+ });
+
+ it('treats an absent/null queuedAt as never stale and never records it', () => {
+ const guard = createNewestWinsGuard();
+ expect(guard.isStale('scene', null)).toBe(false);
+ expect(guard.isStale('scene', undefined)).toBe(false);
+ // Marking with no timestamp is a no-op — a later timed render still wins.
+ guard.mark('scene', null);
+ expect(guard.isStale('scene', '2026-06-29T00:00:01.000Z')).toBe(false);
+ });
+
+ it('keys are independent', () => {
+ const guard = createNewestWinsGuard();
+ guard.mark('a', '2026-06-29T00:00:05.000Z');
+ expect(guard.isStale('a', '2026-06-29T00:00:01.000Z')).toBe(true);
+ // A different slot is untouched.
+ expect(guard.isStale('b', '2026-06-29T00:00:01.000Z')).toBe(false);
+ });
+
+ it('clear() drops all recorded slots', () => {
+ const guard = createNewestWinsGuard();
+ guard.mark('scene', '2026-06-29T00:00:05.000Z');
+ guard.clear();
+ expect(guard.isStale('scene', '2026-06-29T00:00:01.000Z')).toBe(false);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 232e82e0e0..3eb42aa6a6 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -102,6 +102,7 @@ export * from './tuiPromptRunner.js';
export * from './collectionStore.js';
export * from './conflictJournal.js';
export * from './createKeyCachedQueue.js';
+export * from './createNewestWinsGuard.js';
export * from './fileUtils.js';
export * from './fileWriteQueue.js';
export * from './schemaVersions.js';
diff --git a/server/services/catalogImageAttachHook.js b/server/services/catalogImageAttachHook.js
index 8f8a98006c..da7a2b4a4c 100644
--- a/server/services/catalogImageAttachHook.js
+++ b/server/services/catalogImageAttachHook.js
@@ -16,20 +16,32 @@
* filename is already attached (the still-mounted client won the race), the hook
* is a no-op, so the same render never lands as both portrait AND reference.
*
- * Mounted once at server boot from server/index.js (after the media job queue is
- * running). Best-effort: a bookkeeping miss is logged but never thrown — it must
- * not crash the server or fail the user's render.
+ * The shared completion-hook scaffold (tag-decode, per-ingredient
+ * serialization, best-effort error handling, idempotent init/reset) lives in
+ * `createMediaJobImageHook` (#1791) — this file is just the catalog-specific
+ * config plus the portrait newest-render-wins guard below. Mounted once at
+ * server boot from server/index.js (after the media job queue is running).
*/
-import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { attachMedia, setPortraitMedia, listMediaForIngredient, getIngredient } from './catalogDB.js';
-import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
+import { createNewestWinsGuard } from '../lib/createNewestWinsGuard.js';
+
+// Newest-render-wins for the PORTRAIT slot only (#1791). The per-ingredient
+// serialize already stops two concurrent renders from clobbering each other,
+// but an OLDER render completing AFTER a newer portrait (e.g. an out-of-order
+// Codex regenerate) would still demote the newer one. Unlike the scene-frame
+// hooks — which drop a stale render outright — catalog references are additive,
+// so instead of losing the image we file a stale would-be-portrait as a
+// reference. Keyed per ingredient; absent `queuedAt` is never stale, so the
+// guard is inert for renders the queue didn't timestamp.
+const portraitGuard = createNewestWinsGuard();
// Resolve the render onto the ingredient. Returns the kind attached
// ('portrait' | 'reference'), 'duplicate' when the client already filed it,
// 'gone' when the target ingredient no longer exists, or throws on a real DB
-// error (caught by the caller).
-async function attachGeneratedImage({ ingredientId, kind, filename }) {
+// error (caught by the factory).
+async function attachGeneratedImage({ ingredientId, kind, filename, queuedAt }) {
// The ingredient can be deleted between enqueue and completion (a render
// outlives its editor by minutes). `getIngredient` filters `deleted = false`,
// so this skips a hard-deleted ingredient (FK would throw) AND a soft-deleted
@@ -43,77 +55,55 @@ async function attachGeneratedImage({ ingredientId, kind, filename }) {
const hasPortrait = existing.some((m) => m.kind === 'portrait');
// Explicit kind wins; otherwise auto: first image → portrait, later → reference
// (mirrors CatalogIngredient.jsx `handleGeneratedImage`).
- const target = kind === 'portrait' || kind === 'reference'
+ let target = kind === 'portrait' || kind === 'reference'
? kind
: (hasPortrait ? 'reference' : 'portrait');
+ // A stale would-be-portrait must not demote a newer portrait. Keep the image
+ // as a reference rather than dropping it (references are additive).
+ if (target === 'portrait' && portraitGuard.isStale(ingredientId, queuedAt)) {
+ target = 'reference';
+ }
if (target === 'portrait') {
await setPortraitMedia(ingredientId, filename);
+ portraitGuard.mark(ingredientId, queuedAt);
} else {
await attachMedia(ingredientId, filename, 'reference');
}
return target;
}
-// Serialize the read→decide→write per ingredient. Two renders for the SAME
-// ingredient completing close together (e.g. two parallel Codex jobs, or a
-// regenerate after navigating back) would otherwise both read an empty media
-// list, both pick 'portrait', and have the second `setPortraitMedia` demote the
-// first — losing the earlier render entirely. Chaining each attach onto the
-// prior one for that ingredient makes the later job observe the first's write,
-// so it correctly falls through to 'reference'. Keyed by ingredientId, so
-// different ingredients still attach concurrently (their Postgres rows don't
-// conflict). In-memory tail, evicted once settled; lost on restart, which is
-// fine — the whole hook is best-effort. (Shared per-key queue — writers-room +
-// music-video scene-image hooks use the same primitive.)
-const serializePerIngredient = createKeyCachedQueue();
-
-let completedHandler = null;
+const hook = createMediaJobImageHook({
+ label: 'catalog image-attach',
+ initLog: '🏷️ Catalog image-attach hook initialized',
+ tagKey: 'catalogAttach',
+ identify: (tag) => (typeof tag?.ingredientId === 'string' && tag.ingredientId
+ ? { ingredientId: tag.ingredientId }
+ : null),
+ // Serialize the read→decide→write per ingredient so two renders for the SAME
+ // ingredient don't both read an empty media list, both pick 'portrait', and
+ // have the second demote the first. Different ingredients attach concurrently.
+ serializeKey: ({ ingredientId }) => ingredientId,
+ attach: ({ ingredientId, tag, filename, job }) => attachGeneratedImage({
+ ingredientId,
+ kind: tag.kind,
+ filename,
+ queuedAt: typeof job.queuedAt === 'string' ? job.queuedAt : null,
+ }),
+ onAttached: ({ ingredientId, filename }, status) => {
+ if (status === 'portrait' || status === 'reference') {
+ console.log(`🏷️ catalog ingredient ${ingredientId.slice(0, 8)} ← ${status} ${filename}`);
+ }
+ },
+});
export function initCatalogImageAttachHook() {
- // Idempotent: a stray double-init (test reload, future refactor) would
- // otherwise register two listeners and double-file every completed image.
- if (completedHandler) return;
-
- // EventEmitter does not await async listeners and does not catch their
- // rejections — a throw here would surface as a process-killing unhandled
- // rejection on Node ≥15. Use a sync listener that launches an async IIFE with
- // a top-level catch so this bookkeeping miss can never crash the server.
- completedHandler = (job) => {
- void (async () => {
- if (!job || job.kind !== 'image') return;
- const tag = job.params?.catalogAttach;
- const ingredientId = tag?.ingredientId;
- if (!ingredientId || typeof ingredientId !== 'string') return;
- const filename = job.result?.filename;
- if (!filename || typeof filename !== 'string') return;
-
- const status = await serializePerIngredient(ingredientId, () =>
- attachGeneratedImage({ ingredientId, kind: tag.kind, filename }),
- ).catch((err) => {
- console.log(`⚠️ catalog image-attach hook failed for ${filename} → ${ingredientId}: ${err?.message || String(err)}`);
- return 'failed';
- });
- if (status === 'portrait' || status === 'reference') {
- console.log(`🏷️ catalog ingredient ${ingredientId.slice(0, 8)} ← ${status} ${filename}`);
- }
- })().catch((err) => {
- // Last-resort net for synchronous throws (unexpected job shape, etc).
- console.log(`⚠️ catalog image-attach hook crashed: ${err?.message || err}`);
- });
- };
-
- mediaJobEvents.on('completed', completedHandler);
- console.log('🏷️ Catalog image-attach hook initialized');
+ hook.init();
}
-// Test-only reset so suites that re-init can do so cleanly. Removes the
-// previously registered listener so re-init doesn't leak handlers.
+// Test-only reset — also clears the portrait guard the factory doesn't own.
export const __testing = {
reset: () => {
- if (completedHandler) {
- mediaJobEvents.off('completed', completedHandler);
- completedHandler = null;
- }
- serializePerIngredient.clear();
+ hook.__testing.reset();
+ portraitGuard.clear();
},
};
diff --git a/server/services/catalogImageAttachHook.test.js b/server/services/catalogImageAttachHook.test.js
index 51fc2dbc30..79481a6fb0 100644
--- a/server/services/catalogImageAttachHook.test.js
+++ b/server/services/catalogImageAttachHook.test.js
@@ -161,6 +161,42 @@ describe('catalogImageAttachHook', () => {
expect(listMediaForIngredient).not.toHaveBeenCalled();
});
+ it('demotes a stale would-be-portrait to a reference instead of clobbering a newer portrait (#1791)', async () => {
+ // Stateful store so the second (older) render observes the first's portrait.
+ const rows = [];
+ listMediaForIngredient.mockImplementation(async () => rows.map((r) => ({ ...r })));
+ setPortraitMedia.mockImplementation(async (id, key) => {
+ for (let i = rows.length - 1; i >= 0; i--) {
+ if (rows[i].kind === 'portrait' && rows[i].mediaKey !== key) rows.splice(i, 1);
+ }
+ rows.push({ mediaKey: key, kind: 'portrait' });
+ return {};
+ });
+ attachMedia.mockImplementation(async (id, key, kind) => { rows.push({ mediaKey: key, kind }); return {}; });
+
+ // Newer explicit-portrait render lands first and becomes the portrait.
+ mediaJobEvents.emit('completed', {
+ kind: 'image', params: { catalogAttach: { ingredientId: 'ing-q', kind: 'portrait' } },
+ result: { filename: 'new.png' }, queuedAt: '2026-06-29T00:00:02.000Z',
+ });
+ await waitFor(() => rows.length === 1);
+ // An OLDER explicit-portrait render completes out of order — it must NOT
+ // demote the newer portrait; it is kept as a reference instead.
+ mediaJobEvents.emit('completed', {
+ kind: 'image', params: { catalogAttach: { ingredientId: 'ing-q', kind: 'portrait' } },
+ result: { filename: 'old.png' }, queuedAt: '2026-06-29T00:00:01.000Z',
+ });
+ await waitFor(() => rows.length === 2);
+
+ expect(setPortraitMedia).toHaveBeenCalledTimes(1);
+ expect(setPortraitMedia).toHaveBeenCalledWith('ing-q', 'new.png');
+ expect(attachMedia).toHaveBeenCalledWith('ing-q', 'old.png', 'reference');
+ expect(rows).toEqual([
+ { mediaKey: 'new.png', kind: 'portrait' },
+ { mediaKey: 'old.png', kind: 'reference' },
+ ]);
+ });
+
it('swallows a DB error without rejecting (best-effort)', async () => {
listMediaForIngredient.mockRejectedValueOnce(new Error('db down'));
// Must not throw / leave an unhandled rejection.
diff --git a/server/services/mediaJobImageHook.js b/server/services/mediaJobImageHook.js
new file mode 100644
index 0000000000..7a2f409128
--- /dev/null
+++ b/server/services/mediaJobImageHook.js
@@ -0,0 +1,145 @@
+/**
+ * createMediaJobImageHook — shared tag-dispatch scaffold for the media-job
+ * scene-image completion hooks (#1791).
+ *
+ * Three completion hooks (writers-room #1363, catalog #1359, music-video #1760)
+ * each subscribe to `mediaJobEvents 'completed'` and do the same shape of work:
+ * ignore non-image jobs, decode a destination tag off `job.params`, validate its
+ * fields, attach the rendered filename onto a record (serialized per-key so two
+ * renders for the same record can't clobber each other), and — for the
+ * scene-frame hooks — drop an out-of-order older render so it can't overwrite a
+ * newer frame. This factory owns that copy-pasted skeleton so each hook becomes
+ * a small config; a future "attach a render to record X" feature is a new config
+ * object, not a 4th hand-wired listener.
+ *
+ * The shared skeleton this owns:
+ * - the idempotent init (a stray double-init must not double-register the
+ * listener and double-file every render);
+ * - the sync listener → async IIFE → top-level catch pattern (EventEmitter
+ * does not await async listeners or catch their rejections, so a throw would
+ * surface as a process-killing unhandled rejection on Node ≥15);
+ * - the `job.kind !== 'image'` / missing-tag / missing-filename guards;
+ * - per-`serializeKey` serialization via the shared `createKeyCachedQueue`;
+ * - the opt-in newest-render-wins guard keyed on `sceneKey` (drop a render
+ * whose `job.queuedAt` is older than the newest already applied to that
+ * scene slot — read+written inside the serialize section so it never races);
+ * - best-effort error logging (a bookkeeping miss is logged, never thrown);
+ * - `__testing.reset()` (off the listener, clear the queue + guard).
+ *
+ * What each hook supplies via config:
+ * - `label` — used in the failure / crash log lines.
+ * - `initLog` — the full emoji-prefixed init console line.
+ * - `tagKey` — the `job.params` key carrying the destination tag.
+ * - `identify(tag, job)` — validate the tag and return an identity object, or
+ * null to ignore the job. Whatever it returns is the `ctx`
+ * the callbacks below receive (plus `job`, `tag`, `filename`).
+ * - `serializeKey(ctx)` — the per-record write-serialization key.
+ * - `sceneKey(ctx)` — OPTIONAL; when present, enables the newest-wins
+ * guard keyed on the returned scene-slot string.
+ * - `attach(ctx)` — async; perform the durable attach, return its result
+ * (or a falsy value to signal "nothing emitted").
+ * - `onAttached(ctx, result)` — emit the domain event + success log. Only
+ * called when `attach` resolved to a non-null result that
+ * was not dropped by the guard.
+ *
+ * The canceled→client-spinner bridge that #1791 also adds is intentionally NOT
+ * here: every client spinner correlates by media-job id (`generationId`), not by
+ * the per-domain scene identity, so it lives once at the socket layer
+ * (`image-gen:canceled` / `video-gen:canceled` in socket.js) rather than as a
+ * per-hook event. See that bridge for the rationale.
+ */
+
+import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
+import { createNewestWinsGuard } from '../lib/createNewestWinsGuard.js';
+
+// Sentinel a guard'd attach returns to mean "dropped as stale" — distinct from
+// a null result (attach declined / failed) so the caller skips onAttached for both
+// but the guard never records a queuedAt for a render it dropped.
+const STALE = Symbol('stale-render-dropped');
+
+export function createMediaJobImageHook(config) {
+ const {
+ label,
+ initLog,
+ tagKey,
+ identify,
+ serializeKey,
+ sceneKey = null,
+ attach,
+ onAttached,
+ } = config;
+
+ const serialize = createKeyCachedQueue();
+ const guard = createNewestWinsGuard();
+
+ let completedHandler = null;
+
+ // Decode the job into the hook's identity context, or null to ignore it.
+ // Shared across the completed path (filename required) so the kind/tag/field
+ // guards live in one place.
+ function decode(job) {
+ if (!job || job.kind !== 'image') return null;
+ const tag = job.params?.[tagKey];
+ if (!tag) return null;
+ const identity = identify(tag, job);
+ if (!identity) return null;
+ const filename = job.result?.filename;
+ if (!filename || typeof filename !== 'string') return null;
+ return { ...identity, job, tag, filename };
+ }
+
+ function init() {
+ // Idempotent: a stray double-init (test reload, future refactor) would
+ // otherwise register two listeners and double-file every completed image.
+ if (completedHandler) return;
+
+ completedHandler = (job) => {
+ void (async () => {
+ const ctx = decode(job);
+ if (!ctx) return;
+ const sKey = sceneKey ? sceneKey(ctx) : null;
+ const queuedAt = typeof job.queuedAt === 'string' ? job.queuedAt : null;
+
+ const result = await serialize(serializeKey(ctx), async () => {
+ // Newest-render-wins: drop an out-of-order older render so it can't
+ // clobber a newer frame on the same scene slot. Checked + recorded
+ // inside the serialize section so the read/write pair never races.
+ if (sKey && guard.isStale(sKey, queuedAt)) return STALE;
+ const r = await attach(ctx);
+ // Only record the slot's newest queuedAt once the attach actually
+ // applied — a failed attach (null) must not advance the guard, or a
+ // later legitimate render would be wrongly dropped as stale.
+ if (sKey && r != null) guard.mark(sKey, queuedAt);
+ return r;
+ }).catch((err) => {
+ console.log(`⚠️ ${label} hook failed for ${ctx.filename}: ${err?.message || String(err)}`);
+ return null;
+ });
+
+ if (result !== STALE && result != null) onAttached(ctx, result);
+ })().catch((err) => {
+ // Last-resort net for synchronous throws (unexpected job shape, etc).
+ console.log(`⚠️ ${label} hook crashed: ${err?.message || err}`);
+ });
+ };
+
+ mediaJobEvents.on('completed', completedHandler);
+ console.log(initLog);
+ }
+
+ // Test-only reset so suites that re-init can do so cleanly. Removes the
+ // previously registered listener so re-init doesn't leak handlers.
+ const __testing = {
+ reset: () => {
+ if (completedHandler) {
+ mediaJobEvents.off('completed', completedHandler);
+ completedHandler = null;
+ }
+ serialize.clear();
+ guard.clear();
+ },
+ };
+
+ return { init, __testing };
+}
diff --git a/server/services/mediaJobImageHook.test.js b/server/services/mediaJobImageHook.test.js
new file mode 100644
index 0000000000..42d2e170ec
--- /dev/null
+++ b/server/services/mediaJobImageHook.test.js
@@ -0,0 +1,139 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const { createMediaJobImageHook } = await import('./mediaJobImageHook.js');
+
+async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (predicate()) return;
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ throw new Error('waitFor: predicate never became true');
+}
+
+const job = ({ params = {}, filename = 'f.png', id = 'j', kind = 'image', queuedAt } = {}) => ({
+ kind, id, params, result: { filename }, ...(queuedAt ? { queuedAt } : {}),
+});
+const tag = (over = {}) => ({ recordId: 'r1', sceneId: 's1', ...over });
+
+// A representative scene-frame config with the newest-wins guard on. `attach`
+// and `onAttached` are returned so a test can reprogram them via
+// mockImplementation (the factory holds the same fn references).
+function makeHook(over = {}) {
+ const attach = vi.fn(async () => ({ ok: true }));
+ const onAttached = vi.fn();
+ const hook = createMediaJobImageHook({
+ label: 'test',
+ initLog: '🧪 test hook initialized',
+ tagKey: 'test',
+ identify: (t) => (t?.recordId && t.sceneId ? { recordId: t.recordId, sceneId: t.sceneId } : null),
+ serializeKey: (ctx) => ctx.recordId,
+ sceneKey: (ctx) => `${ctx.recordId}:${ctx.sceneId}`,
+ attach,
+ onAttached,
+ ...over,
+ });
+ return { hook, attach, onAttached };
+}
+
+describe('createMediaJobImageHook', () => {
+ let h;
+ beforeEach(() => { h = makeHook(); h.hook.init(); });
+ afterEach(() => { h.hook.__testing.reset(); });
+
+ it('attaches and emits for a tagged image job', async () => {
+ mediaJobEvents.emit('completed', job({ params: { test: tag() } }));
+ await waitFor(() => h.onAttached.mock.calls.length > 0);
+ expect(h.attach).toHaveBeenCalledTimes(1);
+ expect(h.onAttached.mock.calls[0][1]).toEqual({ ok: true });
+ expect(h.attach.mock.calls[0][0]).toMatchObject({ recordId: 'r1', sceneId: 's1', filename: 'f.png' });
+ });
+
+ it('ignores non-image jobs, missing tags, invalid tags, and missing filenames', async () => {
+ mediaJobEvents.emit('completed', { kind: 'video', params: { test: tag() }, result: { filename: 'v.mp4' } });
+ mediaJobEvents.emit('completed', job({ params: {} }));
+ mediaJobEvents.emit('completed', job({ params: { test: { recordId: 'r1' } } })); // missing sceneId
+ mediaJobEvents.emit('completed', { kind: 'image', params: { test: tag() }, result: {} }); // no filename
+ await new Promise((r) => setTimeout(r, 30));
+ expect(h.attach).not.toHaveBeenCalled();
+ expect(h.onAttached).not.toHaveBeenCalled();
+ });
+
+ it('does not let an older queuedAt overwrite a newer frame on the same scene', async () => {
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'new.png', id: 'b', queuedAt: '2026-06-29T00:00:02.000Z' }));
+ await waitFor(() => h.attach.mock.calls.length > 0);
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'old.png', id: 'a', queuedAt: '2026-06-29T00:00:01.000Z' }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(h.attach).toHaveBeenCalledTimes(1);
+ expect(h.attach.mock.calls[0][0].filename).toBe('new.png');
+ });
+
+ it('a failed attach does not advance the newest-wins guard (next render still applies)', async () => {
+ h.attach.mockReset();
+ h.attach
+ .mockRejectedValueOnce(new Error('disk full'))
+ .mockResolvedValueOnce({ ok: true });
+ // First (newer) render fails; its queuedAt must NOT be recorded.
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'fail.png', queuedAt: '2026-06-29T00:00:02.000Z' }));
+ await waitFor(() => h.attach.mock.calls.length > 0);
+ // A later (older) render must still apply since the failed one didn't mark the slot.
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'ok.png', queuedAt: '2026-06-29T00:00:01.000Z' }));
+ await waitFor(() => h.onAttached.mock.calls.length > 0);
+ expect(h.attach).toHaveBeenCalledTimes(2);
+ expect(h.onAttached).toHaveBeenCalledTimes(1);
+ expect(h.onAttached.mock.calls[0][1]).toEqual({ ok: true });
+ });
+
+ it('serializes same-key attaches (second awaits the first); a different key runs concurrently', async () => {
+ const order = [];
+ let releaseFirst;
+ h.attach.mockImplementation(async (ctx) => {
+ order.push(`start:${ctx.recordId}:${ctx.sceneId}`);
+ if (ctx.recordId === 'r1' && ctx.sceneId === 'a') await new Promise((res) => { releaseFirst = res; });
+ order.push(`end:${ctx.recordId}:${ctx.sceneId}`);
+ return { ok: true };
+ });
+
+ mediaJobEvents.emit('completed', job({ params: { test: tag({ recordId: 'r1', sceneId: 'a' }) }, id: '1' }));
+ mediaJobEvents.emit('completed', job({ params: { test: tag({ recordId: 'r1', sceneId: 'b' }) }, id: '2' }));
+ mediaJobEvents.emit('completed', job({ params: { test: tag({ recordId: 'r2', sceneId: 'c' }) }, id: '3' }));
+
+ // r1's first attach blocks; r1's second must NOT have started, but r2 (a
+ // different serialize key) runs concurrently.
+ await waitFor(() => order.includes('end:r2:c'));
+ expect(order).toContain('start:r1:a');
+ expect(order).not.toContain('start:r1:b');
+ releaseFirst();
+ await waitFor(() => order.includes('end:r1:b'));
+ // Same key ran strictly one-after-another.
+ expect(order.indexOf('end:r1:a')).toBeLessThan(order.indexOf('start:r1:b'));
+ });
+
+ it('swallows a thrown attach without an unhandled rejection (best-effort)', async () => {
+ h.attach.mockRejectedValue(new Error('boom'));
+ mediaJobEvents.emit('completed', job({ params: { test: tag() } }));
+ await waitFor(() => h.attach.mock.calls.length > 0);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(h.onAttached).not.toHaveBeenCalled();
+ });
+
+ it('init is idempotent — a double init does not double-file', async () => {
+ h.hook.init(); // second init
+ mediaJobEvents.emit('completed', job({ params: { test: tag() } }));
+ await waitFor(() => h.attach.mock.calls.length > 0);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(h.attach).toHaveBeenCalledTimes(1);
+ });
+
+ it('a hook with no sceneKey skips the guard entirely (every render applies)', async () => {
+ h.hook.__testing.reset();
+ h = makeHook({ sceneKey: null });
+ h.hook.init();
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'a.png', queuedAt: '2026-06-29T00:00:02.000Z' }));
+ await waitFor(() => h.attach.mock.calls.length > 0);
+ mediaJobEvents.emit('completed', job({ params: { test: tag() }, filename: 'b.png', queuedAt: '2026-06-29T00:00:01.000Z' }));
+ await waitFor(() => h.attach.mock.calls.length > 1);
+ expect(h.attach).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/server/services/musicVideoSceneImageHook.js b/server/services/musicVideoSceneImageHook.js
index 6041a8cec5..72dce2ec0c 100644
--- a/server/services/musicVideoSceneImageHook.js
+++ b/server/services/musicVideoSceneImageHook.js
@@ -20,97 +20,45 @@
* hook emits `musicVideoEvents` 'scene-image', which socket.js bridges to the
* client so the board updates reactively.
*
- * Mounted once at server boot from server/index.js (after the media job queue is
- * running). Best-effort: a bookkeeping miss is logged but never thrown — it must
- * not crash the server or fail the user's render.
+ * The shared completion-hook scaffold (tag-decode, per-project serialization,
+ * the newest-render-wins guard, best-effort error handling, idempotent init/
+ * reset) lives in `createMediaJobImageHook` (#1791) — this file is just the
+ * music-video-specific config. Mounted once at server boot from server/index.js
+ * (after the media job queue is running).
*/
-import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { updateScene } from './musicVideo/projects.js';
import { musicVideoEvents } from './musicVideo/events.js';
-import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
-// Serialize attaches per PROJECT. Two scene renders for the same project
-// completing close together would otherwise both load→modify→save the one
-// project record (file backend) and the later write would clobber the earlier
-// scene's `referenceImageId`. Chaining each attach onto the prior one for that
-// project makes the later job merge against the freshest persisted record.
-// Different projects still attach concurrently. (Shared per-key queue —
-// writers-room + catalog scene-image hooks use the same primitive.)
-const serializePerProject = createKeyCachedQueue();
-
-// Newest render (by job `queuedAt`) attached per scene, so an OLDER render that
-// completes AFTER a newer regenerate can't overwrite the newer frame. The GPU
-// lane is FIFO, but the Codex lane and renders kicked off from another client
-// (or after a refresh cleared the local spinner) can complete out of order —
-// "last write wins by completion order" would then show the new frame then
-// revert to the stale one. Keyed `${projectId}:${sceneId}` → queuedAt ISO; read
-// + written inside the per-project serialize section so it never races. In-memory
-// best-effort (lost on restart); one short string per rendered scene.
-// NOTE: the sibling completion hooks (writers-room / catalog) share the same
-// last-write-wins gap — generalizing this guard across them is part of #1791.
-const latestAttachedAt = new Map();
-
-let completedHandler = null;
+const hook = createMediaJobImageHook({
+ label: 'music-video scene-image',
+ initLog: '🎞️ Music Video scene-image hook initialized',
+ tagKey: 'musicVideo',
+ // Require both ids; the tag is otherwise ambiguous about which scene to file.
+ identify: (tag) => (tag?.projectId && tag.sceneId
+ ? { projectId: tag.projectId, sceneId: tag.sceneId }
+ : null),
+ // Serialize per PROJECT: two scene renders for the same project completing
+ // close together would otherwise both load→modify→save the one project record
+ // (file backend) and the later write would clobber the earlier scene's
+ // `referenceImageId`. Different projects still attach concurrently.
+ serializeKey: ({ projectId }) => projectId,
+ // Newest-render-wins per scene: the GPU lane is FIFO, but the Codex lane and
+ // renders kicked off from another client can complete out of order — drop an
+ // older render so it can't overwrite a newer reference frame.
+ sceneKey: ({ projectId, sceneId }) => `${projectId}:${sceneId}`,
+ attach: ({ projectId, sceneId, filename }) =>
+ updateScene(projectId, sceneId, { referenceImageId: filename }),
+ onAttached: ({ projectId, sceneId, filename }) => {
+ musicVideoEvents.emit('scene-image', { projectId, sceneId, referenceImageId: filename });
+ console.log(`🎞️ music-video scene image ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);
+ },
+});
export function initMusicVideoSceneImageHook() {
- // Idempotent: a stray double-init (test reload, future refactor) would
- // otherwise register two listeners and double-file every completed image.
- if (completedHandler) return;
-
- // EventEmitter does not await async listeners and does not catch their
- // rejections — a throw here would surface as a process-killing unhandled
- // rejection on Node ≥15. Use a sync listener that launches an async IIFE with
- // a top-level catch so this bookkeeping miss can never crash the server.
- completedHandler = (job) => {
- void (async () => {
- if (!job || job.kind !== 'image') return;
- const tag = job.params?.musicVideo;
- if (!tag?.projectId || !tag.sceneId) return;
- const filename = job.result?.filename;
- if (!filename || typeof filename !== 'string') return;
- const { projectId, sceneId } = tag;
- const queuedAt = typeof job.queuedAt === 'string' ? job.queuedAt : null;
- const sceneKey = `${projectId}:${sceneId}`;
-
- const updated = await serializePerProject(projectId, async () => {
- // Drop an out-of-order older render so it can't clobber a newer frame.
- // Fixed-width UTC ISO timestamps compare chronologically as strings.
- const prevAt = latestAttachedAt.get(sceneKey);
- if (queuedAt && prevAt && queuedAt < prevAt) return null;
- const result = await updateScene(projectId, sceneId, { referenceImageId: filename });
- if (queuedAt) latestAttachedAt.set(sceneKey, queuedAt);
- return result;
- }).catch((err) => {
- // A 404 here is expected and benign — the project or scene was deleted
- // while its render was in flight. Log and drop; never throw.
- console.log(`⚠️ music-video scene-image hook failed for ${filename} → ${projectId}/${sceneId}: ${err?.message || String(err)}`);
- return null;
- });
-
- if (updated) {
- musicVideoEvents.emit('scene-image', { projectId, sceneId, referenceImageId: filename });
- console.log(`🎞️ music-video scene image ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);
- }
- })().catch((err) => {
- // Last-resort net for synchronous throws (unexpected job shape, etc).
- console.log(`⚠️ music-video scene-image hook crashed: ${err?.message || err}`);
- });
- };
-
- mediaJobEvents.on('completed', completedHandler);
- console.log('🎞️ Music Video scene-image hook initialized');
+ hook.init();
}
-// Test-only reset so suites that re-init can do so cleanly. Removes the
-// previously registered listener so re-init doesn't leak handlers.
-export const __testing = {
- reset: () => {
- if (completedHandler) {
- mediaJobEvents.off('completed', completedHandler);
- completedHandler = null;
- }
- serializePerProject.clear();
- latestAttachedAt.clear();
- },
-};
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;
diff --git a/server/services/socket.js b/server/services/socket.js
index f6a5251507..3b09d58f42 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -20,6 +20,7 @@ import { sanitizePeerForClient } from './instances.js';
import { reviewEvents } from './review.js';
import { loopEvents } from './loops.js';
import { imageGenEvents } from './imageGenEvents.js';
+import { mediaJobEvents } from './mediaJobQueue/index.js';
import { importerEvents, getImporterProgressFrames } from './importerEvents.js';
import { catalogEvents } from './catalogEvents.js';
import { writersRoomEvents } from './writersRoomEvents.js';
@@ -991,4 +992,21 @@ function setupMediaGenEventForwarding() {
videoGenEvents.on('failed', (data) => {
if (ioInstance) ioInstance.emit('video-gen:failed', data);
});
+
+ // Bridge media-job cancellation onto a `*-gen:canceled` socket event keyed by
+ // `generationId` (#1791). The internal gen modules emit started/progress/
+ // completed/failed but have NO 'canceled' — a job canceled *while queued*
+ // never starts a gen run, so it produces only `mediaJobEvents 'canceled'` and
+ // no socket frame at all, leaving per-scene render spinners stuck until the
+ // component remounts. Every client spinner already correlates by media-job id
+ // (`data.generationId === jobId`), so a single id-keyed event clears the right
+ // spinner across writers-room, music-video, and `useMediaJobProgress`
+ // consumers (catalog et al.) uniformly — no per-domain event needed. For a
+ // job canceled *while running* this fires alongside the gen module's `failed`;
+ // both clear the spinner and the handlers are idempotent.
+ mediaJobEvents.on('canceled', (job) => {
+ if (!ioInstance || !job?.id) return;
+ const evt = job.kind === 'video' ? 'video-gen:canceled' : 'image-gen:canceled';
+ ioInstance.emit(evt, { generationId: job.id });
+ });
}
diff --git a/server/services/socket.test.js b/server/services/socket.test.js
index 6d4a8ccafa..2642d6945d 100644
--- a/server/services/socket.test.js
+++ b/server/services/socket.test.js
@@ -60,6 +60,7 @@ vi.mock('../sockets/voice.js', () => ({ registerVoiceHandlers: vi.fn() }));
import { initSocket } from './socket.js';
import { cosEvents } from './cosEvents.js';
+import { mediaJobEvents } from './mediaJobQueue/index.js';
import { detachSocketSessions } from './shell.js';
import * as shellService from './shell.js';
@@ -140,6 +141,20 @@ describe('socket.js — initSocket', () => {
// Tested via the subscription ack — the internal Set membership is observable
// through the ack emission which only happens when registerSubscriber runs.
// ===========================================================================
+ // ===========================================================================
+ // media-job cancellation bridge (#1791): mediaJobEvents 'canceled' → a
+ // generationId-keyed *-gen:canceled broadcast so stuck render spinners clear.
+ // ===========================================================================
+ it('bridges a canceled image job to image-gen:canceled keyed by generationId', () => {
+ mediaJobEvents.emit('canceled', { id: 'job-xyz', kind: 'image' });
+ expect(io.emitted).toContainEqual(['image-gen:canceled', { generationId: 'job-xyz' }]);
+ });
+
+ it('bridges a canceled video job to video-gen:canceled', () => {
+ mediaJobEvents.emit('canceled', { id: 'vid-1', kind: 'video' });
+ expect(io.emitted).toContainEqual(['video-gen:canceled', { generationId: 'vid-1' }]);
+ });
+
it('two independent sockets can both subscribe to cos independently', () => {
const s1 = makeSocket('s1');
const s2 = makeSocket('s2');
diff --git a/server/services/writersRoomSceneImageHook.js b/server/services/writersRoomSceneImageHook.js
index 06dc120d15..9c9b18f809 100644
--- a/server/services/writersRoomSceneImageHook.js
+++ b/server/services/writersRoomSceneImageHook.js
@@ -18,89 +18,58 @@
* On a successful attach the hook emits `writersRoomEvents` 'scene-image', which
* socket.js bridges to the client so the storyboard boards update reactively.
*
- * Mounted once at server boot from server/index.js (after the media job queue is
- * running). Best-effort: a bookkeeping miss is logged but never thrown — it must
- * not crash the server or fail the user's render.
+ * The shared completion-hook scaffold (tag-decode, per-analysis serialization,
+ * the newest-render-wins guard, best-effort error handling, idempotent init/
+ * reset) lives in `createMediaJobImageHook` (#1791) — this file is just the
+ * writers-room-specific config. Mounted once at server boot from server/index.js
+ * (after the media job queue is running).
*/
-import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { persistSceneImage } from './writersRoom/evaluator.js';
import { writersRoomEvents } from './writersRoomEvents.js';
-import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
-// Serialize attaches per analysis FILE (workId:analysisId). Two scene renders
-// for the same analysis completing close together would otherwise both
-// load→modify→save the one `sceneImages` map and the later write would clobber
-// the earlier scene's entry. Chaining each attach onto the prior one for that
-// analysis makes the later job merge against the freshest persisted snapshot.
-// Different analyses (and different works) still attach concurrently. (Shared
-// per-key queue — catalog + music-video scene-image hooks use the same primitive.)
-const serializePerAnalysis = createKeyCachedQueue();
+// The render filename is `${jobId}.png`; prefer the job id, fall back to
+// stripping the extension so the attach records a stable jobId either way.
+const deriveJobId = (job, filename) =>
+ (typeof job.id === 'string' && job.id ? job.id : filename.replace(/\.png$/, ''));
+// The gen prompt IS the scene prompt (buildScenePrompt output), so record it on
+// the attach without the tag having to carry a duplicate copy.
+const derivePrompt = (job) => (typeof job.params?.prompt === 'string' ? job.params.prompt : null);
-let completedHandler = null;
+const hook = createMediaJobImageHook({
+ label: 'writers-room scene-image',
+ initLog: '🎬 Writers-Room scene-image hook initialized',
+ tagKey: 'writersRoom',
+ identify: (tag) => (tag?.workId && tag.analysisId && tag.sceneId
+ ? { workId: tag.workId, analysisId: tag.analysisId, sceneId: tag.sceneId }
+ : null),
+ // Serialize per analysis FILE (workId:analysisId): two scene renders for the
+ // same analysis completing close together would otherwise both
+ // load→modify→save the one `sceneImages` map and the later write would clobber
+ // the earlier scene's entry. Different analyses (and works) attach concurrently.
+ serializeKey: ({ workId, analysisId }) => `${workId}:${analysisId}`,
+ // Newest-render-wins per scene frame so an older render that completes after a
+ // newer regenerate can't overwrite the newer storyboard frame (#1791).
+ sceneKey: ({ workId, analysisId, sceneId }) => `${workId}:${analysisId}:${sceneId}`,
+ attach: ({ workId, analysisId, sceneId, filename, job }) =>
+ persistSceneImage(workId, analysisId, {
+ sceneId, filename, jobId: deriveJobId(job, filename), prompt: derivePrompt(job),
+ }),
+ onAttached: ({ workId, analysisId, sceneId, filename, job }, result) => {
+ // persistSceneImage normally returns { analysis, collectionId }; only emit
+ // when the snapshot actually came back so the client merges a real entry.
+ if (!result?.analysis) return;
+ const image = result.analysis.sceneImages?.[sceneId]
+ || { filename, jobId: deriveJobId(job, filename), prompt: derivePrompt(job) };
+ writersRoomEvents.emit('scene-image', { workId, analysisId, sceneId, image });
+ console.log(`🎬 writers-room scene image ${workId.slice(0, 8)}/${sceneId} ← ${filename}`);
+ },
+});
export function initWritersRoomSceneImageHook() {
- // Idempotent: a stray double-init (test reload, future refactor) would
- // otherwise register two listeners and double-file every completed image.
- if (completedHandler) return;
-
- // EventEmitter does not await async listeners and does not catch their
- // rejections — a throw here would surface as a process-killing unhandled
- // rejection on Node ≥15. Use a sync listener that launches an async IIFE with
- // a top-level catch so this bookkeeping miss can never crash the server.
- completedHandler = (job) => {
- void (async () => {
- if (!job || job.kind !== 'image') return;
- const tag = job.params?.writersRoom;
- if (!tag?.workId || !tag.analysisId || !tag.sceneId) return;
- const filename = job.result?.filename;
- if (!filename || typeof filename !== 'string') return;
- // The render filename is `${jobId}.png`; prefer the job id, fall back to
- // stripping the extension so the attach records a stable jobId either way.
- const jobId = typeof job.id === 'string' && job.id ? job.id : filename.replace(/\.png$/, '');
- // The gen prompt IS the scene prompt (buildScenePrompt output), so record
- // it on the attach without the tag having to carry a duplicate copy.
- const prompt = typeof job.params?.prompt === 'string' ? job.params.prompt : null;
- const key = `${tag.workId}:${tag.analysisId}`;
-
- const result = await serializePerAnalysis(key, () =>
- persistSceneImage(tag.workId, tag.analysisId, { sceneId: tag.sceneId, filename, jobId, prompt }),
- ).catch((err) => {
- console.log(`⚠️ writers-room scene-image hook failed for ${filename} → ${tag.workId}/${tag.sceneId}: ${err?.message || String(err)}`);
- return null;
- });
-
- if (result?.analysis) {
- // Emit the freshly-stored entry so the client board merges exactly what
- // landed on disk (falling back to the bare fields if the snapshot didn't
- // echo it for some reason).
- const image = result.analysis.sceneImages?.[tag.sceneId] || { filename, jobId, prompt };
- writersRoomEvents.emit('scene-image', {
- workId: tag.workId,
- analysisId: tag.analysisId,
- sceneId: tag.sceneId,
- image,
- });
- console.log(`🎬 writers-room scene image ${tag.workId.slice(0, 8)}/${tag.sceneId} ← ${filename}`);
- }
- })().catch((err) => {
- // Last-resort net for synchronous throws (unexpected job shape, etc).
- console.log(`⚠️ writers-room scene-image hook crashed: ${err?.message || err}`);
- });
- };
-
- mediaJobEvents.on('completed', completedHandler);
- console.log('🎬 Writers-Room scene-image hook initialized');
+ hook.init();
}
-// Test-only reset so suites that re-init can do so cleanly. Removes the
-// previously registered listener so re-init doesn't leak handlers.
-export const __testing = {
- reset: () => {
- if (completedHandler) {
- mediaJobEvents.off('completed', completedHandler);
- completedHandler = null;
- }
- serializePerAnalysis.clear();
- },
-};
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;
diff --git a/server/services/writersRoomSceneImageHook.test.js b/server/services/writersRoomSceneImageHook.test.js
index 6b0ea5ebe5..3b81faa9ea 100644
--- a/server/services/writersRoomSceneImageHook.test.js
+++ b/server/services/writersRoomSceneImageHook.test.js
@@ -117,4 +117,37 @@ describe('writersRoomSceneImageHook', () => {
await new Promise((r) => setTimeout(r, 30));
expect(emitted).toHaveLength(0);
});
+
+ it('does not let an older render (earlier queuedAt) overwrite a newer scene frame (#1791)', async () => {
+ // Newer render lands first, then an out-of-order older one completes.
+ mediaJobEvents.emit('completed', {
+ kind: 'image', id: 'b', params: { writersRoom: tag() }, result: { filename: 'new.png' },
+ queuedAt: '2026-06-29T00:00:02.000Z',
+ });
+ await waitFor(() => persistSceneImage.mock.calls.length > 0);
+ mediaJobEvents.emit('completed', {
+ kind: 'image', id: 'a', params: { writersRoom: tag() }, result: { filename: 'old.png' },
+ queuedAt: '2026-06-29T00:00:01.000Z',
+ });
+ await new Promise((r) => setTimeout(r, 30));
+ // The newer frame persisted; the older one was dropped (never re-persisted).
+ expect(persistSceneImage).toHaveBeenCalledTimes(1);
+ expect(persistSceneImage.mock.calls[0][2].filename).toBe('new.png');
+ expect(emitted.map((e) => e.image.filename)).toEqual(['new.png']);
+ });
+
+ it('newest-wins is per scene — an older render on a DIFFERENT scene still applies', async () => {
+ mediaJobEvents.emit('completed', {
+ kind: 'image', id: 'b', params: { writersRoom: tag({ sceneId: 's1' }) }, result: { filename: 'new.png' },
+ queuedAt: '2026-06-29T00:00:02.000Z',
+ });
+ await waitFor(() => persistSceneImage.mock.calls.length > 0);
+ // Older queuedAt but a different sceneId — must NOT be dropped.
+ mediaJobEvents.emit('completed', {
+ kind: 'image', id: 'a', params: { writersRoom: tag({ sceneId: 's2' }) }, result: { filename: 'other.png' },
+ queuedAt: '2026-06-29T00:00:01.000Z',
+ });
+ await waitFor(() => persistSceneImage.mock.calls.length > 1);
+ expect(persistSceneImage).toHaveBeenCalledTimes(2);
+ });
});