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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add FableLoom scene video generation
[._.]/ Adam Eivy80a2e78e254a
diff --git a/client/src/components/fableloom/LoomNodeEditor.jsx b/client/src/components/fableloom/LoomNodeEditor.jsxindex b6d5187a6e..7ba2e50449 100644--- a/client/src/components/fableloom/LoomNodeEditor.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.jsx@@ -1,7 +1,7 @@/*** FableLoom scene editor — the side panel for the selected node: title/prose,- * ending flag + label, the intent-transition list, the scene image (prompt +- * queued render via the shared image-gen lane), and the AI branch action.+ * ending flag + label, the intent-transition list, scene image/video prompts+ * and previews via the shared local media lanes, and the AI branch action.** Fields save on blur (silent PATCH, skipped when unchanged; the server* returns the full loom, which the parent folds into state). Paths save one@@ -12,7 +12,7 @@*/import { useEffect, useMemo, useState } from 'react';-import { GitBranch, ImagePlus, Loader2, Trash2 } from 'lucide-react';+import { GitBranch, ImagePlus, Loader2, Trash2, Video } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import { FormField } from '../ui/FormField.jsx';@@ -21,7 +21,7 @@ import { useAsyncAction } from '../../hooks/useAsyncAction';import { useConfirmDelete } from '../../hooks/useConfirmDelete';import {addLoomTransition, branchLoomNode, deleteLoomNode, deleteLoomTransition,- generateImage, updateLoomNode, updateLoomTransition,+ generateImage, generateVideo, updateLoomNode, updateLoomTransition,} from '../../services/api';import { fieldClass, labelClass, sceneFieldClass } from './fieldStyles';import { isTeleplayFormat } from './loomFormats';@@ -55,6 +55,7 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCltitle: node.title || '',prose: node.prose || '',imagePrompt: node.imagePrompt || '',+ videoPrompt: node.videoPrompt || '',isEnding: !!node.isEnding,endingLabel: node.endingLabel || '',transitions: (node.transitions || []).map(toRow),@@ -168,6 +169,27 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCltoast.success('Scene render queued — it will attach when it completes');}, { errorMessage: 'Could not queue the render' });+ const [runGenerateVideo, videoRendering] = useAsyncAction(async () => {+ const prompt = form.videoPrompt.trim() || form.imagePrompt.trim();+ if (!prompt) {+ toast.error('Write a video or image prompt first');+ return;+ }+ // Keep the motion prompt independently editable, while allowing existing+ // image-only scenes to render a useful first clip without a migration or a+ // second required authoring step. A rendered still seeds image-to-video.+ await saveField('videoPrompt', form.videoPrompt.trim());+ await generateVideo({+ prompt: loom.styleNotes ? `${prompt}\n\nStyle: ${loom.styleNotes}` : prompt,+ backend: 'local',+ mode: node.image ? 'image' : 'text',+ ...(node.image ? { sourceImageFile: node.image } : {}),+ disableAudio: true,+ fableLoom: JSON.stringify({ loomId: loom.id, episodeId: episode.id, nodeId: node.id }),+ });+ toast.success('Scene video queued — it will attach when it completes');+ }, { errorMessage: 'Could not queue the video render' });+const handleDelete = async () => {const updated = await deleteLoomNode(loom.id, episode.id, node.id).catch(() => null);if (updated) {@@ -284,6 +306,40 @@ export default function LoomNodeEditor({ loom, episode, node, onLoomUpdate, onCl)}</div>+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-xs font-medium text-port-text-muted">Scene video</span>+ <button+ type="button"+ onClick={runGenerateVideo}+ disabled={videoRendering || aiBlocked}+ className="flex items-center gap-1 text-xs text-port-accent hover:underline disabled:opacity-50"+ >+ {videoRendering ? <Loader2 size={12} className="animate-spin" /> : <Video size={12} />}+ Generate video+ </button>+ </div>+ <textarea+ rows={2}+ className={fieldClass}+ placeholder="Motion prompt (falls back to the image prompt)"+ aria-label="Video prompt"+ value={form.videoPrompt}+ onChange={(e) => setForm((p) => ({ ...p, videoPrompt: e.target.value }))}+ onBlur={() => saveField('videoPrompt', form.videoPrompt)}+ />+ {node.videoHistoryId && (+ <video+ controls+ playsInline+ preload="metadata"+ src={`/data/videos/${encodeURIComponent(node.videoHistoryId)}.mp4`}+ aria-label={form.title || 'Scene video'}+ className="mt-2 rounded max-w-full max-h-56 bg-black"+ />+ )}+ </div>+<div><div className="flex items-center justify-between mb-1"><span className="text-xs font-medium text-port-text-muted">diff --git a/client/src/components/fableloom/LoomNodeEditor.test.jsx b/client/src/components/fableloom/LoomNodeEditor.test.jsxindex a6a99cb0e3..dbbb6b3850 100644--- a/client/src/components/fableloom/LoomNodeEditor.test.jsx+++ b/client/src/components/fableloom/LoomNodeEditor.test.jsx@@ -8,13 +8,14 @@ vi.mock('../../services/api', () => ({deleteLoomNode: vi.fn(),deleteLoomTransition: vi.fn(),generateImage: vi.fn(),+ generateVideo: vi.fn(),updateLoomNode: vi.fn(),updateLoomTransition: vi.fn(),}));vi.mock('../MediaImage', () => ({ default: () => null }));import {- addLoomTransition, deleteLoomTransition, updateLoomNode, updateLoomTransition,+ addLoomTransition, deleteLoomTransition, generateVideo, updateLoomNode, updateLoomTransition,} from '../../services/api';import LoomNodeEditor from './LoomNodeEditor';@@ -22,7 +23,7 @@ const loom = { id: 'loom-1', name: 'Example Story', format: 'prose', styleNotes:// One scene with a single existing path, plus a second scene to point at.const makeNodes = (transitions) => ([- { id: 'n1', title: 'The Gate', prose: 'You stand before it.', transitions },+ { id: 'n1', title: 'The Gate', prose: 'You stand before it.', image: 'scene.png', imagePrompt: 'an ancient gate', videoPrompt: 'the gate slowly opens', transitions },{ id: 'n2', title: 'Inside', prose: 'Torchlight.', transitions: [] },]);@@ -105,3 +106,48 @@ describe('LoomNodeEditor paths', () => {expect(screen.getByText('Paths out (0)')).toBeInTheDocument();});});++describe('LoomNodeEditor scene media', () => {+ it('queues a local video from the scene prompt and rendered still', async () => {+ const user = userEvent.setup();+ generateVideo.mockResolvedValue({ jobId: 'video-1', status: 'queued' });+ renderEditor();++ await user.click(screen.getByRole('button', { name: 'Generate video' }));++ await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));+ expect(generateVideo).toHaveBeenCalledWith({+ prompt: 'the gate slowly opens',+ backend: 'local',+ mode: 'image',+ sourceImageFile: 'scene.png',+ disableAudio: true,+ fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'n1' }),+ });+ });++ it('falls back to the image prompt for a scene without a video prompt', async () => {+ const user = userEvent.setup();+ generateVideo.mockResolvedValue({ jobId: 'video-2', status: 'queued' });+ const nodes = makeNodes([]).map((node) => node.id === 'n1'+ ? { ...node, imagePrompt: 'a lantern in fog', image: null, videoPrompt: '' }+ : node);+ render(+ <LoomNodeEditor+ loom={loom}+ episode={{ id: 'ep-1', nodes }}+ node={nodes[0]}+ onLoomUpdate={vi.fn()}+ onClearSelection={() => {}}+ />,+ );++ await user.click(screen.getByRole('button', { name: 'Generate video' }));++ await waitFor(() => expect(generateVideo).toHaveBeenCalledTimes(1));+ expect(generateVideo).toHaveBeenCalledWith(expect.objectContaining({+ prompt: 'a lantern in fog', backend: 'local', mode: 'text', fableLoom: expect.any(String),+ }));+ expect(generateVideo.mock.calls[0][0]).not.toHaveProperty('sourceImageFile');+ });+});diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex 539821c4da..4a4767584b 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -120,7 +120,7 @@ ends, dangling transitions, unreachable endings, duplicate/empty intents —and renders in the editor's Structure panel via`GET /api/fableloom/:id/episodes/:episodeId/validate`.-## Scene images+## Scene mediaEach node carries an `imagePrompt`; **Generate** posts to the shared`/api/image-gen/generate` queue with a `fableLoom: { loomId, episodeId,@@ -130,6 +130,13 @@ the node durably — even if the editor unmounted mid-render — withnewest-render-wins per node. The loom's `styleNotes` are appended to theprompt for a consistent look.+Each node also carries an optional `videoPrompt` and `videoHistoryId`. **Generate+video** posts to the shared local `/api/video-gen` queue with the same+destination tag. If the node already has a rendered image, it is sent as the+video's first-frame conditioning image; otherwise the render is text-to-video.+The completion hook (`server/services/fableLoomSceneVideoHook.js`) files the+finished history id onto the node durably, with newest-render-wins per node.+## Storage`fableloom_stories` (db-primary; one row per loom, full record in `data`diff --git a/server/lib/fableLoomLimits.js b/server/lib/fableLoomLimits.jsindex 6f73fe2661..620cec6426 100644--- a/server/lib/fableLoomLimits.js+++ b/server/lib/fableLoomLimits.js@@ -23,6 +23,7 @@ export const LOOM_LIMITS = Object.freeze({NODE_TITLE_MAX: 300,PROSE_MAX: 20000,IMAGE_PROMPT_MAX: 2000,+ VIDEO_PROMPT_MAX: 4000,ENDING_LABEL_MAX: 200,TRANSITIONS_MAX: 12,INTENT_MAX: 120,diff --git a/server/lib/fableLoomValidation.js b/server/lib/fableLoomValidation.jsindex a63e8acad8..fbc39c0be4 100644--- a/server/lib/fableLoomValidation.js+++ b/server/lib/fableLoomValidation.js@@ -122,6 +122,7 @@ const nodeFields = {title: z.string().max(LOOM_LIMITS.NODE_TITLE_MAX).optional(),prose: z.string().max(LOOM_LIMITS.PROSE_MAX).optional(),imagePrompt: z.string().max(LOOM_LIMITS.IMAGE_PROMPT_MAX).optional(),+ videoPrompt: z.string().max(LOOM_LIMITS.VIDEO_PROMPT_MAX).optional(),isEnding: z.boolean().optional(),endingLabel: z.string().max(LOOM_LIMITS.ENDING_LABEL_MAX).optional(),pos: z.object({ x: z.number(), y: z.number() }).nullable().optional(),diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex e1c79b4346..73ea8db809 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -3,9 +3,9 @@** CRUD for looms/episodes/nodes plus the AI lanes (weave/branch/feedback/review/play)* and the deterministic graph validation. Every AI endpoint is a direct- * user action in the same request (AI Provider Usage Policy). Scene images- * ride the existing `/api/image-gen/generate` queue with a `fableLoom`- * destination tag — there is no image endpoint here.+ * user action in the same request (AI Provider Usage Policy). Scene media+ * rides the shared image/video generation queues with a `fableLoom`+ * destination tag — there are no bespoke generation endpoints here.*/import { Router } from 'express';diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 4eabf1281f..37ca00589d 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -353,6 +353,24 @@ const generateBodySchema = z.object({sceneId: z.string().min(1).max(200),}).optional(),),+ // FableLoom scene-video render. The media-job completion hook files the+ // finished history id onto the tagged loom node, even if the editor has+ // unmounted. Video requests are multipart, so parse the JSON tag before+ // validation; the tag carries destination identity only.+ fableLoom: 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({+ loomId: z.string().min(1).max(200),+ episodeId: z.string().min(1).max(200),+ nodeId: z.string().min(1).max(200),+ }).optional(),+ ),// Federated media provider (#4348). When set, the render is submitted to// THIS registered peer instead of local hardware. Server-validated against// the per-peer allowlist, so naming a peer here cannot route work to one the@@ -920,6 +938,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {['LoRA weights', body.loraFilenames?.length],['chained chunks', body.chunks > 1],['the Grok backend', body.backend === 'grok'],+ ['a FableLoom scene tag', body.fableLoom],// A loose reference (#4874) is a per-runtime CAPABILITY, and this side// cannot see which runtime the peer will pick — nor can an older peer even// parse the field, which its wire schema would strip on the way in. Sending@@ -1037,6 +1056,7 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {sourceImagePath,uploadedTempPath,...(body.musicVideo ? { musicVideo: body.musicVideo } : {}),+ ...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),});return res.json({ jobId, generationId: jobId, filename: `${jobId}.mp4`, model: 'grok', mode: 'grok', status, position });}@@ -1107,6 +1127,9 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {// 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 } : {}),+ // FableLoom scene attach tag. Rides into persisted job.params so the+ // completion hook can file the clip even if the editor unmounted.+ ...(body.fableLoom ? { fableLoom: body.fableLoom } : {}),});// Match the legacy response shape (jobId, generationId, filename, model,// mode) so existing client code keeps working; add status+position fordiff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex 6c0394b45b..77cf5098ef 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -998,6 +998,23 @@ describe('videoGen routes', () => {}));});+ it('forwards a fableLoom i2v tag into job.params alongside the resolved frame', async () => {+ const r = await request(app).post('/api/video-gen/').send({+ prompt: 'the gate slowly opens',+ mode: 'image',+ sourceImageFile: 'scene-image.png',+ fableLoom: JSON.stringify({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' }),+ });+ expect(r.status).toBe(200);+ expect(mediaJobQueue.enqueueJob).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'video',+ params: expect.objectContaining({+ sourceImagePath: '/mock/images/scene-image.png',+ fableLoom: { loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1' },+ }),+ }));+ });+it('rejects a musicVideo i2v render when the reference frame cannot be resolved (no silent t2v)', async () => {// A stale/deleted gallery file resolves to null (mustExist defaults true).resolveGalleryImage.mockReturnValueOnce(null);diff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 38976c6a33..f7b8df5207 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -121,6 +121,7 @@ import { initUniverseBuilderCollectionHook } from './universeBuilderCollectionHoimport { initCatalogImageAttachHook } from './catalogImageAttachHook.js';import { initWritersRoomSceneImageHook } from './writersRoomSceneImageHook.js';import { initFableLoomSceneImageHook } from './fableLoomSceneImageHook.js';+import { initFableLoomSceneVideoHook } from './fableLoomSceneVideoHook.js';import { initMusicVideoSceneImageHook } from './musicVideoSceneImageHook.js';import { initMusicVideoSceneVideoHook } from './musicVideoSceneVideoHook.js';import { initCreativeDirectorMusicBedHook } from './creativeDirectorMusicBedHook.js';@@ -501,6 +502,9 @@ const initMediaJobDependentHooks = () => {// FableLoom scene-image hook — durably files a queued scene render onto its// loom episode's node on completion, even if the editor unmounted mid-render.initFableLoomSceneImageHook();+ // FableLoom scene-video hook — durably files a queued local clip onto its+ // loom episode's node on completion, even if the editor unmounted.+ initFableLoomSceneVideoHook();// Music Video scene-image hook — durably files a queued reference-frame// render onto its project scene's `referenceImageId` on completion, even if// the director board unmounted mid-render (#1760 Phase 1b).diff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.mdindex e0e6be8c3c..ee39f2e8df 100644--- a/server/services/fableLoom/README.md+++ b/server/services/fableLoom/README.md@@ -7,7 +7,7 @@ intent to a transition and moves them through the graph until an ending.| Module | Purpose ||---|---|-| `records.js` | Sanitizer + CRUD for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` for the media-job hook. |+| `records.js` | Sanitizer + CRUD for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` and `attachNodeVideo` for media-job hooks. || `weave.js` | AI ops via `runStagedLLM`: `weaveEpisode` (full graph), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; a tapped path resolves off the graph with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). || `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. || `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). |diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex 46b3e6c1e0..6bad1ce594 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -4,6 +4,7 @@ export {addNode,addNodeTransition,attachNodeImage,+ attachNodeVideo,createLoom,deleteEpisode,deleteLoom,diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex f801e4570c..21fef03036 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -3,9 +3,9 @@* transitions.** A loom is a branching-narrative story: episodes hold a directed graph of- * scene nodes; each node carries prose, an image prompt/render, and a list of- * intent-triggered transitions the play LLM matches free-text reader input- * against. All ids are server-minted. Every write funnels through+ * scene nodes; each node carries prose, image/video prompts and rendered media,+ * plus a list of intent-triggered transitions the play LLM matches free-text+ * reader input against. All ids are server-minted. Every write funnels through* `mutateLoom` (per-record write queue + full re-sanitize), so a malformed* mutation can never persist.*/@@ -31,6 +31,8 @@ export { LOOM_LIMITS };const isSafeImageFilename = (value) =>typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]*\.(png|jpg|jpeg|webp)$/i.test(value);+const isSafeVideoHistoryId = (value) =>+ typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(value);const nullableRef = (value) => (isStr(value) && value.trim() ? value.trim().slice(0, LOOM_LIMITS.REF_ID_MAX) : null);@@ -65,6 +67,8 @@ function sanitizeNode(raw) {imagePrompt: trimTo(raw.imagePrompt, LOOM_LIMITS.IMAGE_PROMPT_MAX),image: isSafeImageFilename(raw.image) ? raw.image : null,imageJobId: isStr(raw.imageJobId) && raw.imageJobId ? raw.imageJobId.slice(0, 200) : null,+ videoPrompt: trimTo(raw.videoPrompt, LOOM_LIMITS.VIDEO_PROMPT_MAX),+ videoHistoryId: isSafeVideoHistoryId(raw.videoHistoryId) ? raw.videoHistoryId : null,isEnding: raw.isEnding === true,// The format this scene's text is actually WRITTEN in — server-set, not// patchable. `null` means unknown (authored before the field existed, or@@ -365,7 +369,7 @@ export function deleteEpisode(loomId, episodeId) {// --- Nodes & transitions -----------------------------------------------------const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'isEnding', 'endingLabel', 'pos', 'transitions'];+const NODE_PATCH_FIELDS = ['title', 'prose', 'imagePrompt', 'videoPrompt', 'isEnding', 'endingLabel', 'pos', 'transitions'];export function addNode(loomId, episodeId, fields = {}) {return mutateLoom(loomId, (loom) => {@@ -497,3 +501,21 @@ export async function attachNodeImage(loomId, episodeId, nodeId, { filename, job}).catch(() => null);return updated?.episodes.find((e) => e.id === episodeId)?.nodes.find((n) => n.id === nodeId) ?? null;}++/**+ * Durable video attach for the media-job completion hook. Video history ids+ * are also the generated filenames under data/videos, but are kept as ids so+ * the node can use the same history/media conventions as other video surfaces.+ */+export async function attachNodeVideo(loomId, episodeId, nodeId, { videoHistoryId }) {+ if (!isValidLoomId(loomId) || !isSafeVideoHistoryId(videoHistoryId)) return null;+ const updated = await mutateLoom(loomId, (loom) => {+ const episode = loom.episodes.find((e) => e.id === episodeId);+ const node = episode?.nodes.find((n) => n.id === nodeId);+ if (!node) return null;+ node.videoHistoryId = videoHistoryId;+ episode.updatedAt = new Date().toISOString();+ return loom;+ }).catch(() => null);+ return updated?.episodes.find((e) => e.id === episodeId)?.nodes.find((n) => n.id === nodeId) ?? null;+}diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.jsindex 5f49ee069e..a74da45a9c 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -24,7 +24,7 @@ const getSeriesMock = vi.hoisted(() => vi.fn(async (id) => ({ id })));vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));const {- LOOM_LIMITS, addEpisode, addNode, addNodeTransition, attachNodeImage, createLoom,+ LOOM_LIMITS, addEpisode, addNode, addNodeTransition, attachNodeImage, attachNodeVideo, createLoom,deleteEpisode, deleteLoom, deleteNode, deleteNodeTransition, getLoom,listLooms, listLoomSummaries, sanitizeLoom, updateEpisode, updateLoom,updateNode, updateNodeTransition,@@ -416,3 +416,25 @@ describe('attachNodeImage', () => {expect(await attachNodeImage('loom-missing', episodeId, 'node-gone', { filename: 'x.png' })).toBeNull();});});++describe('attachNodeVideo', () => {+ it('files a completed video history id onto its node', async () => {+ const loom = await makeLoom();+ let updated = await addEpisode(loom.id, {});+ const episodeId = updated.episodes[0].id;+ updated = await addNode(loom.id, episodeId, { title: 'A' });+ const node = updated.episodes[0].nodes[0];++ const attached = await attachNodeVideo(loom.id, episodeId, node.id, { videoHistoryId: 'video-1' });+ expect(attached).toMatchObject({ id: node.id, videoHistoryId: 'video-1' });+ expect((await getLoom(loom.id)).episodes[0].nodes[0].videoHistoryId).toBe('video-1');+ });++ it('returns null when the target or history id is unsafe', async () => {+ const loom = await makeLoom();+ const updated = await addEpisode(loom.id, {});+ const episodeId = updated.episodes[0].id;+ expect(await attachNodeVideo(loom.id, episodeId, 'node-gone', { videoHistoryId: '../video' })).toBeNull();+ expect(await attachNodeVideo(loom.id, episodeId, 'node-gone', { videoHistoryId: 'video-1' })).toBeNull();+ });+});diff --git a/server/services/fableLoomSceneVideoHook.js b/server/services/fableLoomSceneVideoHook.jsnew file mode 100644index 0000000000..c52fc2261b--- /dev/null+++ b/server/services/fableLoomSceneVideoHook.js@@ -0,0 +1,41 @@+/**+ * FableLoom scene-video attach hook.+ *+ * Video renders always ride the media-job queue. When a queued local render+ * completes after the editor unmounted, this hook still files its history id+ * onto the scene node, matching the durable image attach path.+ */++import { createMediaJobImageHook } from './mediaJobImageHook.js';+import { attachNodeVideo } from './fableLoom/records.js';++const hook = createMediaJobImageHook({+ label: 'fableloom scene-video',+ initLog: '🎬 FableLoom scene-video hook initialized',+ kind: 'video',+ tagKey: 'fableLoom',+ extractResult: (job) => {+ const videoHistoryId = (typeof job.result?.generationId === 'string' && job.result.generationId)+ || (typeof job.id === 'string' ? job.id : null);+ return videoHistoryId ? { videoHistoryId } : null;+ },+ identify: (tag) => (tag?.loomId && tag.episodeId && tag.nodeId+ ? { loomId: tag.loomId, episodeId: tag.episodeId, nodeId: tag.nodeId }+ : null),+ serializeKey: ({ loomId }) => loomId,+ sceneKey: ({ loomId, episodeId, nodeId }) => `${loomId}:${episodeId}:${nodeId}`,+ describe: ({ loomId, nodeId }) => `${loomId.slice(0, 13)}/${nodeId.slice(0, 13)}`,+ attach: ({ loomId, episodeId, nodeId, videoHistoryId }) =>+ attachNodeVideo(loomId, episodeId, nodeId, { videoHistoryId }),+ onAttached: ({ loomId, nodeId, videoHistoryId }, result) => {+ if (!result) return;+ console.log(`🎬 fableloom scene video ${loomId.slice(0, 13)}/${nodeId.slice(0, 13)} ← ${videoHistoryId}`);+ },+});++export function initFableLoomSceneVideoHook() {+ hook.init();+}++// Test-only reset so suites that re-init can do so cleanly.+export const __testing = hook.__testing;diff --git a/server/services/fableLoomSceneVideoHook.test.js b/server/services/fableLoomSceneVideoHook.test.jsnew file mode 100644index 0000000000..2ae6f3398e--- /dev/null+++ b/server/services/fableLoomSceneVideoHook.test.js@@ -0,0 +1,56 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const attachNodeVideo = vi.fn(async (loomId, episodeId, nodeId, { videoHistoryId }) => ({+ id: nodeId, videoHistoryId,+}));+vi.mock('./fableLoom/records.js', () => ({ attachNodeVideo }));++const { mediaJobEvents } = await import('./mediaJobQueue/index.js');+const hook = await import('./fableLoomSceneVideoHook.js');++async function waitFor(predicate, { timeoutMs = 1000, intervalMs = 5 } = {}) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, intervalMs));+ }+ throw new Error('waitFor: predicate never became true');+}++const tag = (over = {}) => ({ loomId: 'loom-1', episodeId: 'ep-1', nodeId: 'node-1', ...over });+const completedVideoJob = ({ params = {}, id = 'video-1', generationId, queuedAt } = {}) => ({+ kind: 'video', id, params,+ result: { generationId: generationId ?? id, filename: `${id}.mp4` },+ ...(queuedAt ? { queuedAt } : {}),+});++describe('fableLoomSceneVideoHook', () => {+ beforeEach(() => {+ hook.__testing.reset();+ hook.initFableLoomSceneVideoHook();+ attachNodeVideo.mockClear();+ });++ afterEach(() => hook.__testing.reset());++ it('files a completed fableLoom-tagged video onto its node', async () => {+ mediaJobEvents.emit('completed', completedVideoJob({ params: { fableLoom: tag() } }));+ await waitFor(() => attachNodeVideo.mock.calls.length > 0);+ expect(attachNodeVideo).toHaveBeenCalledWith('loom-1', 'ep-1', 'node-1', { videoHistoryId: 'video-1' });+ });++ it('falls back to the queue job id when generationId is absent', async () => {+ mediaJobEvents.emit('completed', {+ kind: 'video', id: 'video-2', params: { fableLoom: tag() }, result: { filename: 'video-2.mp4' },+ });+ await waitFor(() => attachNodeVideo.mock.calls.length > 0);+ expect(attachNodeVideo.mock.calls[0][3]).toEqual({ videoHistoryId: 'video-2' });+ });++ it('ignores image jobs and videos without a complete destination tag', async () => {+ mediaJobEvents.emit('completed', { kind: 'image', id: 'image-1', params: { fableLoom: tag() }, result: { filename: 'image-1.png' } });+ mediaJobEvents.emit('completed', completedVideoJob({ params: { fableLoom: { loomId: 'loom-1' } } }));+ await new Promise((resolve) => setTimeout(resolve, 25));+ expect(attachNodeVideo).not.toHaveBeenCalled();+ });+});