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

simplify(issue-1760): ride the shared media-job hook factory for the scene-video lane

[._.]/ Adam Eivy634e86fcea9e
diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsx
index b418fbef83..bc08d74068 100644
--- a/client/src/pages/MusicVideo.jsx
+++ b/client/src/pages/MusicVideo.jsx
@@ -184,11 +184,12 @@ export default function MusicVideo() {
// - 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).
+ // - video-gen:completed / video-gen:failed / video-gen:canceled — the job's
+ // terminal events; clear the spinner by correlating generationId → sceneId.
+ // A queued-cancel emits only :canceled (no :failed), so without that
+ // handler the spinner would stick; a running-cancel emits :failed then
+ // :canceled, so 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);
@@ -229,13 +230,25 @@ export default function MusicVideo() {
settle(data, !owned);
if (owned && !failTimers.has(jobId)) armFailToast(jobId);
};
+ // Queued-cancel emits no *:failed; running-cancel emits failed then this.
+ // Either way clear the spinner and cancel any pending failure toast.
+ const onCanceled = (data) => {
+ const jobId = data?.generationId || data?.jobId;
+ if (jobId) {
+ const t = failTimers.get(jobId);
+ if (t) { clearTimeout(t); failTimers.delete(jobId); }
+ }
+ settle(data, false);
+ };
socket.on('music-video:scene-video', onSceneVideo);
socket.on('video-gen:completed', onCompleted);
socket.on('video-gen:failed', onFailed);
+ socket.on('video-gen:canceled', onCanceled);
return () => {
socket.off('music-video:scene-video', onSceneVideo);
socket.off('video-gen:completed', onCompleted);
socket.off('video-gen:failed', onFailed);
+ socket.off('video-gen:canceled', onCanceled);
for (const t of failTimers.values()) clearTimeout(t);
failTimers.clear();
};
diff --git a/server/services/mediaJobImageHook.js b/server/services/mediaJobImageHook.js
index 8138e4ba95..571ae33b11 100644
--- a/server/services/mediaJobImageHook.js
+++ b/server/services/mediaJobImageHook.js
@@ -1,16 +1,19 @@
/**
* createMediaJobImageHook — shared tag-dispatch scaffold for the media-job
- * scene-image completion hooks (#1791).
+ * scene-asset completion hooks (#1791, generalized to video in #1760 Phase 1).
*
- * Three completion hooks (writers-room #1363, catalog #1359, music-video #1760)
- * each subscribe to `mediaJobEvents 'completed'` and do the same shape of work:
- * ignore non-image jobs, decode a destination tag off `job.params`, validate its
- * fields, attach the rendered filename onto a record (serialized per-key so two
- * renders for the same record can't clobber each other), and — for the
- * scene-frame hooks — drop an out-of-order older render so it can't overwrite a
- * newer frame. This factory owns that copy-pasted skeleton so each hook becomes
- * a small config; a future "attach a render to record X" feature is a new config
- * object, not a 4th hand-wired listener.
+ * Four completion hooks (writers-room #1363, catalog #1359, music-video scene
+ * image #1760 Phase 1b, music-video scene video #1760 Phase 1) each subscribe to
+ * `mediaJobEvents 'completed'` and do the same shape of work: ignore jobs of the
+ * wrong `kind`, decode a destination tag off `job.params`, validate its fields,
+ * attach the rendered asset (an image filename or a video history id) onto a
+ * record (serialized per-key so two renders for the same record can't clobber
+ * each other), and — for the scene-frame hooks — drop an out-of-order older
+ * render so it can't overwrite a newer one. This factory owns that copy-pasted
+ * skeleton so each hook becomes a small config; a new "attach a render to record
+ * X" feature is a new config object, not another hand-wired listener. The job
+ * `kind` and the attached-value extraction are config knobs (`kind`,
+ * `extractResult`) so the scaffold covers both image and video jobs.
*
* The shared skeleton this owns:
* - the idempotent init (a stray double-init must not double-register the
@@ -67,6 +70,19 @@ export function createMediaJobImageHook(config) {
// log (e.g. `workId/sceneId`), so a "render didn't attach" line is traceable
// to a specific record the way each hand-written hook's log used to be.
describe = null,
+ // The media-job kind this hook attaches. Defaults to 'image' (the three
+ // scene-image hooks); the music-video i2v hook (#1760) passes 'video' to
+ // ride this same scaffold for a different job kind.
+ kind = 'image',
+ // Pull the fields to merge into `ctx` off a completed job, or return null to
+ // ignore it. The default surfaces the rendered image filename as
+ // `ctx.filename` (string-required) — the shape the three image hooks consume.
+ // The video hook overrides it to surface `ctx.videoHistoryId` (the clip's
+ // history id) instead, so each hook's attach/onAttached reads its own field.
+ extractResult = (job) => {
+ const f = job.result?.filename;
+ return (f && typeof f === 'string') ? { filename: f } : null;
+ },
} = config;
const serialize = createKeyCachedQueue();
@@ -74,22 +90,22 @@ export function createMediaJobImageHook(config) {
let completedHandler = null;
- // Decode the job into the hook's identity context, or null to ignore it.
- // Shared across the completed path (filename required) so the kind/tag/field
- // guards live in one place.
+ // Decode the job into the hook's identity context, or null to ignore it, so
+ // the kind/tag/result guards live in one place (the result fields are pulled
+ // by the configurable `extractResult`).
function decode(job) {
- if (!job || job.kind !== 'image') return null;
+ if (!job || job.kind !== kind) return null;
const tag = job.params?.[tagKey];
if (!tag) return null;
const identity = identify(tag, job);
if (!identity) return null;
- const filename = job.result?.filename;
- if (!filename || typeof filename !== 'string') return null;
+ const fields = extractResult(job);
+ if (!fields) return null;
// Normalize queuedAt once here so the guard below AND any consumer's attach
// (e.g. catalog's portrait guard) read the same `ctx.queuedAt` instead of
// re-deriving it.
const queuedAt = typeof job.queuedAt === 'string' ? job.queuedAt : null;
- return { ...identity, job, tag, filename, queuedAt };
+ return { ...identity, job, tag, ...fields, queuedAt };
}
function init() {
@@ -117,7 +133,10 @@ export function createMediaJobImageHook(config) {
return r;
}).catch((err) => {
const where = describe ? ` → ${describe(ctx)}` : '';
- console.log(`⚠️ ${label} hook failed for ${ctx.filename}${where}: ${err?.message || String(err)}`);
+ // `ctx.filename` is the image lanes' attached value; the video lane has
+ // no filename (it attaches a history id), so fall back to the routing
+ // string from `describe` for a still-traceable line.
+ console.log(`⚠️ ${label} hook failed for ${ctx.filename || 'render'}${where}: ${err?.message || String(err)}`);
return null;
});
diff --git a/server/services/mediaJobImageHook.test.js b/server/services/mediaJobImageHook.test.js
index 42d2e170ec..beea206f60 100644
--- a/server/services/mediaJobImageHook.test.js
+++ b/server/services/mediaJobImageHook.test.js
@@ -136,4 +136,25 @@ describe('createMediaJobImageHook', () => {
await waitFor(() => h.attach.mock.calls.length > 1);
expect(h.attach).toHaveBeenCalledTimes(2);
});
+
+ it('config kind + extractResult ride the same scaffold for non-image jobs (video lane, #1760)', async () => {
+ h.hook.__testing.reset();
+ // A video-kind hook: it ignores image jobs and surfaces a custom ctx field
+ // from a custom extractor (the music-video i2v hook's exact shape).
+ h = makeHook({
+ kind: 'video',
+ extractResult: (j) => {
+ const id = (typeof j.result?.generationId === 'string' && j.result.generationId) || j.id;
+ return id ? { videoHistoryId: id } : null;
+ },
+ });
+ h.hook.init();
+ // An image-kind job is ignored by a kind:'video' hook.
+ mediaJobEvents.emit('completed', { kind: 'image', id: 'i', params: { test: tag() }, result: { filename: 'f.png' } });
+ // A video job attaches via extractResult → ctx.videoHistoryId (falls back to job.id).
+ mediaJobEvents.emit('completed', { kind: 'video', id: 'vid-1', params: { test: tag() }, result: { generationId: 'vid-1' } });
+ await waitFor(() => h.onAttached.mock.calls.length > 0);
+ expect(h.attach).toHaveBeenCalledTimes(1);
+ expect(h.attach.mock.calls[0][0]).toMatchObject({ recordId: 'r1', sceneId: 's1', videoHistoryId: 'vid-1' });
+ });
});
diff --git a/server/services/musicVideoSceneVideoHook.js b/server/services/musicVideoSceneVideoHook.js
index df119d7cdf..6356ae4b9e 100644
--- a/server/services/musicVideoSceneVideoHook.js
+++ b/server/services/musicVideoSceneVideoHook.js
@@ -3,119 +3,74 @@
*
* 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
+ * `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).
+ * 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.
+ * fallback; every scene clip lands through here.
*
- * The video history record's id IS the job id (see videoGen/local.js: meta.id =
+ * The video history record's id IS the job id (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.
+ * `job.result` carries it as `generationId`. `extractResult` reads
+ * `job.result.generationId` and falls 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.
+ * 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) — generalized to the video
+ * `kind` in #1760 Phase 1. This file is just the music-video-video config,
+ * structurally identical to its scene-image sibling. Mounted once at server boot
+ * from server/index.js (after the media job queue is running).
*/
-import { mediaJobEvents } from './mediaJobQueue/index.js';
+import { createMediaJobImageHook } from './mediaJobImageHook.js';
import { updateScene } from './musicVideo/projects.js';
import { musicVideoEvents } from './musicVideo/events.js';
-import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
-
-// Serialize attaches per PROJECT — 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;
+const hook = createMediaJobImageHook({
+ label: 'music-video scene-video',
+ initLog: '🎬 Music Video scene-video hook initialized',
+ kind: 'video',
+ tagKey: 'musicVideo',
+ // 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.
+ extractResult: (job) => {
+ const videoHistoryId = (typeof job.result?.generationId === 'string' && job.result.generationId)
+ || (typeof job.id === 'string' ? job.id : null);
+ return videoHistoryId ? { videoHistoryId } : null;
+ },
+ // 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 clips for the same project completing close
+ // together would otherwise both load→modify→save the one project record (file
+ // backend) and the later write would clobber the earlier scene's
+ // `videoHistoryId`. Different projects still attach concurrently.
+ serializeKey: ({ projectId }) => projectId,
+ // Newest-render-wins per scene: a clip kicked off from another client (or after
+ // a refresh cleared the local spinner) can complete out of order — drop an
+ // older render so it can't overwrite a newer clip.
+ sceneKey: ({ projectId, sceneId }) => `${projectId}:${sceneId}`,
+ describe: ({ projectId, sceneId }) => `${projectId}/${sceneId}`,
+ attach: ({ projectId, sceneId, videoHistoryId }) =>
+ updateScene(projectId, sceneId, { videoHistoryId }),
+ onAttached: ({ projectId, sceneId, videoHistoryId }) => {
+ musicVideoEvents.emit('scene-video', { projectId, sceneId, videoHistoryId });
+ console.log(`🎬 music-video scene clip ${projectId.slice(0, 8)}/${sceneId} ← ${videoHistoryId.slice(0, 8)}`);
+ },
+});
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');
+ hook.init();
}
-// Test-only reset so suites that re-init can do so cleanly. Removes the
-// previously registered listener so re-init doesn't leak handlers.
-export const __testing = {
- reset: () => {
- if (completedHandler) {
- mediaJobEvents.off('completed', completedHandler);
- completedHandler = null;
- }
- serializePerProject.clear();
- latestAttachedAt.clear();
- },
-};
+// Test-only reset so suites that re-init can do so cleanly.
+export const __testing = hook.__testing;