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([issue-1760]): generate a scene's video from its reference frame via i2v (Phase 1)

[._.]/ Adam Eivyf5f487ca5e7f
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index f2f7e450e7..b418fbef83 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, useCallback } from 'react';
-import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon } from 'lucide-react';
+import { Plus, Film, Trash2, Music, Activity, ArrowUp, ArrowDown, Image as ImageIcon, Video } from 'lucide-react';
import toast from '../components/ui/Toast';
import PageHeader from '../components/PageHeader';
import {
@@ -13,6 +13,7 @@ import {
reorderMusicVideoScenes,
} from '../services/apiMusicVideo.js';
import { generateImage } from '../services/apiSystem.js';
+import { generateVideo } from '../services/apiImageVideo.js';
import { listTracks } from '../services/apiTracks.js';
import { getMediaJob } from '../services/apiMediaJobs.js';
import socket from '../services/socket.js';
@@ -55,6 +56,14 @@ export default function MusicVideo() {
// (jobId → failed) so the terminal events of unrelated image-gen jobs across the
// app can't grow it unbounded; the kickoff reconciles its own entry on arrival.
const orphanTerminalsRef = useRef(new Map());
+ // Per-scene i2v video generation (#1760 Phase 1): sceneId → true while a scene
+ // clip is rendering. Video renders always ride the media-job queue (no
+ // synchronous lane), so the spinner is cleared by the job-id-correlated
+ // video-gen:completed/failed events and the clip lands durably via
+ // music-video:scene-video — the direct analog of the reference-frame refs above.
+ const [genVideoScenes, setGenVideoScenes] = useState({});
+ const pendingVideoJobsRef = useRef(new Map());
+ const orphanVideoTerminalsRef = useRef(new Map());
const selected = projects.find((p) => p.id === selectedId) || null;
const replaceProject = (next) => setProjects((prev) => prev.map((p) => (p.id === next.id ? next : p)));
@@ -67,6 +76,13 @@ export default function MusicVideo() {
setProjects((prev) => prev.map((p) => (p.id === projectId
? { ...p, scenes: (p.scenes || []).map((s) => (s.sceneId === sceneId ? { ...s, referenceImageId } : s)) }
: p)));
+ const clearGenVideo = (sceneId) => setGenVideoScenes((prev) => { const next = { ...prev }; delete next[sceneId]; return next; });
+ // Merge ONLY a scene's videoHistoryId via a functional update (same stale-
+ // snapshot guard as applyReferenceImage above).
+ const applySceneVideo = (projectId, sceneId, videoHistoryId) =>
+ setProjects((prev) => prev.map((p) => (p.id === projectId
+ ? { ...p, scenes: (p.scenes || []).map((s) => (s.sceneId === sceneId ? { ...s, videoHistoryId } : s)) }
+ : p)));
// Socket lifecycle for async (local/Codex) reference-frame renders (#1760
// Phase 1b). Three events, all broadcast to every client:
@@ -163,6 +179,68 @@ export default function MusicVideo() {
};
}, []);
+ // Socket lifecycle for async i2v scene-clip renders (#1760 Phase 1). Mirrors
+ // the reference-frame effect above, for video:
+ // - music-video:scene-video — durable attach filed by musicVideoSceneVideoHook;
+ // fold videoHistoryId onto the matching scene without a refetch, even for a
+ // project that isn't selected. Does NOT touch the spinner.
+ // - video-gen:completed / video-gen:failed — the job's terminal events; clear
+ // the spinner by correlating generationId → sceneId. There is no
+ // video-gen:canceled bridge, so a running-cancel surfaces as :failed for an
+ // owned job; the deferred toast re-polls the job and stays silent when it
+ // resolved to 'canceled' (same disambiguation the image lane uses).
+ useEffect(() => {
+ const onSceneVideo = ({ projectId, sceneId, videoHistoryId }) => {
+ applySceneVideo(projectId, sceneId, videoHistoryId);
+ };
+ const failTimers = new Map();
+ const settle = (data, failed) => {
+ const jobId = data?.generationId || data?.jobId;
+ if (!jobId) return;
+ const sceneId = pendingVideoJobsRef.current.get(jobId);
+ if (!sceneId) {
+ const orphans = orphanVideoTerminalsRef.current;
+ orphans.set(jobId, !!failed);
+ if (orphans.size > 64) orphans.delete(orphans.keys().next().value);
+ return;
+ }
+ pendingVideoJobsRef.current.delete(jobId);
+ clearGenVideo(sceneId);
+ if (failed) toast.error('Scene video render failed');
+ };
+ const onCompleted = (data) => settle(data, false);
+ const armFailToast = (jobId, attempt = 0) => {
+ failTimers.set(jobId, setTimeout(() => {
+ failTimers.delete(jobId);
+ getMediaJob(jobId)
+ .then((job) => {
+ const status = job?.status;
+ if (status === 'canceled') return; // user cancel — never a failure toast
+ if (status === 'failed' || status === 'error') { toast.error('Scene video render failed'); return; }
+ if (attempt < 2) armFailToast(jobId, attempt + 1); // non-terminal: wait, don't toast yet
+ })
+ .catch(() => toast.error('Scene video render failed'));
+ }, 800));
+ };
+ const onFailed = (data) => {
+ const jobId = data?.generationId || data?.jobId;
+ if (!jobId) return;
+ const owned = pendingVideoJobsRef.current.has(jobId);
+ settle(data, !owned);
+ if (owned && !failTimers.has(jobId)) armFailToast(jobId);
+ };
+ socket.on('music-video:scene-video', onSceneVideo);
+ socket.on('video-gen:completed', onCompleted);
+ socket.on('video-gen:failed', onFailed);
+ return () => {
+ socket.off('music-video:scene-video', onSceneVideo);
+ socket.off('video-gen:completed', onCompleted);
+ socket.off('video-gen:failed', onFailed);
+ for (const t of failTimers.values()) clearTimeout(t);
+ failTimers.clear();
+ };
+ }, []);
+
useEffect(() => {
listMusicVideoProjects()
.then((data) => { setProjects(data || []); setLoading(false); })
@@ -287,6 +365,51 @@ export default function MusicVideo() {
});
};
+ // The i2v prompt for a scene's clip: its shot prompt (or the frame prompt as a
+ // fallback) suffixed with the project's global concept style. The reference
+ // frame already fixes the look; this prompt guides the motion.
+ const buildShotPrompt = (scene) => {
+ const base = (scene.prompt?.trim() || scene.framePrompt?.trim() || '');
+ const style = selected?.concept?.style?.trim();
+ return [base, style].filter(Boolean).join(', ');
+ };
+
+ // Generate this scene's video from its chosen reference frame via the video
+ // route's image (i2v) mode. The render always rides the media-job queue, so we
+ // correlate the returned job id and let the terminal video-gen:completed/failed
+ // event clear the spinner; the finished clip's history id lands durably via
+ // music-video:scene-video (musicVideoSceneVideoHook). generateVideo() throws on
+ // a non-OK response, so the catch owns the only error toast (no double-toast).
+ const handleGenerateVideo = (scene) => {
+ if (!scene.referenceImageId) { toast.error('Generate a reference frame first'); return; }
+ const prompt = buildShotPrompt(scene);
+ if (!prompt) { toast.error('Add a shot prompt first'); return; }
+ setGenVideoScenes((prev) => ({ ...prev, [scene.sceneId]: true }));
+ generateVideo({
+ prompt,
+ mode: 'image',
+ sourceImageFile: scene.referenceImageId,
+ musicVideo: JSON.stringify({ projectId: selected.id, sceneId: scene.sceneId }),
+ })
+ .then((res) => {
+ const jobId = res?.jobId || res?.generationId;
+ if (!jobId) { clearGenVideo(scene.sceneId); return; } // no id to track → don't strand the button
+ // The terminal event may have raced ahead of this .then — reconcile it now.
+ if (orphanVideoTerminalsRef.current.has(jobId)) {
+ const failed = orphanVideoTerminalsRef.current.get(jobId);
+ orphanVideoTerminalsRef.current.delete(jobId);
+ clearGenVideo(scene.sceneId);
+ if (failed) toast.error('Scene video render failed');
+ return;
+ }
+ pendingVideoJobsRef.current.set(jobId, scene.sceneId);
+ })
+ .catch((err) => {
+ toast.error(err?.message || 'Scene video generation failed');
+ clearGenVideo(scene.sceneId);
+ });
+ };
+
return (
<div className="space-y-4">
<PageHeader icon={Film} title="Music Video" subtitle="Director-controlled, beat-aware music videos" />
@@ -429,6 +552,21 @@ export default function MusicVideo() {
</button>
</div>
</div>
+ {/* Scene clip — i2v video generated from the reference frame (Phase 1) */}
+ <div className="flex items-center gap-2 flex-wrap">
+ {scene.videoHistoryId && (
+ <video src={`/data/videos/${scene.videoHistoryId}.mp4`}
+ className="w-28 h-16 object-cover rounded border border-port-border bg-black"
+ muted playsInline preload="metadata" controls />
+ )}
+ <button onClick={() => handleGenerateVideo(scene)}
+ disabled={!scene.referenceImageId || !!genVideoScenes[scene.sceneId]}
+ className="flex items-center gap-1 bg-port-border hover:bg-port-border/70 disabled:opacity-50 rounded px-2 py-1.5 text-xs min-h-[40px] sm:min-h-0 whitespace-nowrap"
+ title={scene.referenceImageId ? "Generate this scene's video from its reference frame (i2v)" : 'Generate a reference frame first'}>
+ {genVideoScenes[scene.sceneId] ? <Activity size={14} className="animate-spin" /> : <Video size={14} />}
+ {genVideoScenes[scene.sceneId] ? 'Rendering…' : (scene.videoHistoryId ? 'Regenerate video' : 'Generate video')}
+ </button>
+ </div>
</div>
))}
</div>
diff --git a/server/index.js b/server/index.js
index d54e619687..b14a746add 100644
--- a/server/index.js
+++ b/server/index.js
@@ -120,6 +120,7 @@ import { initUniverseBuilderCollectionHook } from './services/universeBuilderCol
import { initCatalogImageAttachHook } from './services/catalogImageAttachHook.js';
import { initWritersRoomSceneImageHook } from './services/writersRoomSceneImageHook.js';
import { initMusicVideoSceneImageHook } from './services/musicVideoSceneImageHook.js';
+import { initMusicVideoSceneVideoHook } from './services/musicVideoSceneVideoHook.js';
import { initComicPagesFilenameHook } from './services/pipeline/comicPagesFilenameHook.js';
import { initStoryboardsFilenameHook } from './services/pipeline/storyboardsFilenameHook.js';
import { initSeasonCoverFilenameHook } from './services/pipeline/seasonCoverFilenameHook.js';
@@ -810,6 +811,11 @@ ensureSelf()
// the director board unmounted mid-render (#1760 Phase 1b). Also depends on
// the queue being loaded.
initMusicVideoSceneImageHook();
+ // Music Video scene-video hook — durably files a queued i2v scene clip onto
+ // its project scene's `videoHistoryId` on completion, even if the director
+ // board unmounted mid-render (#1760 Phase 1). Also depends on the queue
+ // being loaded.
+ initMusicVideoSceneVideoHook();
// 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/videoGen.js b/server/routes/videoGen.js
index 9d76ad1355..92699c0d52 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -175,6 +175,28 @@ const generateBodySchema = z.object({
},
z.array(z.number().min(0).max(2)).max(8).optional(),
),
+ // Music Video director-board i2v render (#1760 Phase 1). When present, the
+ // mediaJobQueue completion hook (`musicVideoSceneVideoHook`) files the finished
+ // clip's history id onto the project scene's `videoHistoryId` — durably, even
+ // if the director board unmounted mid-render (the i2v counterpart to the
+ // Phase 1b reference-frame `musicVideo` tag on the image route). The shot
+ // prompt rides in `prompt` and the reference frame in `sourceImageFile`, so
+ // the tag carries only the destination identity. The video route always sends
+ // multipart, so the object arrives as a JSON string — preprocess-parse it
+ // before the schema sees it (mirrors `keyframes` above).
+ musicVideo: z.preprocess(
+ (v) => {
+ if (v == null || v === '') return undefined;
+ if (typeof v === 'string') {
+ try { return JSON.parse(v); } catch { return v; }
+ }
+ return v;
+ },
+ z.object({
+ projectId: z.string().min(1).max(200),
+ sceneId: z.string().min(1).max(200),
+ }).optional(),
+ ),
});
// Probes required-package imports on each call so a half-installed Python
@@ -856,6 +878,10 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
imageStrength: body.imageStrength,
chunks: effectiveChunks,
loras,
+ // Director-board attach tag (#1760 Phase 1). Rides into persisted
+ // job.params so the completion hook can file the clip onto the scene even
+ // if the board unmounted; absent for ordinary VideoGen-page renders.
+ ...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),
},
});
// Match the legacy response shape (jobId, generationId, filename, model,
diff --git a/server/services/musicVideo/events.js b/server/services/musicVideo/events.js
index 9fcb964fb3..67fd78e820 100644
--- a/server/services/musicVideo/events.js
+++ b/server/services/musicVideo/events.js
@@ -1,15 +1,18 @@
import { EventEmitter } from 'events';
// Event bus for Music Video async side effects that need to reach the client
-// after the originating HTTP request has returned. Today it carries one event:
+// after the originating HTTP request has returned. It carries two events:
//
// 'scene-image' → { projectId, sceneId, referenceImageId }
+// 'scene-video' → { projectId, sceneId, videoHistoryId }
//
-// emitted by `musicVideoSceneImageHook` once an async (local/Codex) reference-
-// frame render has been durably filed onto the project scene's
-// `referenceImageId` (#1760 Phase 1b). socket.js bridges it to
-// `music-video:scene-image` on Socket.IO so the director scene board updates
+// emitted by `musicVideoSceneImageHook` / `musicVideoSceneVideoHook` once an
+// async (local/Codex) reference-frame render or i2v scene clip has been durably
+// filed onto the project scene's `referenceImageId` / `videoHistoryId` (#1760
+// Phase 1b / Phase 1). socket.js bridges them to `music-video:scene-image` /
+// `music-video:scene-video` on Socket.IO so the director scene board updates
// reactively without a refetch — the durable, hook-driven counterpart to the
-// synchronous external-SD-API lane (which returns the filename inline and lets
-// the client PATCH `referenceImageId` directly).
+// synchronous external-SD-API lane (which returns the image filename inline and
+// lets the client PATCH `referenceImageId` directly; video renders always ride
+// the queue, so the clip attach is hook-only).
export const musicVideoEvents = new EventEmitter();
diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.js
new file mode 100644
index 0000000000..df119d7cdf
--- /dev/null
+++ b/server/services/musicVideoSceneVideoHook.js
@@ -0,0 +1,121 @@
+/**
+ * Music Video scene i2v-clip attach hook (issue #1760, Phase 1).
+ *
+ * Subscribes to mediaJobEvents and, for each completed VIDEO job that carries
+ * `params.musicVideo`, files the resulting history id onto that project scene's
+ * `videoHistoryId` — server-side, independent of any mounted client. This is
+ * the i2v counterpart to the Phase 1b reference-frame hook
+ * (`musicVideoSceneImageHook`): a scene's video is generated from its chosen
+ * reference frame via the video route's `image` (i2v) mode, and a long local/
+ * Codex render that completes after the director navigated away, refreshed, or
+ * moved on still lands on the scene (otherwise the clip reaches the video
+ * history but the scene link is lost).
+ *
+ * Video jobs always ride the mediaJobQueue this hook listens to (there is no
+ * synchronous video lane), so — unlike the image hook — there's no inline-attach
+ * fallback to mirror; every scene clip lands through here.
+ *
+ * The video history record's id IS the job id (see videoGen/local.js: meta.id =
+ * jobId), and the `videoGenEvents` 'completed' payload the queue stores as
+ * `job.result` carries it as `generationId`. We read `job.result.generationId`
+ * and fall back to `job.id` so a runtime that doesn't echo the field still
+ * attaches the right clip.
+ *
+ * `updateScene` routes through the project store dispatcher, so the attach also
+ * emits a `musicVideoProject` record-updated event — the new `videoHistoryId`
+ * propagates to subscribed sync peers exactly like a hand edit. On success the
+ * hook emits `musicVideoEvents` 'scene-video', 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.
+ */
+
+import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { updateScene } from './musicVideo/projects.js';
+import { musicVideoEvents } from './musicVideo/events.js';
+import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
+
+// Serialize attaches per PROJECT — same rationale as the reference-frame hook:
+// two scene clips for one project completing close together would otherwise
+// both load→modify→save the single project record (file backend) and the later
+// write would clobber the earlier scene's `videoHistoryId`. Different projects
+// still attach concurrently. (Shared per-key queue primitive, #1791.)
+const serializePerProject = createKeyCachedQueue();
+
+// Newest render (by job `queuedAt`) attached per scene, so an OLDER clip that
+// completes AFTER a newer regenerate can't overwrite the newer one. The GPU
+// lane is FIFO, but a render kicked off from another client (or after a refresh
+// cleared the local spinner) can complete out of order. Keyed
+// `${projectId}:${sceneId}` → queuedAt ISO; read + written inside the
+// per-project serialize section so it never races. In-memory best-effort.
+const latestAttachedAt = new Map();
+
+let completedHandler = null;
+
+export function initMusicVideoSceneVideoHook() {
+ // Idempotent: a stray double-init (test reload, future refactor) would
+ // otherwise register two listeners and double-file every completed clip.
+ 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 !== 'video') return;
+ const tag = job.params?.musicVideo;
+ if (!tag?.projectId || !tag.sceneId) return;
+ // History id = the completed video job's id. The videoGenEvents 'completed'
+ // payload (stored as job.result) echoes it as generationId; fall back to
+ // job.id so a runtime that omits the field still attaches correctly.
+ const videoHistoryId = (typeof job.result?.generationId === 'string' && job.result.generationId)
+ || (typeof job.id === 'string' ? job.id : null);
+ if (!videoHistoryId) 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 clip.
+ // 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, { videoHistoryId });
+ 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-video hook failed for ${videoHistoryId} → ${projectId}/${sceneId}: ${err?.message || String(err)}`);
+ return null;
+ });
+
+ if (updated) {
+ musicVideoEvents.emit('scene-video', { projectId, sceneId, videoHistoryId });
+ console.log(`🎬 music-video scene clip ${projectId.slice(0, 8)}/${sceneId} ← ${videoHistoryId.slice(0, 8)}`);
+ }
+ })().catch((err) => {
+ // Last-resort net for synchronous throws (unexpected job shape, etc).
+ console.log(`⚠️ music-video scene-video hook crashed: ${err?.message || err}`);
+ });
+ };
+
+ mediaJobEvents.on('completed', completedHandler);
+ console.log('🎬 Music Video scene-video 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;
+ }
+ serializePerProject.clear();
+ latestAttachedAt.clear();
+ },
+};
diff --git a/server/services/musicVideoSceneVideoHook.test.js b/server/services/musicVideoSceneVideoHook.test.js
new file mode 100644
index 0000000000..1ed9ae2db1
--- /dev/null
+++ b/server/services/musicVideoSceneVideoHook.test.js
@@ -0,0 +1,129 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+// Mock the project store so the hook's tag-decode + serialize + emit 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('./musicVideo/projects.js', () => ({ updateScene }));
+
+const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
+const { musicVideoEvents } = await import('./musicVideo/events.js');
+const hook = await import('./musicVideoSceneVideoHook.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: 'mv-1', sceneId: 'mvs-1', ...over });
+// A completed video job: the queue stores the videoGenEvents 'completed' payload
+// as job.result, which echoes the history id as generationId.
+const completedVideoJob = ({ params = {}, id = 'vid-abc', generationId, queuedAt } = {}) => ({
+ kind: 'video', id, params,
+ result: { generationId: generationId ?? id, filename: `${id}.mp4`, path: `/data/videos/${id}.mp4` },
+ ...(queuedAt ? { queuedAt } : {}),
+});
+
+describe('musicVideoSceneVideoHook', () => {
+ let emitted;
+ const capture = (data) => emitted.push(data);
+
+ beforeEach(() => {
+ hook.__testing.reset();
+ hook.initMusicVideoSceneVideoHook();
+ updateScene.mockReset();
+ updateScene.mockImplementation(async (projectId, sceneId, patch) => ({ sceneId, ...patch }));
+ emitted = [];
+ musicVideoEvents.on('scene-video', capture);
+ });
+
+ afterEach(() => {
+ hook.__testing.reset();
+ musicVideoEvents.off('scene-video', capture);
+ });
+
+ it('attaches the clip history id and emits scene-video for a musicVideo-tagged video job', async () => {
+ mediaJobEvents.emit('completed', completedVideoJob({
+ params: { musicVideo: tag(), prompt: 'a neon skyline dolly' }, id: 'vid-abc',
+ }));
+ await waitFor(() => emitted.length > 0);
+ expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'vid-abc' });
+ expect(emitted[0]).toEqual({ projectId: 'mv-1', sceneId: 'mvs-1', videoHistoryId: 'vid-abc' });
+ });
+
+ it('falls back to job.id when the result omits generationId', async () => {
+ mediaJobEvents.emit('completed', { kind: 'video', id: 'vid-xyz', params: { musicVideo: tag() }, result: { filename: 'vid-xyz.mp4' } });
+ await waitFor(() => emitted.length > 0);
+ expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'vid-xyz' });
+ expect(emitted[0].videoHistoryId).toBe('vid-xyz');
+ });
+
+ it('ignores a completed job with no musicVideo tag', async () => {
+ mediaJobEvents.emit('completed', completedVideoJob({ params: { prompt: 'plain video-gen render' } }));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ expect(emitted).toHaveLength(0);
+ });
+
+ it('ignores a non-video job kind (the image hook owns those)', async () => {
+ mediaJobEvents.emit('completed', { kind: 'image', id: 'img1', params: { musicVideo: tag() }, result: { filename: 'img1.png' } });
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ expect(emitted).toHaveLength(0);
+ });
+
+ it('skips a tag missing projectId or sceneId', async () => {
+ mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: { projectId: 'mv-1' } } }));
+ mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: { sceneId: 'mvs-1' } } }));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(updateScene).not.toHaveBeenCalled();
+ expect(emitted).toHaveLength(0);
+ });
+
+ it('does not emit (or 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', completedVideoJob({ params: { musicVideo: tag() } }));
+ await waitFor(() => updateScene.mock.calls.length > 0);
+ await new Promise((r) => setTimeout(r, 20));
+ expect(emitted).toHaveLength(0);
+ });
+
+ it('does not let an older render (earlier queuedAt) overwrite a newer clip on the same scene', async () => {
+ mediaJobEvents.emit('completed', completedVideoJob({
+ params: { musicVideo: tag() }, id: 'new', queuedAt: '2026-06-29T00:00:02.000Z',
+ }));
+ await waitFor(() => updateScene.mock.calls.length > 0);
+ mediaJobEvents.emit('completed', completedVideoJob({
+ params: { musicVideo: tag() }, id: 'old', queuedAt: '2026-06-29T00:00:01.000Z',
+ }));
+ await new Promise((r) => setTimeout(r, 30));
+ expect(updateScene).toHaveBeenCalledTimes(1);
+ expect(updateScene).toHaveBeenCalledWith('mv-1', 'mvs-1', { videoHistoryId: 'new' });
+ expect(emitted.map((e) => e.videoHistoryId)).toEqual(['new']);
+ });
+
+ 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({ videoHistoryId: 'a' }); };
+ }))
+ .mockImplementationOnce(async () => { order.push('start-2'); return { videoHistoryId: 'b' }; });
+
+ mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: tag({ sceneId: 'mvs-1' }) }, id: 'a' }));
+ mediaJobEvents.emit('completed', completedVideoJob({ params: { musicVideo: tag({ sceneId: 'mvs-2' }) }, 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']);
+ });
+});
diff --git a/server/services/socket.js b/server/services/socket.js
index 3b09d58f42..0dc767cd2e 100644
--- a/server/services/socket.js
+++ b/server/services/socket.js
@@ -699,6 +699,12 @@ function setupMusicVideoEventForwarding() {
musicVideoEvents.on('scene-image', (data) => {
if (ioInstance) ioInstance.emit('music-video:scene-image', data);
});
+ // A scene i2v clip filed durably by musicVideoSceneVideoHook — bridge it so
+ // the board picks up the resulting `videoHistoryId` without a refetch
+ // (#1760 Phase 1).
+ musicVideoEvents.on('scene-video', (data) => {
+ if (ioInstance) ioInstance.emit('music-video:scene-video', data);
+ });
}
let aiStatusForwardingSetup = false;