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

feat: fold Writers-Room storyboard scene-image attach into the render completion hook (#1363)

Adam Eivydd9a528bb290
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f8c871482f..06ad7701a2 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -166,3 +166,5 @@
- **[issue-1207] Messages, Wiki, Feature Agents, and Creative Director now use the shared `PageHeader` title bar.** These four tabbed/top-level pages still hand-rolled the same icon + `<h1>` + subtitle + `border-b border-port-border` bar with their own padding and title scale, so navigating between them and the already-adopted pages (Brain, MeatSpace, Settings, Goals, Calendar, Insights — #1182) produced visual jitter. Each now renders `PageHeader` with its stats/controls moved into the `actions` slot: Messages' account count, Wiki's page/source counts + vault `<select>`, Feature Agents' refresh button + "New Agent" link, and Creative Director's smoke-test + "New project" buttons. Creative Director's subtitle token reconciles from `text-port-text-muted` to `PageHeader`'s `text-gray-500` (and its title from `font-semibold` to the shared `font-bold`) as called out in the issue. AIProviders/PromptManager were correctly left alone — they render inside the Settings shell, not a standalone bar. (`client/src/pages/Messages.jsx`, `client/src/pages/Wiki.jsx`, `client/src/pages/FeatureAgents.jsx`, `client/src/pages/CreativeDirector.jsx`, #1207)
- **[issue-1362] The pipeline Nouns stage and the Story Builder characters step now auto-file their reference renders server-side instead of round-tripping a follow-up PATCH.** Both surfaces used the generate-then-attach anti-pattern that #1395 already removed from the Universe canon section: they POSTed an *untagged* render, then on completion made a second full-array `updateUniverse` PATCH purely to append the new filename onto the entry's `imageRefs[]` (Story Builder even refetched the universe first to avoid clobbering a sibling's `imageRefs[]` — work the server-side append does atomically). The render carried no `universeRun` tag, so the existing `appendEntryImageRef` completion hook never fired and a render that finished *after* the page unmounted lost its attachment. Both call sites now thread a durable `universeRun.entryRef` tag through the generate call (canon → `kindKey` + id, the same shape the batch path uses), so `universeBuilderCollectionHook` files the finished render into the universe collection AND appends it to the entry's `imageRefs[]` independent of any mounted client. The client keeps only an optimistic, dedup-guarded + last-N-capped local stamp for an instant thumbnail (no PATCH; no refetch-before-PATCH race). The tag builder shared by all three call sites is extracted to `client/src/lib/universeRunTag.js` (`buildUniverseSectionRenderTag`), replacing UniverseCanonSection's inline copy. (`client/src/lib/universeRunTag.js`, `client/src/components/pipeline/stages/NounsStage.jsx`, `client/src/pages/StoryBuilder.jsx`, `client/src/components/universe/UniverseCanonSection.jsx`, #1362)
+
+- **[issue-1363] Writers-Room storyboard scene renders now attach durably server-side instead of via a generate-then-attach round-trip.** Both render entry points — the per-scene `SceneCard` "Image" button and the cursor-driven `LiveRenderPanel` "Render scene" — fired an *untagged* image render, then on the `image-gen:completed` socket event made a **second** call (`attachWritersRoomSceneImage`) to file the rendered filename onto the analysis snapshot's `sceneImages[sceneId]`. That second call lost the image whenever the render finished *after* the editor unmounted / the user navigated away. The render now threads a durable `writersRoom: { workId, analysisId, sceneId }` job tag, and a new completion hook (`writersRoomSceneImageHook`) files the finished render onto the snapshot AND mirrors it into the work's auto-collection independent of any mounted client — converging this surface onto the same durable hook path the universe (#1395/#1362) and catalog (#1359) renders use. The hook serializes attaches per analysis file so two scenes completing back-to-back can't clobber each other's `sceneImages` entry, and emits a `writers-room:scene-image` socket event so the storyboard boards still update reactively without a refetch. The shared attach+mirror logic the route and hook both run is extracted to `persistSceneImage` (evaluator). Only the async local/Codex lanes ride the media-job queue the hook listens to; the synchronous external SD-API lane (which returns its filename inline) still attaches via the `scene-image` route, so it keeps working. (`server/routes/imageGen.js`, `server/services/writersRoomSceneImageHook.js`, `server/services/writersRoomEvents.js`, `server/services/writersRoom/evaluator.js`, `server/routes/writersRoom.js`, `server/services/socket.js`, `server/index.js`, `client/src/lib/wrImageDefaults.js`, `client/src/components/writers-room/{SceneCard,LiveRenderPanel}.jsx`, #1363)
diff --git a/client/src/components/writers-room/LiveRenderPanel.jsx b/client/src/components/writers-room/LiveRenderPanel.jsx
index b7fceeb2a1..f9c45fadc0 100644
--- a/client/src/components/writers-room/LiveRenderPanel.jsx
+++ b/client/src/components/writers-room/LiveRenderPanel.jsx
@@ -67,12 +67,15 @@ export default function LiveRenderPanel({
const scenes = useMemo(() => (Array.isArray(ctx.scenes) ? ctx.scenes : []), [ctx.scenes]);
const imageCfg = ctx.imageCfg || WR_IMAGE_DEFAULTS;
- // Persist a finished render onto the script analysis (best-effort, mirroring
- // SceneCard) AND fold the returned sceneImages map up so the storyboard
- // updates reactively without a refetch. Shared by the socket-completion path
- // and the fast synchronous-completion path. Takes a job snapshot so it never
- // reads live state. { silent: true } because we own the error UI here (a
- // console.warn) — without it the helper would also toast.
+ // Persist a finished render onto the script analysis AND fold the returned
+ // sceneImages map up so the storyboard updates reactively without a refetch.
+ // Used ONLY by the fast synchronous-completion path (external SD-API), which
+ // returns its filename inline and never rides the media-job queue the
+ // server-side writersRoomSceneImageHook listens to (#1363). The async
+ // local/Codex lanes file durably via that hook and refresh the boards through
+ // the `writers-room:scene-image` socket event below — no client round-trip.
+ // Takes a job snapshot so it never reads live state. { silent: true } because
+ // we own the error UI here (a console.warn) — without it the helper would also toast.
const persistAttach = useCallback((job) => {
if (!workId || !job?.analysisId || !job.jobId || !job.sceneId) return;
attachWritersRoomSceneImage(workId, job.analysisId, {
@@ -103,9 +106,10 @@ export default function LiveRenderPanel({
if (!job || data.generationId !== job.jobId) return;
pendingJobRef.current = null;
if (mountedRef.current) setGenStatus('idle');
- // Prefer the prompt captured at kickoff (queued completion events from
- // local/codex don't echo the prompt); fall back to the event's if present.
- persistAttach({ ...job, prompt: job.prompt || data.prompt });
+ // The async render's durable attach is filed server-side by
+ // writersRoomSceneImageHook off this job's `writersRoom` tag (#1363); the
+ // boards refresh via the `writers-room:scene-image` event below, so there's
+ // no client attach here. Button state only.
};
const onFailed = (data) => {
const job = pendingJobRef.current;
@@ -113,15 +117,28 @@ export default function LiveRenderPanel({
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
+ // merge guards on analysis id, so a stale analysisId is dropped there.
+ const onSceneImage = (data) => {
+ if (!data || data.workId !== workId || !data.analysisId || !data.sceneId) return;
+ if (mountedRef.current) {
+ onAttachedRef.current?.({ id: data.analysisId, sceneImages: { [data.sceneId]: data.image } });
+ }
+ };
socket.on('image-gen:completed', onCompleted);
socket.on('image-gen:failed', onFailed);
+ socket.on('writers-room:scene-image', onSceneImage);
return () => {
socket.off('image-gen:completed', onCompleted);
socket.off('image-gen:failed', onFailed);
+ socket.off('writers-room:scene-image', onSceneImage);
};
- // The job snapshot is read from pendingJobRef (set at kickoff); persistAttach
- // is identity-stable, so this effect binds once.
- }, [persistAttach, mountedRef]);
+ // The job snapshot is read from pendingJobRef (set at kickoff); the attach
+ // bridge is read through onAttachedRef. Re-bind when workId changes so the
+ // scene-image gate matches the current work.
+ }, [mountedRef, workId]);
const renderCursorScene = useCallback(async () => {
if (reserving || genStatus === 'running') return;
@@ -169,6 +186,7 @@ export default function LiveRenderPanel({
prompt,
negativePrompt: ctx.imageStyle?.negativePrompt || '',
imageCfg,
+ writersRoom: { workId, analysisId, sceneId: scene.id },
}), { silent: true }).catch((err) => {
if (mountedRef.current) {
toast.error(`Render failed: ${err.message}`);
diff --git a/client/src/components/writers-room/SceneCard.jsx b/client/src/components/writers-room/SceneCard.jsx
index ca62f83e61..7dcd4c50b9 100644
--- a/client/src/components/writers-room/SceneCard.jsx
+++ b/client/src/components/writers-room/SceneCard.jsx
@@ -10,9 +10,6 @@ import {
} from 'lucide-react';
import toast from '../ui/Toast';
import { generateImage } from '../../services/apiSystem';
-import {
- attachWritersRoomSceneImage,
-} from '../../services/apiWritersRoom';
import socket from '../../services/socket';
import useClickOutside from '../../hooks/useClickOutside';
import { WR_IMAGE_DEFAULTS, buildSceneRenderPayload } from '../../lib/wrImageDefaults';
@@ -113,21 +110,13 @@ const SceneCard = forwardRef(function SceneCard({
};
const onCompleted = (data) => {
if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
- const completedJobId = jobIdRef.current;
+ // The optimistic preview already shows this render; the durable attach
+ // onto the analysis snapshot is filed server-side by writersRoomSceneImageHook
+ // off the same job's `writersRoom` tag (#1363), so no client round-trip here.
setGenerated((prev) => prev ? { ...prev, path: data.path || prev.path } : prev);
setGenStatus('done');
setProgress(null);
jobIdRef.current = null;
- if (workId && analysisId && scene.id) {
- attachWritersRoomSceneImage(workId, analysisId, {
- sceneId: scene.id,
- filename: `${completedJobId}.png`,
- jobId: completedJobId,
- prompt: data.prompt || null,
- }, { silent: true }).catch((err) => {
- console.warn(`scene-image persist failed: ${err.message}`);
- });
- }
};
const onFailed = (data) => {
if (!jobIdRef.current || data.generationId !== jobIdRef.current) return;
@@ -163,6 +152,9 @@ const SceneCard = forwardRef(function SceneCard({
prompt,
negativePrompt: imageStyle?.negativePrompt || '',
imageCfg,
+ writersRoom: workId && analysisId && scene.id
+ ? { workId, analysisId, sceneId: scene.id }
+ : null,
}), { silent: true }).catch((err) => {
setError(err.message);
setGenStatus('error');
diff --git a/client/src/lib/wrImageDefaults.js b/client/src/lib/wrImageDefaults.js
index 1f1d71785f..934a0799e9 100644
--- a/client/src/lib/wrImageDefaults.js
+++ b/client/src/lib/wrImageDefaults.js
@@ -30,7 +30,12 @@ export const WR_IMAGE_DEFAULTS = Object.freeze({
// the payload shape both SceneCard and the live render preview send. Keeping
// the steps/seed parsing in one place means the two render entry points can't
// drift on what "use the model default" means.
-export function buildSceneRenderPayload({ prompt, negativePrompt = '', imageCfg = WR_IMAGE_DEFAULTS }) {
+//
+// `writersRoom` ({ workId, analysisId, sceneId }), when provided, tags the
+// render so the server-side completion hook files it onto the analysis snapshot
+// durably — sparing the client a generate-then-attach round-trip on the async
+// local/Codex lanes (#1363).
+export function buildSceneRenderPayload({ prompt, negativePrompt = '', imageCfg = WR_IMAGE_DEFAULTS, writersRoom = null }) {
const stepsNum = imageCfg.steps ? Number(imageCfg.steps) : undefined;
const seedNum = imageCfg.seed && Number(imageCfg.seed) >= 0 ? Number(imageCfg.seed) : undefined;
return {
@@ -42,6 +47,7 @@ export function buildSceneRenderPayload({ prompt, negativePrompt = '', imageCfg
height: imageCfg.height,
...(Number.isFinite(stepsNum) ? { steps: stepsNum } : {}),
...(Number.isFinite(seedNum) ? { seed: seedNum } : {}),
+ ...(writersRoom ? { writersRoom } : {}),
};
}
diff --git a/client/src/lib/wrImageDefaults.test.js b/client/src/lib/wrImageDefaults.test.js
new file mode 100644
index 0000000000..19ac1ffa2d
--- /dev/null
+++ b/client/src/lib/wrImageDefaults.test.js
@@ -0,0 +1,37 @@
+import { describe, it, expect } from 'vitest';
+import { buildSceneRenderPayload, WR_IMAGE_DEFAULTS } from './wrImageDefaults';
+
+describe('buildSceneRenderPayload', () => {
+ it('folds prompt + imageCfg into the generate payload, dropping empty steps/seed', () => {
+ const payload = buildSceneRenderPayload({ prompt: 'a quiet alley', negativePrompt: 'blurry' });
+ expect(payload).toEqual({
+ prompt: 'a quiet alley',
+ negativePrompt: 'blurry',
+ modelId: WR_IMAGE_DEFAULTS.modelId,
+ mode: WR_IMAGE_DEFAULTS.mode,
+ width: WR_IMAGE_DEFAULTS.width,
+ height: WR_IMAGE_DEFAULTS.height,
+ });
+ expect(payload).not.toHaveProperty('writersRoom');
+ });
+
+ it('parses string steps/seed to numbers', () => {
+ const payload = buildSceneRenderPayload({
+ prompt: 'p',
+ imageCfg: { ...WR_IMAGE_DEFAULTS, steps: '20', seed: '7' },
+ });
+ expect(payload.steps).toBe(20);
+ expect(payload.seed).toBe(7);
+ });
+
+ it('includes the writersRoom destination tag when provided', () => {
+ const writersRoom = { workId: 'w1', analysisId: 'script', sceneId: 's1' };
+ const payload = buildSceneRenderPayload({ prompt: 'p', writersRoom });
+ expect(payload.writersRoom).toEqual(writersRoom);
+ });
+
+ it('omits the writersRoom tag when null (synchronous lane / missing ids)', () => {
+ const payload = buildSceneRenderPayload({ prompt: 'p', writersRoom: null });
+ expect(payload).not.toHaveProperty('writersRoom');
+ });
+});
diff --git a/server/index.js b/server/index.js
index eece83be2e..6c260ff2cd 100644
--- a/server/index.js
+++ b/server/index.js
@@ -109,6 +109,7 @@ import authorsRoutes from './routes/authors.js';
import conflictJournalRoutes from './routes/conflictJournal.js';
import { initUniverseBuilderCollectionHook } from './services/universeBuilderCollectionHook.js';
import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
+import { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';
@@ -762,6 +763,10 @@ ensureSelf()
// ingredient on completion, even if the editor page unmounted mid-render
// (#1359). Also depends on the media job queue being loaded.
initCatalogImageAttachHook();
+ // Writers-Room scene-image hook — durably files a queued storyboard render
+ // onto its analysis snapshot + work collection on completion, even if the
+ // editor unmounted mid-render (#1363). Also depends on the queue being loaded.
+ initWritersRoomSceneImageHook();
// Pipeline filename hooks — stamp `filename` onto stage records on
// media-job completion so the UI can still render them after the
// 24h media-job archive TTL elapses.
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index 1c7e79e8a3..e4694fa30b 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -132,6 +132,21 @@ const generateSchema = z.object({
{ message: 'entryRef requires its locating key (canon→kindKey, variation→categoryKey)' },
).optional(),
}).optional(),
+ // Writers-Room storyboard scene render (#1363). When present, the mediaJobQueue
+ // completion hook (`writersRoomSceneImageHook`) files the finished render onto
+ // the analysis snapshot's `sceneImages[sceneId]` AND mirrors it into the work's
+ // auto-collection — durably, even if the editor unmounted mid-render (the
+ // "navigated away → image never attached" failure mode the synchronous attach
+ // suffered). Only the async local/Codex lanes ride the queue this hook listens
+ // to; the synchronous external SD-API lane still attaches via the scene-image
+ // route. The scene prompt is read from the job's own `prompt` param, so the tag
+ // carries only the destination identity. JSON-only (the multipart ImageGen page
+ // never sends it).
+ writersRoom: z.object({
+ workId: z.string().min(1).max(200),
+ analysisId: z.string().min(1).max(200),
+ sceneId: z.string().min(1).max(200),
+ }).optional(),
// Durable catalog attach (#1359). When present, the mediaJobQueue completion
// hook (catalogImageAttachHook) files the finished render onto this catalog
// ingredient even if the page that started the render has since unmounted —
diff --git a/server/routes/writersRoom.js b/server/routes/writersRoom.js
index 66e1f375c9..81e77dcf3d 100644
--- a/server/routes/writersRoom.js
+++ b/server/routes/writersRoom.js
@@ -32,10 +32,9 @@ import {
listWorks, getWorkWithBody, createWork, updateWork, deleteWork,
saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
listExercises, createExercise, finishExercise, discardExercise,
- ensureWorkMediaCollection,
} from '../services/writersRoom/local.js';
import {
- runAnalysis, listAnalyses, getAnalysis, attachSceneImage,
+ runAnalysis, listAnalyses, getAnalysis, persistSceneImage,
} from '../services/writersRoom/evaluator.js';
import { getSyncedReview } from '../services/writersRoom/syncedReview.js';
import {
@@ -51,7 +50,6 @@ import {
listObjects, createObject, updateObject, deleteObject,
} from '../services/writersRoom/objects.js';
import { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } from '../services/writersRoom/promoteToPipeline.js';
-import { addItem as addCollectionItem, ERR_DUPLICATE } from '../services/mediaCollections.js';
import { scanProseForIngredientRefs } from '../services/catalogExtraction.js';
const router = Router();
@@ -306,17 +304,16 @@ router.delete('/works/:id/objects/:objectId', asyncHandler(async (req, res) => {
// Persist a scene→generated-image link on the analysis snapshot, AND mirror
// the image into the work's auto-collection so it appears in MediaGen's
-// Collections view. Called by SceneCard when image-gen:completed fires.
+// Collections view. Retained for the synchronous (external SD-API) render lane,
+// which returns its filename inline and never rides the media-job queue the
+// `writersRoomSceneImageHook` listens to (#1363); the async local/Codex lanes
+// now file durably via that hook instead.
router.post('/works/:id/analysis/:analysisId/scene-image', asyncHandler(async (req, res) => {
const { sceneId, filename, jobId, prompt } = req.body || {};
- const updated = await attachSceneImage(req.params.id, req.params.analysisId, { sceneId, filename, jobId, prompt });
- // Add to the per-work collection. Best-effort — a duplicate (same render
- // already in the collection) is a no-op, not an error.
- const collection = await ensureWorkMediaCollection(req.params.id);
- await addCollectionItem(collection.id, { kind: 'image', ref: filename }).catch((err) => {
- if (err?.code !== ERR_DUPLICATE) throw err;
- });
- res.json({ analysis: updated, collectionId: collection.id });
+ const { analysis, collectionId } = await persistSceneImage(
+ req.params.id, req.params.analysisId, { sceneId, filename, jobId, prompt },
+ );
+ res.json({ analysis, collectionId });
}));
export default router;
diff --git a/server/services/socket.js b/server/services/socket.js
index b1890572a8..2aa8f8a04d 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -22,6 +22,7 @@ import { loopEvents } from './loops.js';
import { imageGenEvents } from './imageGenEvents.js';
import { importerEvents, getImporterProgressFrames } from './importerEvents.js';
import { catalogEvents } from './catalogEvents.js';
+import { writersRoomEvents } from './writersRoomEvents.js';
import { videoGenEvents } from './videoGen/events.js';
import { aiStatusEvents } from './aiStatusEvents.js';
import { wireProactiveTriggers } from './voice/proactiveTriggers.js';
@@ -642,6 +643,9 @@ export function initSocket(io) {
// Set up catalog extraction-progress forwarding (broadcast to all clients)
setupCatalogEventForwarding();
+ // Set up Writers-Room scene-image forwarding (broadcast to all clients)
+ setupWritersRoomEventForwarding();
+
// Wire proactive voice (CoS speaks first on high-severity errors, new tasks,
// and high-priority notifications — rate-limited per source).
setupProactiveSpeechForwarding();
@@ -669,6 +673,17 @@ function setupCatalogEventForwarding() {
});
}
+let writersRoomForwardingSetup = false;
+function setupWritersRoomEventForwarding() {
+ if (writersRoomForwardingSetup) return;
+ writersRoomForwardingSetup = true;
+ // A storyboard render filed durably by writersRoomSceneImageHook — bridge it
+ // so the boards update reactively without a refetch (#1363).
+ writersRoomEvents.on('scene-image', (data) => {
+ if (ioInstance) ioInstance.emit('writers-room:scene-image', data);
+ });
+}
+
let aiStatusForwardingSetup = false;
function setupAIStatusEventForwarding() {
if (aiStatusForwardingSetup) return;
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 35a6ab64bc..1f449cadda 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -14,7 +14,8 @@ import { extractBible } from '../../lib/bibleExtractor.js';
import { extractScenes, SOURCE_KIND } from '../../lib/sceneExtractor.js';
import { BIBLE_KIND } from '../../lib/storyBible.js';
import { ANALYSIS_KINDS } from '../../lib/writersRoomPresets.js';
-import { getWorkWithBody } from './local.js';
+import { getWorkWithBody, ensureWorkMediaCollection } from './local.js';
+import { addItem as addCollectionItem, ERR_DUPLICATE } from '../mediaCollections.js';
import { listCharacters, mergeExtractedCharacters } from './characters.js';
import { listPlaces, mergeExtractedPlaces } from './places.js';
import { listObjects, mergeExtractedObjects } from './objects.js';
@@ -172,6 +173,22 @@ export async function attachSceneImage(workId, id, { sceneId, filename, jobId, p
return next;
}
+// Persist a scene→generated-image link on the analysis snapshot AND mirror the
+// image into the work's auto-collection (so it appears in MediaGen's
+// Collections view). Shared by the HTTP `scene-image` route and the image-job
+// completion hook (#1363) so the render-then-attach flow converges on one
+// durable path — neither caller can drift on what "file this render" means.
+// Best-effort collection mirror: a duplicate (same render already filed) is a
+// no-op, not an error. Returns `{ analysis, collectionId }`.
+export async function persistSceneImage(workId, id, { sceneId, filename, jobId, prompt }) {
+ const analysis = await attachSceneImage(workId, id, { sceneId, filename, jobId, prompt });
+ const collection = await ensureWorkMediaCollection(workId);
+ await addCollectionItem(collection.id, { kind: 'image', ref: filename }).catch((err) => {
+ if (err?.code !== ERR_DUPLICATE) throw err;
+ });
+ return { analysis, collectionId: collection.id };
+}
+
// ---------- startup recovery ----------
// Walk every wr-analysis-<uuid>.json file in a work's analysis dir, group by
diff --git a/server/services/writersRoomEvents.js b/server/services/writersRoomEvents.js
new file mode 100644
index 0000000000..1c3cf11b47
--- /dev/null
+++ b/server/services/writersRoomEvents.js
@@ -0,0 +1,13 @@
+import { EventEmitter } from 'events';
+
+// Event bus for Writers-Room async side effects that need to reach the client
+// after the originating HTTP request has returned. Today it carries one event:
+//
+// 'scene-image' → { workId, analysisId, sceneId, image }
+//
+// emitted by `writersRoomSceneImageHook` once an async (local/Codex) storyboard
+// render has been durably filed onto the analysis snapshot. socket.js bridges
+// it to `writers-room:scene-image` on Socket.IO so the storyboard boards update
+// reactively without a refetch — the durable, hook-driven replacement for the
+// client's old generate-then-attach round-trip (#1363).
+export const writersRoomEvents = new EventEmitter();
diff --git a/server/services/writersRoomSceneImageHook.js b/server/services/writersRoomSceneImageHook.js
new file mode 100644
index 0000000000..ed315c08d6
--- /dev/null
+++ b/server/services/writersRoomSceneImageHook.js
@@ -0,0 +1,118 @@
+/**
+ * Writers-Room scene-image attach hook (issue #1363).
+ *
+ * Subscribes to mediaJobEvents and, for each completed image job that carries
+ * `params.writersRoom`, files the rendered filename onto that work's analysis
+ * snapshot (`sceneImages[sceneId]`) and mirrors it into the work's auto-
+ * collection — server-side, independent of any mounted client. This is the
+ * durable counterpart to SceneCard / LiveRenderPanel's old generate-then-attach
+ * round-trip: a long-running local/Codex render that completes after the user
+ * navigated away, refreshed, or moved their cursor still lands on the snapshot
+ * (previously the image reached the gallery but the analysis link was lost).
+ *
+ * Only the async local/Codex lanes ride the media-job queue this hook listens
+ * to. The synchronous external SD-API lane returns its filename inline and
+ * attaches via the `scene-image` route directly — same split the catalog hook
+ * (#1359) documents.
+ *
+ * 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.
+ */
+
+import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { persistSceneImage } from './writersRoom/evaluator.js';
+import { writersRoomEvents } from './writersRoomEvents.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. In-memory
+// tail, evicted once settled; lost on restart, which is fine — best-effort.
+const attachTails = new Map();
+
+function serializePerAnalysis(key, work) {
+ const prev = attachTails.get(key) || Promise.resolve();
+ // Run `work` on both fulfil AND reject so a prior failure doesn't stall the chain.
+ const next = prev.then(work, work);
+ attachTails.set(key, next);
+ // Evict once settled, but only if nothing newer has chained on. Swallow here
+ // so eviction can't surface as an unhandled rejection — the caller attaches
+ // its own `.catch` to the returned promise.
+ const evict = () => { if (attachTails.get(key) === next) attachTails.delete(key); };
+ next.then(evict, evict);
+ return next;
+}
+
+let completedHandler = null;
+
+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');
+}
+
+// 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;
+ }
+ attachTails.clear();
+ },
+};
diff --git a/server/services/writersRoomSceneImageHook.test.js b/server/services/writersRoomSceneImageHook.test.js
new file mode 100644
index 0000000000..6b0ea5ebe5
--- /dev/null
+++ b/server/services/writersRoomSceneImageHook.test.js
@@ -0,0 +1,120 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+// Mock the evaluator so the hook's tag-decode + serialize + emit logic is
+// exercised without touching disk. `persistSceneImage` is reprogrammed per-test
+// to stand in for the durable attach.
+const persistSceneImage = vi.fn(async (workId, analysisId, { sceneId, filename, jobId, prompt }) => ({
+ analysis: { id: analysisId, sceneImages: { [sceneId]: { filename, jobId, prompt, generatedAt: 't' } } },
+ collectionId: 'col-1',
+}));
+vi.mock('./writersRoom/evaluator.js', () => ({ persistSceneImage }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const { writersRoomEvents } = await import('./writersRoomEvents.js');
+const hook = await import('./writersRoomSceneImageHook.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 tag = (over = {}) => ({ workId: 'w1', analysisId: 'script', sceneId: 's1', ...over });
+const completedImageJob = ({ params = {}, filename = 'job-abc.png', id = 'job-abc' } = {}) => ({
+ kind: 'image', id, params, result: { filename },
+});
+
+describe('writersRoomSceneImageHook', () => {
+ let emitted;
+ const capture = (data) => emitted.push(data);
+
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initWritersRoomSceneImageHook();
+ persistSceneImage.mockReset();
+ persistSceneImage.mockImplementation(async (workId, analysisId, { sceneId, filename, jobId, prompt }) => ({
+ analysis: { id: analysisId, sceneImages: { [sceneId]: { filename, jobId, prompt, generatedAt: 't' } } },
+ collectionId: 'col-1',
+ }));
+ emitted = [];
+ writersRoomEvents.on('scene-image', capture);
+ });
+
+ afterEach(() => {
+ hook.__testing.reset();
+ writersRoomEvents.off('scene-image', capture);
+ });
+
+ it('files a scene image and emits scene-image for a writersRoom-tagged job', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({
+ params: { writersRoom: tag(), prompt: 'a cinematic alley' },
+ filename: 'job-abc.png', id: 'job-abc',
+ }));
+ await waitFor(() => emitted.length > 0);
+ expect(persistSceneImage).toHaveBeenCalledWith('w1', 'script', {
+ sceneId: 's1', filename: 'job-abc.png', jobId: 'job-abc', prompt: 'a cinematic alley',
+ });
+ expect(emitted[0]).toEqual({
+ workId: 'w1', analysisId: 'script', sceneId: 's1',
+ image: { filename: 'job-abc.png', jobId: 'job-abc', prompt: 'a cinematic alley', generatedAt: 't' },
+ });
+ });
+
+ it('derives jobId from the filename when the job carries no id', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { writersRoom: tag() }, filename: 'noid.png', id: null }));
+ await waitFor(() => persistSceneImage.mock.calls.length > 0);
+ expect(persistSceneImage.mock.calls[0][2].jobId).toBe('noid');
+ expect(persistSceneImage.mock.calls[0][2].prompt).toBeNull();
+ });
+
+ it('serializes two completions for the same analysis (second awaits the first)', async () => {
+ const order = [];
+ let releaseFirst;
+ const firstGate = new Promise((res) => { releaseFirst = res; });
+ persistSceneImage.mockImplementation(async (workId, analysisId, { sceneId }) => {
+ order.push(`start:${sceneId}`);
+ if (sceneId === 's1') await firstGate;
+ order.push(`end:${sceneId}`);
+ return { analysis: { id: analysisId, sceneImages: { [sceneId]: { filename: 'f' } } }, collectionId: 'c' };
+ });
+ mediaJobEvents.emit('completed', completedImageJob({ params: { writersRoom: tag({ sceneId: 's1' }) }, id: 'a' }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { writersRoom: tag({ sceneId: 's2' }) }, id: 'b' }));
+ // The second must NOT start until the first finishes (same analysis file).
+ await waitFor(() => order.length === 1);
+ expect(order).toEqual(['start:s1']);
+ releaseFirst();
+ await waitFor(() => order.length === 4);
+ expect(order).toEqual(['start:s1', 'end:s1', 'start:s2', 'end:s2']);
+ });
+
+ it('ignores jobs without a writersRoom tag', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { catalogAttach: { ingredientId: 'x' } } }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: {} }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(persistSceneImage).not.toHaveBeenCalled();
+ expect(emitted).toHaveLength(0);
+ });
+
+ it('ignores an incomplete writersRoom tag (missing sceneId)', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { writersRoom: { workId: 'w1', analysisId: 'script' } } }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(persistSceneImage).not.toHaveBeenCalled();
+ });
+
+ it('ignores non-image jobs and jobs with no result filename', async () => {
+ mediaJobEvents.emit('completed', { kind: 'video', id: 'v', params: { writersRoom: tag() }, result: { filename: 'v.mp4' } });
+ mediaJobEvents.emit('completed', { kind: 'image', id: 'i', params: { writersRoom: tag() }, result: {} });
+ await new Promise((r) => setTimeout(r, 30));
+ expect(persistSceneImage).not.toHaveBeenCalled();
+ });
+
+ it('swallows a persist error without rejecting and emits nothing (best-effort)', async () => {
+ persistSceneImage.mockRejectedValueOnce(new Error('disk full'));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { writersRoom: tag() } }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(emitted).toHaveLength(0);
+ });
+});