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(creative-director): seed first-pass scene reference frames after auto-compose

[._.]/ Adam Eivy2b81e0aa28d2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9d65803be6..4477fbabdd 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,6 +15,10 @@
- **[issue-1855] Autonomous shot planner: AI proposes a scene per song section.** A new **AI Plan** button (and `POST /api/music-video/:id/plan`) seeds the director scene board from the analyzed track in one click — one scene per audio section, with each scene's duration set to that section's exact span (energy-aware for free, since the cached sections already come from energy-novelty segmentation: louder, more eventful stretches were already split into more/shorter sections). It also best-effort asks the active AI provider for a first-pass `framePrompt`/shot `prompt` per scene from the project's concept and section context; a missing/disabled provider or an unparsable response degrades gracefully to plain, empty-prompt scenes rather than failing the request. Director-first — every seeded scene is an ordinary, fully-editable board entry, identical to a hand-added one. (Closes #1855)
+## Creative Director
+
+- **[issue-1867] Auto-cast first-pass scene reference frames.** Extends the opt-in first-pass gen step from #1818 (catalog portraits) one stage later: once auto-compose writes a treatment, the director seeds a first reference frame per scene the same way it already seeds cast portraits — one image-gen job per scene, enqueued onto the durable media-job queue and filed onto `scene.sourceImageFile` (the same field a manual reference image or i2v-continuation source already populates) by a new `creativeDirectorSceneImageHook`, so the render lands even with no client mounted. Idempotent (a scene that already has a reference frame is left alone) and only fires for queue-backed image-gen modes (local/Codex), mirroring the portrait path's graceful skip for external mode. The two remaining downstream modalities #1818 named — first-pass scene clips (image-to-video) and a first-pass music bed — are genuinely separate pipelines and are tracked as their own follow-up issues (#1927, #1928) rather than folded into this slice. (`server/services/creativeDirector/firstPassGen.js`, `server/services/creativeDirectorSceneImageHook.js`)
+
## Architecture
- **[issue-1878] CoS runner now wires the process-level `unhandledRejection`/`uncaughtException` net (defense-in-depth).** The main server (`server/index.js`) already registered a process-level net via the shared `setupProcessErrorHandlers()` helper (`server/lib/errorHandler.js`) — but the standalone CoS runner (`server/cos-runner/index.js`), a separate long-lived PM2 process that spawns and supervises child agents, had none, so a stray async handler that rejected/threw outside the request lifecycle would crash it with Node's default unhandled output. The runner now calls the same shared helper, giving it the identical, already-tested convention: log via the emoji-prefixed `console.error` style, log-and-stay-alive on an unhandled rejection, and log-then-exit-cleanly on an uncaught exception (after flushing, so PM2 restarts a process that would otherwise be left in an undefined state and reaps any orphaned agents on boot). Reusing the shared helper (rather than rolling inline handlers) keeps the two long-lived processes consistent and routes arbitrary non-Error throw values through `normalizeError`, so the net can't itself throw on a `reason` with no `.stack`. This is the backstop for the per-handler try/catch wrapping done in #1825 — not a replacement for it. While wiring this up, hardened the shared helper's `uncaughtException` branch, which dereferenced `error.stack` on the raw thrown value — a non-Error throw (`throw null`) made the net itself throw, masking the original exception and skipping the clean exit/flush; it now guards `error instanceof Error` (mirroring the existing `unhandledRejection` branch). A regression test (`server/process-safety-net.test.js`) asserts the shared helper registers both handlers, that both entry processes wire it up, and that the `uncaughtException` listener tolerates a non-Error throw value. (Closes #1878)
diff --git a/server/index.js b/server/index.js
index 337551af20..e097d6d14d 100644
--- a/server/index.js
+++ b/server/index.js
@@ -122,6 +122,7 @@ import { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageH
import { initMusicVideoSceneImageHook } from './services/musicVideoSceneImageHook.js';
import { initMusicVideoSceneVideoHook } from './services/musicVideoSceneVideoHook.js';
import { initCreativeDirectorMusicBedHook } from './services/creativeDirectorMusicBedHook.js';
+import { initCreativeDirectorSceneImageHook } from './services/creativeDirectorSceneImageHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';
@@ -755,6 +756,11 @@ ensureSelf()
// the requesting client unmounted mid-render (#1928). Also depends on the
// queue being loaded.
initCreativeDirectorMusicBedHook();
+ // Creative Director scene-frame hook — durably files a queued first-pass
+ // reference-frame render onto its project scene's `sourceImageFile` on
+ // completion, even if no client is watching (#1867). Also depends on the
+ // queue being loaded.
+ initCreativeDirectorSceneImageHook();
// 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/creativeDirector.js b/server/routes/creativeDirector.js
index dc09598cd3..1cc01f421e 100644
--- a/server/routes/creativeDirector.js
+++ b/server/routes/creativeDirector.js
@@ -28,7 +28,7 @@ import {
updateScene,
} from '../services/creativeDirector/local.js';
import { suggestCastForBrief, applyAutoCastToProject, toSuggestionView } from '../services/creativeDirector/autoCast.js';
-import { enqueueFirstPassPortraits } from '../services/creativeDirector/firstPassGen.js';
+import { enqueueFirstPassPortraits, enqueueFirstPassSceneFrames } from '../services/creativeDirector/firstPassGen.js';
import { enqueueFirstPassMusicBed } from '../services/creativeDirector/firstPassMusicGen.js';
import { startCreativeDirectorProject } from '../services/creativeDirector/completionHook.js';
import { createSmokeTestProject } from '../services/creativeDirector/smokeTest.js';
@@ -121,6 +121,16 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
const composing = Boolean(compose) && composable && Array.isArray(cast) && cast.length > 0 && !project.treatment;
if (composing) {
startCreativeDirectorProject(req.params.id).catch((e) => console.log(`⚠️ CD auto-compose failed: ${e.message}`));
+ // Scene reference frames (#1867) depend on a treatment existing, which
+ // auto-compose only writes asynchronously above. Persist the user's
+ // opt-in on the project record so the `/:id/treatment` handler (where the
+ // agent's scene plan actually lands) knows to also seed first-pass frames
+ // — there is no other durable hand-off point between this request and
+ // that later write.
+ if (generateFirstPass) {
+ updateProject(req.params.id, { generateFirstPass: true })
+ .catch((e) => console.log(`⚠️ CD persist generateFirstPass flag failed: ${e.message}`));
+ }
}
// First-pass gen (#1818): when opted in, kick off a catalog portrait render
// for each member auto-cast just added that has no portrait yet. The renders
@@ -162,6 +172,16 @@ router.post('/:id/auto-cast', asyncHandler(async (req, res) => {
router.patch('/:id/treatment', asyncHandler(async (req, res) => {
const treatment = validateRequest(creativeDirectorTreatmentSchema, req.body);
const updated = await setTreatment(req.params.id, treatment);
+ // Scene reference frames (#1867): the user opted into first-pass gen back
+ // at auto-cast time (persisted as `generateFirstPass` on the project since
+ // the treatment lands asynchronously, possibly much later). Now that a
+ // scene plan exists, seed a first reference frame per scene the same way
+ // first-pass portraits are seeded — fire-and-forget like auto-compose
+ // above; the response shouldn't block on render-queue work.
+ if (updated?.generateFirstPass) {
+ enqueueFirstPassSceneFrames(updated)
+ .catch((e) => console.log(`⚠️ CD first-pass scene frames failed: ${e.message}`));
+ }
res.json(updated);
}));
diff --git a/server/routes/creativeDirector.test.js b/server/routes/creativeDirector.test.js
index 5cc0a2a84a..cff43704a3 100644
--- a/server/routes/creativeDirector.test.js
+++ b/server/routes/creativeDirector.test.js
@@ -25,10 +25,12 @@ vi.mock('../services/creativeDirector/autoCast.js', () => ({
toSuggestionView: (hit) => ({ ingredientId: hit.ingredient.id, name: hit.ingredient.name, type: hit.ingredient.type, score: hit.rrfScore, searchMethod: hit.searchMethod }),
}));
-// Mock first-pass gen (#1818) so the route test doesn't pull the real
-// mediaJobQueue/catalogDB graph; the route's job is to gate + dispatch.
+// Mock first-pass gen (#1818, extended by #1867) so the route test doesn't
+// pull the real mediaJobQueue/catalogDB graph; the route's job is to gate +
+// dispatch.
vi.mock('../services/creativeDirector/firstPassGen.js', () => ({
enqueueFirstPassPortraits: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),
+ enqueueFirstPassSceneFrames: vi.fn(async () => ({ mode: 'local', enqueued: [], skipped: [] })),
}));
// Mock first-pass music-bed gen (#1928) so the route test doesn't pull the
@@ -156,22 +158,38 @@ describe('creativeDirector routes', () => {
});
describe('PATCH /:id/treatment', () => {
+ const treatmentBody = {
+ logline: 'A cat finds a hat.',
+ synopsis: 'Then puts it on.',
+ scenes: [{
+ sceneId: 'scene-1',
+ order: 0,
+ intent: 'Cat enters frame',
+ prompt: 'A cat walks into view',
+ durationSeconds: 4,
+ }],
+ };
+
it('writes the treatment when shape is valid', async () => {
cdService.setTreatment.mockResolvedValue({ id: 'cd-1', treatment: { scenes: [] } });
- const r = await request(app).patch('/api/creative-director/cd-1/treatment').send({
- logline: 'A cat finds a hat.',
- synopsis: 'Then puts it on.',
- scenes: [{
- sceneId: 'scene-1',
- order: 0,
- intent: 'Cat enters frame',
- prompt: 'A cat walks into view',
- durationSeconds: 4,
- }],
- });
+ const r = await request(app).patch('/api/creative-director/cd-1/treatment').send(treatmentBody);
expect(r.status).toBe(200);
expect(cdService.setTreatment).toHaveBeenCalled();
});
+
+ it('seeds first-pass scene frames when the project opted in (#1867)', async () => {
+ cdService.setTreatment.mockResolvedValue({ id: 'cd-1', generateFirstPass: true, treatment: { scenes: [] } });
+ const r = await request(app).patch('/api/creative-director/cd-1/treatment').send(treatmentBody);
+ expect(r.status).toBe(200);
+ expect(firstPass.enqueueFirstPassSceneFrames).toHaveBeenCalledWith({ id: 'cd-1', generateFirstPass: true, treatment: { scenes: [] } });
+ });
+
+ it('does not seed first-pass scene frames when the project never opted in', async () => {
+ cdService.setTreatment.mockResolvedValue({ id: 'cd-1', treatment: { scenes: [] } });
+ const r = await request(app).patch('/api/creative-director/cd-1/treatment').send(treatmentBody);
+ expect(r.status).toBe(200);
+ expect(firstPass.enqueueFirstPassSceneFrames).not.toHaveBeenCalled();
+ });
});
describe('POST /:id/start', () => {
@@ -363,6 +381,24 @@ describe('creativeDirector routes', () => {
expect(r.body.composing).toBe(false);
expect(hook.startCreativeDirectorProject).not.toHaveBeenCalled();
});
+
+ it('persists generateFirstPass on the project when composing with the flag set (#1867)', async () => {
+ autoCast.applyAutoCastToProject.mockResolvedValue({
+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],
+ });
+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ compose: true, generateFirstPass: true });
+ expect(r.status).toBe(200);
+ expect(cdService.updateProject).toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
+ });
+
+ it('does not persist generateFirstPass when not composing', async () => {
+ autoCast.applyAutoCastToProject.mockResolvedValue({
+ project: { id: 'cd-1', cast: [{ ingredientId: 'p1' }] }, added: [{ ingredientId: 'p1' }], suggestions: [],
+ });
+ const r = await request(app).post('/api/creative-director/cd-1/auto-cast').send({ generateFirstPass: true });
+ expect(r.status).toBe(200);
+ expect(cdService.updateProject).not.toHaveBeenCalledWith('cd-1', { generateFirstPass: true });
+ });
});
describe('POST /:id/auto-cast — first-pass gen (#1818)', () => {
diff --git a/server/services/creativeDirector/firstPassGen.js b/server/services/creativeDirector/firstPassGen.js
index 4ebc27c275..5d3174401e 100644
--- a/server/services/creativeDirector/firstPassGen.js
+++ b/server/services/creativeDirector/firstPassGen.js
@@ -1,5 +1,5 @@
/**
- * Creative Director — first-pass asset generation (#1818).
+ * Creative Director — first-pass asset generation (#1818, extended by #1867).
*
* Follow-up to the Auto-cast MVP (#1810) and auto-compose (#1817). When the
* autonomous path seeds a project's cast from the catalog, an opt-in
@@ -7,6 +7,13 @@
* each freshly-cast member that has no portrait yet — so the cast "arrives
* on-model" without the user hand-rendering each ingredient.
*
+ * #1867 extends the same opt-in step one stage later: once auto-compose has
+ * written a treatment (a scene plan exists), `enqueueFirstPassSceneFrames`
+ * seeds a first reference frame per scene the same way portraits are seeded.
+ * The other two downstream modalities #1818 named (scene clips / i2v, music
+ * bed) are genuinely separate pipelines and are tracked as their own issues
+ * rather than folded in here.
+ *
* Reuse, not a new pipeline (the issue's explicit constraint). Each render is
* an ordinary image-gen job enqueued onto the SAME mediaJobQueue with the same
* `catalogAttach` tag the manual portrait path uses (#1359), so the durable
@@ -56,8 +63,11 @@ export function buildPortraitPrompt(ingredient) {
* (external mode, codex disabled). Reads settings the same way the imageGen
* route + universeBuilderRender do, so the cleanC2PA / denoise cleaners apply
* to first-pass renders exactly like a manual portrait render.
+ *
+ * Exported so `enqueueFirstPassSceneFrames` (#1867) shares the exact same
+ * queue-backed-mode gate as the portrait path rather than re-deriving it.
*/
-async function resolveQueueModeParams() {
+export async function resolveQueueModeParams() {
const settings = await getSettings();
const mode = settings.imageGen?.mode || IMAGE_GEN_MODE.EXTERNAL;
if (mode === IMAGE_GEN_MODE.CODEX) {
@@ -159,3 +169,63 @@ export async function enqueueFirstPassPortraits(members = []) {
console.log(`🎨 CD first-pass portraits: ${enqueued.length} queued, ${skipped.length} skipped (${resolved.mode})`);
return { mode: resolved.mode, enqueued, skipped };
}
+
+/**
+ * Enqueue first-pass scene reference-frame renders for a project's treatment
+ * (#1867 — the first slice of #1818's deferred "extend beyond portraits"
+ * follow-up). Once auto-compose (#1817) has written a scene plan, seed an
+ * on-model reference frame per scene the same way `enqueueFirstPassPortraits`
+ * seeds cast portraits: one image-gen job per scene tagged for the durable
+ * `creativeDirectorSceneImageHook`, which files the finished render onto
+ * `scene.sourceImageFile` — the SAME field a manually-set reference image or
+ * an i2v-continuation source already populates (sceneRunner.js reads it as
+ * the render's source image), so first-pass gen fills the gap rather than
+ * adding a parallel field.
+ *
+ * Director-first + idempotent: a scene that already carries a
+ * `sourceImageFile` (set by hand, a prior first-pass run, or the agent
+ * itself) is left alone. Best-effort and self-contained — a single scene
+ * missing a prompt is recorded in `skipped`, never thrown, since this runs as
+ * a side effect of writing the treatment and must not fail that write.
+ *
+ * Returns `{ mode, enqueued: [{ sceneId, jobId }], skipped: [{ sceneId, reason }], reason? }`.
+ */
+export async function enqueueFirstPassSceneFrames(project) {
+ const scenes = Array.isArray(project?.treatment?.scenes) ? project.treatment.scenes : [];
+ if (scenes.length === 0) return { mode: null, enqueued: [], skipped: [] };
+
+ const resolved = await resolveQueueModeParams();
+ if (!resolved.ready) {
+ return { mode: resolved.mode, enqueued: [], skipped: [], reason: resolved.reason };
+ }
+
+ const enqueued = [];
+ const skipped = [];
+ for (const scene of scenes) {
+ if (!scene?.sceneId) continue;
+ if (scene.sourceImageFile) {
+ skipped.push({ sceneId: scene.sceneId, reason: 'has-reference' });
+ continue;
+ }
+ const prompt = typeof scene.prompt === 'string' ? scene.prompt.trim() : '';
+ if (!prompt) {
+ skipped.push({ sceneId: scene.sceneId, reason: 'no-prompt' });
+ continue;
+ }
+ const queued = enqueueJob({
+ kind: 'image',
+ params: {
+ ...resolved.jobParams,
+ prompt,
+ // Tag the job so the durable creativeDirectorSceneImageHook files the
+ // finished render onto this scene's sourceImageFile — no mounted
+ // client required. Mirrors the catalogAttach tag the portrait path
+ // uses for the catalog hook.
+ creativeDirector: { projectId: project.id, sceneId: scene.sceneId },
+ },
+ });
+ enqueued.push({ sceneId: scene.sceneId, jobId: queued.jobId });
+ }
+ console.log(`🎬 CD first-pass scene frames: ${enqueued.length} queued, ${skipped.length} skipped (${resolved.mode})`);
+ return { mode: resolved.mode, enqueued, skipped };
+}
diff --git a/server/services/creativeDirector/firstPassGen.test.js b/server/services/creativeDirector/firstPassGen.test.js
index 7ed396cd05..b4894f3a4b 100644
--- a/server/services/creativeDirector/firstPassGen.test.js
+++ b/server/services/creativeDirector/firstPassGen.test.js
@@ -16,7 +16,7 @@ vi.mock('../catalogDB.js', () => ({
listMediaForIngredient: vi.fn(),
}));
-import { buildPortraitPrompt, enqueueFirstPassPortraits } from './firstPassGen.js';
+import { buildPortraitPrompt, enqueueFirstPassPortraits, enqueueFirstPassSceneFrames } from './firstPassGen.js';
import { enqueueJob } from '../mediaJobQueue/index.js';
import { getSettings } from '../settings.js';
import { getIngredient, listMediaForIngredient } from '../catalogDB.js';
@@ -149,3 +149,58 @@ describe('enqueueFirstPassPortraits', () => {
expect(out.enqueued).toEqual([{ ingredientId: 'a', jobId: 'job-1' }]);
});
});
+
+describe('enqueueFirstPassSceneFrames (#1867)', () => {
+ const scene = (over = {}) => ({
+ sceneId: 's1', order: 0, intent: 'x', prompt: 'a cat walks into a noir alley',
+ durationSeconds: 4, status: 'pending', ...over,
+ });
+
+ it('enqueues a creativeDirector-tagged job per scene lacking a reference frame', async () => {
+ const project = { id: 'cd-1', treatment: { scenes: [scene({ sceneId: 's1' }), scene({ sceneId: 's2' })] } };
+ const out = await enqueueFirstPassSceneFrames(project);
+ expect(out.mode).toBe('local');
+ expect(out.enqueued).toEqual([
+ { sceneId: 's1', jobId: 'job-1' },
+ { sceneId: 's2', jobId: 'job-2' },
+ ]);
+ expect(out.skipped).toEqual([]);
+ const firstJob = enqueueJob.mock.calls[0][0];
+ expect(firstJob.kind).toBe('image');
+ expect(firstJob.params.creativeDirector).toEqual({ projectId: 'cd-1', sceneId: 's1' });
+ expect(firstJob.params.prompt).toBe('a cat walks into a noir alley');
+ expect(firstJob.params.pythonPath).toBe('/py');
+ });
+
+ it('skips a scene that already has a reference frame (idempotent re-run)', async () => {
+ const project = {
+ id: 'cd-1',
+ treatment: { scenes: [scene({ sceneId: 's1', sourceImageFile: 'existing.png' }), scene({ sceneId: 's2' })] },
+ };
+ const out = await enqueueFirstPassSceneFrames(project);
+ expect(out.enqueued).toEqual([{ sceneId: 's2', jobId: 'job-1' }]);
+ expect(out.skipped).toEqual([{ sceneId: 's1', reason: 'has-reference' }]);
+ expect(enqueueJob).toHaveBeenCalledTimes(1);
+ });
+
+ it('skips a scene with a blank prompt', async () => {
+ const project = { id: 'cd-1', treatment: { scenes: [scene({ sceneId: 's1', prompt: ' ' })] } };
+ const out = await enqueueFirstPassSceneFrames(project);
+ expect(out.enqueued).toEqual([]);
+ expect(out.skipped).toEqual([{ sceneId: 's1', reason: 'no-prompt' }]);
+ });
+
+ it('skips gracefully for external mode (not queue-backed)', async () => {
+ getSettings.mockResolvedValue({ imageGen: { mode: 'external' } });
+ const project = { id: 'cd-1', treatment: { scenes: [scene()] } };
+ const out = await enqueueFirstPassSceneFrames(project);
+ expect(out).toEqual({ mode: 'external', enqueued: [], skipped: [], reason: 'mode-unsupported' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+
+ it('returns an empty summary for no treatment / no scenes (never reads settings)', async () => {
+ expect(await enqueueFirstPassSceneFrames({ id: 'cd-1', treatment: null })).toEqual({ mode: null, enqueued: [], skipped: [] });
+ expect(await enqueueFirstPassSceneFrames({ id: 'cd-1', treatment: { scenes: [] } })).toEqual({ mode: null, enqueued: [], skipped: [] });
+ expect(getSettings).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/creativeDirector/projectsLogic.js b/server/services/creativeDirector/projectsLogic.js
index 3de09c1af7..515d7315ca 100644
--- a/server/services/creativeDirector/projectsLogic.js
+++ b/server/services/creativeDirector/projectsLogic.js
@@ -86,7 +86,7 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
name, aspectRatio, quality, modelId, targetDurationSeconds,
styleSpec = '', startingImageFile = null, userStory = null,
disableAudio = true, autoAcceptScenes = false, sourceIssueId = null,
- cast = [],
+ cast = [], generateFirstPass = false,
} = input;
return {
id,
@@ -109,6 +109,13 @@ export function buildProjectRecord(input, { id, now, collectionId }) {
cast: Array.isArray(cast) ? cast : [],
disableAudio,
autoAcceptScenes,
+ // Server-managed intent flag (#1867) — set on the project by the
+ // auto-cast route when a user opts into both `compose` and
+ // `generateFirstPass`, since the actual scene-frame seeding can only run
+ // once the treatment lands (asynchronously, after this record is
+ // created). Not part of the public create/update schema; see
+ // creativeDirector.js's `/:id/auto-cast` and `/:id/treatment` handlers.
+ generateFirstPass,
// Optional back-pointer to the pipeline issue that spawned this project.
// The stitch step uses it to look up `stages.audio.music` and mix it into
// the final cut. Bare CD projects leave this null and skip the audio-mux.
diff --git a/server/services/creativeDirectorSceneImageHook.js b/server/services/creativeDirectorSceneImageHook.js
new file mode 100644
index 0000000000..fba2019a16
--- /dev/null
+++ b/server/services/creativeDirectorSceneImageHook.js
@@ -0,0 +1,67 @@
+/**
+ * Creative Director scene reference-frame attach hook (#1867).
+ *
+ * Subscribes to mediaJobEvents and, for each completed image job that
+ * carries `params.creativeDirector`, files the rendered filename onto that
+ * project scene's `sourceImageFile` — server-side, independent of any
+ * mounted client. This is the durable attach counterpart to the job
+ * `firstPassGen.js`'s `enqueueFirstPassSceneFrames` enqueues: a fire-and-
+ * forget seed render queued right after the director writes a treatment,
+ * landing even if no client is watching.
+ *
+ * `sourceImageFile` is the SAME field a manually-set per-scene reference
+ * image or an i2v-continuation source already populates (sceneRunner.js
+ * reads it as the render's source image when `useContinuationFromPrior` is
+ * false) — first-pass gen fills the gap, it does not add a parallel field.
+ *
+ * Only the async local/Codex lanes ride the media-job queue this hook
+ * listens to; `resolveQueueModeParams` in firstPassGen.js never queues an
+ * external-mode render in the first place, so this hook only ever sees
+ * local/Codex completions.
+ *
+ * `updateScene` routes through the project store dispatcher (local.js),
+ * which emits a `creativeDirectorProject` record-updated event on every
+ * call — the new `sourceImageFile` propagates to subscribed sync peers
+ * exactly like a hand edit.
+ *
+ * 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 Creative-Director-specific config. Mounted once at server
+ * boot from server/index.js (after the media job queue is running).
+ */
+
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
+import { updateScene } from './creativeDirector/local.js';
+
+const hook = createMediaJobImageHook({
+ label: 'creative-director scene-frame',
+ initLog: '🎬 Creative Director scene-frame hook initialized',
+ tagKey: 'creativeDirector',
+ // 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-frame renders for the same project
+ // completing close together would otherwise both load→modify→save the one
+ // project record and the later write could clobber the earlier scene's
+ // sourceImageFile. Different projects still attach concurrently.
+ serializeKey: ({ projectId }) => projectId,
+ // Newest-render-wins per scene: a render kicked off from another client (or
+ // a re-queued retry) can complete out of order — drop an older render so
+ // it can't overwrite a newer reference frame.
+ sceneKey: ({ projectId, sceneId }) => `${projectId}:${sceneId}`,
+ describe: ({ projectId, sceneId }) => `${projectId}/${sceneId}`,
+ attach: ({ projectId, sceneId, filename }) =>
+ updateScene(projectId, sceneId, { sourceImageFile: filename }),
+ onAttached: ({ projectId, sceneId, filename }) => {
+ console.log(`🎬 CD scene reference frame ${projectId.slice(0, 8)}/${sceneId} ← ${filename}`);
+ },
+});
+
+export function initCreativeDirectorSceneImageHook() {
+ hook.init();
+}
+
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;
diff --git a/server/services/creativeDirectorSceneImageHook.test.js b/server/services/creativeDirectorSceneImageHook.test.js
new file mode 100644
index 0000000000..d03c0a41c3
--- /dev/null
+++ b/server/services/creativeDirectorSceneImageHook.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+// Mock the project store so the hook's tag-decode + serialize logic is
+// exercised without touching disk or a DB. `updateScene` is reprogrammed
+// per-test to stand in for the durable attach.
+const updateScene = vi.fn(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));
+vi.mock('./creativeDirector/local.js', () => ({ updateScene }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const hook = await import('./creativeDirectorSceneImageHook.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 = {}) => ({ projectId: 'cd-1', sceneId: 'scene-1', ...over });
+const completedImageJob = ({ params = {}, filename = 'job-abc.png', id = 'job-abc', queuedAt } = {}) => ({
+ kind: 'image', id, params, result: { filename }, ...(queuedAt ? { queuedAt } : {}),
+});
+
+describe('creativeDirectorSceneImageHook', () => {
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initCreativeDirectorSceneImageHook();
+ updateScene.mockReset();
+ updateScene.mockImplementation(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));
+ });
+
+ afterEach(() => {
+ hook.__testing.reset();
+ });
+
+ it('attaches the rendered filename to sourceImageFile for a creativeDirector-tagged job', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({
+ params: { creativeDirector: tag(), prompt: 'a cat walks into a noir alley' },
+ filename: 'job-abc.png', id: 'job-abc',
+ }));
+ await waitFor(() => updateScene.mock.calls.length > 0);
+ expect(updateScene).toHaveBeenCalledWith('cd-1', 'scene-1', { sourceImageFile: 'job-abc.png' });
+ });
+
+ it('ignores a completed job with no creativeDirector tag', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({
+ params: { musicVideo: { projectId: 'mv-1', sceneId: 'mvs-1' } },
+ }));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ });
+
+ it('ignores a non-image job kind', async () => {
+ mediaJobEvents.emit('completed', { kind: 'video', id: 'v1', params: { creativeDirector: tag() }, result: { filename: 'v1.mp4' } });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ });
+
+ it('skips a tag missing projectId or sceneId', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({ params: { creativeDirector: { projectId: 'cd-1' } } }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { creativeDirector: { sceneId: 'scene-1' } } }));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ });
+
+ it('does not throw when the attach fails — project/scene deleted mid-render', async () => {
+ updateScene.mockRejectedValueOnce(Object.assign(new Error('Project not found'), { status: 404 }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { creativeDirector: tag() } }));
+ await waitFor(() => updateScene.mock.calls.length > 0);
+ // No further assertions needed — a thrown rejection inside the hook would
+ // surface as an unhandled rejection and fail the test run.
+ await new Promise((r) => setTimeout(r, 20));
+ });
+
+ it('does not let an older render (earlier queuedAt) overwrite a newer frame on the same scene', async () => {
+ mediaJobEvents.emit('completed', completedImageJob({
+ params: { creativeDirector: tag() }, filename: 'new.png', id: 'b', queuedAt: '2026-06-29T00:00:02.000Z',
+ }));
+ await waitFor(() => updateScene.mock.calls.length > 0);
+ mediaJobEvents.emit('completed', completedImageJob({
+ params: { creativeDirector: tag() }, filename: 'old.png', id: 'a', queuedAt: '2026-06-29T00:00:01.000Z',
+ }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(updateScene).toHaveBeenCalledTimes(1);
+ expect(updateScene).toHaveBeenCalledWith('cd-1', 'scene-1', { sourceImageFile: 'new.png' });
+ });
+
+ it('serializes attaches for the same project so concurrent renders do not clobber', async () => {
+ const order = [];
+ let resolveFirst;
+ updateScene
+ .mockImplementationOnce(() => new Promise((resolve) => {
+ order.push('start-1');
+ resolveFirst = () => { order.push('end-1'); resolve({ sourceImageFile: 'a.png' }); };
+ }))
+ .mockImplementationOnce(async () => { order.push('start-2'); return { sourceImageFile: 'b.png' }; });
+
+ mediaJobEvents.emit('completed', completedImageJob({ params: { creativeDirector: tag({ sceneId: 'scene-1' }) }, filename: 'a.png', id: 'a' }));
+ mediaJobEvents.emit('completed', completedImageJob({ params: { creativeDirector: tag({ sceneId: 'scene-2' }) }, filename: 'b.png', id: 'b' }));
+
+ await waitFor(() => order.includes('start-1'));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(order).toEqual(['start-1']);
+ resolveFirst();
+ await waitFor(() => order.includes('start-2'));
+ expect(order).toEqual(['start-1', 'end-1', 'start-2']);
+ });
+});